ETH Price: $1,828.37 (+0.47%)

Transaction Decoder

Block:
21682378 at Jan-22-2025 08:20:35 PM +UTC
Transaction Fee:
0.00085101920578743 ETH $1.56
Gas Used:
93,565 Gas / 9.095486622 Gwei

Emitted Events:

291 HashConsensus.ReportReceived( refSlot=10895999, member=[Sender] 0x007de4a5f7bc37e2f26c0cb2e8a95006ee9b89b5, report=9AEF2A89918CA9AC431065D89CC8D01F5E75B744BDEF7B079CA6B398D2E9480A )
292 HashConsensus.ConsensusReached( refSlot=10895999, report=9AEF2A89918CA9AC431065D89CC8D01F5E75B744BDEF7B079CA6B398D2E9480A, support=5 )
293 OssifiableProxy.0xaed7d1a7a1831158dcda1e4214f5862f450bd3eb5721a5f322bf8c9fe1790b0a( 0xaed7d1a7a1831158dcda1e4214f5862f450bd3eb5721a5f322bf8c9fe1790b0a, 0x0000000000000000000000000000000000000000000000000000000000a6427f, 9aef2a89918ca9ac431065d89cc8d01f5e75b744bdef7b079ca6b398d2e9480a, 000000000000000000000000000000000000000000000000000000006791becb )

Account State Difference:

  Address   Before After State Difference Code
0x007DE4a5...6EE9B89b5
0.810389937373873767 Eth
Nonce: 3114
0.809538918168086337 Eth
Nonce: 3115
0.00085101920578743
0x0De4Ea01...8d5Bf5c6e
(Lido: Validators Exit Bus Oracle)
(Titan Builder)
12.128453143750208214 Eth12.128457822000208214 Eth0.00000467825
0x7FaDB635...De3df355a
(Lido: Validators Exit Bus Oracle Hash Consensus)

Execution Trace

HashConsensus.submitReport( slot=10895999, report=9AEF2A89918CA9AC431065D89CC8D01F5E75B744BDEF7B079CA6B398D2E9480A, consensusVersion=2 )
  • OssifiableProxy.STATICCALL( )
    • ValidatorsExitBusOracle.DELEGATECALL( )
    • OssifiableProxy.STATICCALL( )
      • ValidatorsExitBusOracle.DELEGATECALL( )
      • OssifiableProxy.063f36ad( )
        • ValidatorsExitBusOracle.submitConsensusReport( reportHash=9AEF2A89918CA9AC431065D89CC8D01F5E75B744BDEF7B079CA6B398D2E9480A, refSlot=10895999, deadline=1737604811 )
          submitReport[HashConsensus (ln:1326)]
          File 1 of 3: HashConsensus
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev External interface of AccessControl declared to support ERC165 detection.
           */
          interface IAccessControl {
              /**
               * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
               *
               * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
               * {RoleAdminChanged} not being emitted signaling this.
               *
               * _Available since v3.1._
               */
              event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
              /**
               * @dev Emitted when `account` is granted `role`.
               *
               * `sender` is the account that originated the contract call, an admin role
               * bearer except when using {AccessControl-_setupRole}.
               */
              event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
              /**
               * @dev Emitted when `account` is revoked `role`.
               *
               * `sender` is the account that originated the contract call:
               *   - if using `revokeRole`, it is the admin role bearer
               *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
               */
              event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
              /**
               * @dev Returns `true` if `account` has been granted `role`.
               */
              function hasRole(bytes32 role, address account) external view returns (bool);
              /**
               * @dev Returns the admin role that controls `role`. See {grantRole} and
               * {revokeRole}.
               *
               * To change a role's admin, use {AccessControl-_setRoleAdmin}.
               */
              function getRoleAdmin(bytes32 role) external view returns (bytes32);
              /**
               * @dev Grants `role` to `account`.
               *
               * If `account` had not been already granted `role`, emits a {RoleGranted}
               * event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               */
              function grantRole(bytes32 role, address account) external;
              /**
               * @dev Revokes `role` from `account`.
               *
               * If `account` had been granted `role`, emits a {RoleRevoked} event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               */
              function revokeRole(bytes32 role, address account) external;
              /**
               * @dev Revokes `role` from the calling account.
               *
               * Roles are often managed via {grantRole} and {revokeRole}: this function's
               * purpose is to provide a mechanism for accounts to lose their privileges
               * if they are compromised (such as when a trusted device is misplaced).
               *
               * If the calling account had been granted `role`, emits a {RoleRevoked}
               * event.
               *
               * Requirements:
               *
               * - the caller must be `account`.
               */
              function renounceRole(bytes32 role, address account) external;
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
          pragma solidity ^0.8.0;
          import "./IAccessControl.sol";
          /**
           * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
           */
          interface IAccessControlEnumerable is IAccessControl {
              /**
               * @dev Returns one of the accounts that have `role`. `index` must be a
               * value between 0 and {getRoleMemberCount}, non-inclusive.
               *
               * Role bearers are not sorted in any particular way, and their ordering may
               * change at any point.
               *
               * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
               * you perform all queries on the same block. See the following
               * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
               * for more information.
               */
              function getRoleMember(bytes32 role, uint256 index) external view returns (address);
              /**
               * @dev Returns the number of accounts that have `role`. Can be used
               * together with {getRoleMember} to enumerate all bearers of a role.
               */
              function getRoleMemberCount(bytes32 role) external view returns (uint256);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Provides information about the current execution context, including the
           * sender of the transaction and its data. While these are generally available
           * via msg.sender and msg.data, they should not be accessed in such a direct
           * manner, since when dealing with meta-transactions the account sending and
           * paying for execution may not be the actual sender (as far as an application
           * is concerned).
           *
           * This contract is only required for intermediate, library-like contracts.
           */
          abstract contract Context {
              function _msgSender() internal view virtual returns (address) {
                  return msg.sender;
              }
              function _msgData() internal view virtual returns (bytes calldata) {
                  return msg.data;
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
          pragma solidity ^0.8.0;
          import "./IERC165.sol";
          /**
           * @dev Implementation of the {IERC165} interface.
           *
           * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
           * for the additional interface id that will be supported. For example:
           *
           * ```solidity
           * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
           *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
           * }
           * ```
           *
           * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
           */
          abstract contract ERC165 is IERC165 {
              /**
               * @dev See {IERC165-supportsInterface}.
               */
              function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                  return interfaceId == type(IERC165).interfaceId;
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Interface of the ERC165 standard, as defined in the
           * https://eips.ethereum.org/EIPS/eip-165[EIP].
           *
           * Implementers can declare support of contract interfaces, which can then be
           * queried by others ({ERC165Checker}).
           *
           * For an implementation, see {ERC165}.
           */
          interface IERC165 {
              /**
               * @dev Returns true if this contract implements the interface defined by
               * `interfaceId`. See the corresponding
               * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
               * to learn more about how these ids are created.
               *
               * This function call must use less than 30 000 gas.
               */
              function supportsInterface(bytes4 interfaceId) external view returns (bool);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
           * checks.
           *
           * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
           * easily result in undesired exploitation or bugs, since developers usually
           * assume that overflows raise errors. `SafeCast` restores this intuition by
           * reverting the transaction when such an operation overflows.
           *
           * Using this library instead of the unchecked operations eliminates an entire
           * class of bugs, so it's recommended to use it always.
           *
           * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
           * all math on `uint256` and `int256` and then downcasting.
           */
          library SafeCast {
              /**
               * @dev Returns the downcasted uint224 from uint256, reverting on
               * overflow (when the input is greater than largest uint224).
               *
               * Counterpart to Solidity's `uint224` operator.
               *
               * Requirements:
               *
               * - input must fit into 224 bits
               */
              function toUint224(uint256 value) internal pure returns (uint224) {
                  require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
                  return uint224(value);
              }
              /**
               * @dev Returns the downcasted uint128 from uint256, reverting on
               * overflow (when the input is greater than largest uint128).
               *
               * Counterpart to Solidity's `uint128` operator.
               *
               * Requirements:
               *
               * - input must fit into 128 bits
               */
              function toUint128(uint256 value) internal pure returns (uint128) {
                  require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
                  return uint128(value);
              }
              /**
               * @dev Returns the downcasted uint96 from uint256, reverting on
               * overflow (when the input is greater than largest uint96).
               *
               * Counterpart to Solidity's `uint96` operator.
               *
               * Requirements:
               *
               * - input must fit into 96 bits
               */
              function toUint96(uint256 value) internal pure returns (uint96) {
                  require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
                  return uint96(value);
              }
              /**
               * @dev Returns the downcasted uint64 from uint256, reverting on
               * overflow (when the input is greater than largest uint64).
               *
               * Counterpart to Solidity's `uint64` operator.
               *
               * Requirements:
               *
               * - input must fit into 64 bits
               */
              function toUint64(uint256 value) internal pure returns (uint64) {
                  require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
                  return uint64(value);
              }
              /**
               * @dev Returns the downcasted uint32 from uint256, reverting on
               * overflow (when the input is greater than largest uint32).
               *
               * Counterpart to Solidity's `uint32` operator.
               *
               * Requirements:
               *
               * - input must fit into 32 bits
               */
              function toUint32(uint256 value) internal pure returns (uint32) {
                  require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
                  return uint32(value);
              }
              /**
               * @dev Returns the downcasted uint16 from uint256, reverting on
               * overflow (when the input is greater than largest uint16).
               *
               * Counterpart to Solidity's `uint16` operator.
               *
               * Requirements:
               *
               * - input must fit into 16 bits
               */
              function toUint16(uint256 value) internal pure returns (uint16) {
                  require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
                  return uint16(value);
              }
              /**
               * @dev Returns the downcasted uint8 from uint256, reverting on
               * overflow (when the input is greater than largest uint8).
               *
               * Counterpart to Solidity's `uint8` operator.
               *
               * Requirements:
               *
               * - input must fit into 8 bits.
               */
              function toUint8(uint256 value) internal pure returns (uint8) {
                  require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
                  return uint8(value);
              }
              /**
               * @dev Converts a signed int256 into an unsigned uint256.
               *
               * Requirements:
               *
               * - input must be greater than or equal to 0.
               */
              function toUint256(int256 value) internal pure returns (uint256) {
                  require(value >= 0, "SafeCast: value must be positive");
                  return uint256(value);
              }
              /**
               * @dev Returns the downcasted int128 from int256, reverting on
               * overflow (when the input is less than smallest int128 or
               * greater than largest int128).
               *
               * Counterpart to Solidity's `int128` operator.
               *
               * Requirements:
               *
               * - input must fit into 128 bits
               *
               * _Available since v3.1._
               */
              function toInt128(int256 value) internal pure returns (int128) {
                  require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
                  return int128(value);
              }
              /**
               * @dev Returns the downcasted int64 from int256, reverting on
               * overflow (when the input is less than smallest int64 or
               * greater than largest int64).
               *
               * Counterpart to Solidity's `int64` operator.
               *
               * Requirements:
               *
               * - input must fit into 64 bits
               *
               * _Available since v3.1._
               */
              function toInt64(int256 value) internal pure returns (int64) {
                  require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
                  return int64(value);
              }
              /**
               * @dev Returns the downcasted int32 from int256, reverting on
               * overflow (when the input is less than smallest int32 or
               * greater than largest int32).
               *
               * Counterpart to Solidity's `int32` operator.
               *
               * Requirements:
               *
               * - input must fit into 32 bits
               *
               * _Available since v3.1._
               */
              function toInt32(int256 value) internal pure returns (int32) {
                  require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
                  return int32(value);
              }
              /**
               * @dev Returns the downcasted int16 from int256, reverting on
               * overflow (when the input is less than smallest int16 or
               * greater than largest int16).
               *
               * Counterpart to Solidity's `int16` operator.
               *
               * Requirements:
               *
               * - input must fit into 16 bits
               *
               * _Available since v3.1._
               */
              function toInt16(int256 value) internal pure returns (int16) {
                  require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
                  return int16(value);
              }
              /**
               * @dev Returns the downcasted int8 from int256, reverting on
               * overflow (when the input is less than smallest int8 or
               * greater than largest int8).
               *
               * Counterpart to Solidity's `int8` operator.
               *
               * Requirements:
               *
               * - input must fit into 8 bits.
               *
               * _Available since v3.1._
               */
              function toInt8(int256 value) internal pure returns (int8) {
                  require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
                  return int8(value);
              }
              /**
               * @dev Converts an unsigned uint256 into a signed int256.
               *
               * Requirements:
               *
               * - input must be less than or equal to maxInt256.
               */
              function toInt256(uint256 value) internal pure returns (int256) {
                  // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
                  require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
                  return int256(value);
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev String operations.
           */
          library Strings {
              bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
              /**
               * @dev Converts a `uint256` to its ASCII `string` decimal representation.
               */
              function toString(uint256 value) internal pure returns (string memory) {
                  // Inspired by OraclizeAPI's implementation - MIT licence
                  // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
                  if (value == 0) {
                      return "0";
                  }
                  uint256 temp = value;
                  uint256 digits;
                  while (temp != 0) {
                      digits++;
                      temp /= 10;
                  }
                  bytes memory buffer = new bytes(digits);
                  while (value != 0) {
                      digits -= 1;
                      buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
                      value /= 10;
                  }
                  return string(buffer);
              }
              /**
               * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
               */
              function toHexString(uint256 value) internal pure returns (string memory) {
                  if (value == 0) {
                      return "0x00";
                  }
                  uint256 temp = value;
                  uint256 length = 0;
                  while (temp != 0) {
                      length++;
                      temp >>= 8;
                  }
                  return toHexString(value, length);
              }
              /**
               * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
               */
              function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
                  bytes memory buffer = new bytes(2 * length + 2);
                  buffer[0] = "0";
                  buffer[1] = "x";
                  for (uint256 i = 2 * length + 1; i > 1; --i) {
                      buffer[i] = _HEX_SYMBOLS[value & 0xf];
                      value >>= 4;
                  }
                  require(value == 0, "Strings: hex length insufficient");
                  return string(buffer);
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Library for managing
           * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
           * types.
           *
           * Sets have the following properties:
           *
           * - Elements are added, removed, and checked for existence in constant time
           * (O(1)).
           * - Elements are enumerated in O(n). No guarantees are made on the ordering.
           *
           * ```
           * contract Example {
           *     // Add the library methods
           *     using EnumerableSet for EnumerableSet.AddressSet;
           *
           *     // Declare a set state variable
           *     EnumerableSet.AddressSet private mySet;
           * }
           * ```
           *
           * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
           * and `uint256` (`UintSet`) are supported.
           */
          library EnumerableSet {
              // To implement this library for multiple types with as little code
              // repetition as possible, we write it in terms of a generic Set type with
              // bytes32 values.
              // The Set implementation uses private functions, and user-facing
              // implementations (such as AddressSet) are just wrappers around the
              // underlying Set.
              // This means that we can only create new EnumerableSets for types that fit
              // in bytes32.
              struct Set {
                  // Storage of set values
                  bytes32[] _values;
                  // Position of the value in the `values` array, plus 1 because index 0
                  // means a value is not in the set.
                  mapping(bytes32 => uint256) _indexes;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function _add(Set storage set, bytes32 value) private returns (bool) {
                  if (!_contains(set, value)) {
                      set._values.push(value);
                      // The value is stored at length-1, but we add 1 to all indexes
                      // and use 0 as a sentinel value
                      set._indexes[value] = set._values.length;
                      return true;
                  } else {
                      return false;
                  }
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function _remove(Set storage set, bytes32 value) private returns (bool) {
                  // We read and store the value's index to prevent multiple reads from the same storage slot
                  uint256 valueIndex = set._indexes[value];
                  if (valueIndex != 0) {
                      // Equivalent to contains(set, value)
                      // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
                      // the array, and then remove the last element (sometimes called as 'swap and pop').
                      // This modifies the order of the array, as noted in {at}.
                      uint256 toDeleteIndex = valueIndex - 1;
                      uint256 lastIndex = set._values.length - 1;
                      if (lastIndex != toDeleteIndex) {
                          bytes32 lastvalue = set._values[lastIndex];
                          // Move the last value to the index where the value to delete is
                          set._values[toDeleteIndex] = lastvalue;
                          // Update the index for the moved value
                          set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
                      }
                      // Delete the slot where the moved value was stored
                      set._values.pop();
                      // Delete the index for the deleted slot
                      delete set._indexes[value];
                      return true;
                  } else {
                      return false;
                  }
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function _contains(Set storage set, bytes32 value) private view returns (bool) {
                  return set._indexes[value] != 0;
              }
              /**
               * @dev Returns the number of values on the set. O(1).
               */
              function _length(Set storage set) private view returns (uint256) {
                  return set._values.length;
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function _at(Set storage set, uint256 index) private view returns (bytes32) {
                  return set._values[index];
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function _values(Set storage set) private view returns (bytes32[] memory) {
                  return set._values;
              }
              // Bytes32Set
              struct Bytes32Set {
                  Set _inner;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                  return _add(set._inner, value);
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                  return _remove(set._inner, value);
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
                  return _contains(set._inner, value);
              }
              /**
               * @dev Returns the number of values in the set. O(1).
               */
              function length(Bytes32Set storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
                  return _at(set._inner, index);
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
                  return _values(set._inner);
              }
              // AddressSet
              struct AddressSet {
                  Set _inner;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(AddressSet storage set, address value) internal returns (bool) {
                  return _add(set._inner, bytes32(uint256(uint160(value))));
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(AddressSet storage set, address value) internal returns (bool) {
                  return _remove(set._inner, bytes32(uint256(uint160(value))));
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(AddressSet storage set, address value) internal view returns (bool) {
                  return _contains(set._inner, bytes32(uint256(uint160(value))));
              }
              /**
               * @dev Returns the number of values in the set. O(1).
               */
              function length(AddressSet storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(AddressSet storage set, uint256 index) internal view returns (address) {
                  return address(uint160(uint256(_at(set._inner, index))));
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(AddressSet storage set) internal view returns (address[] memory) {
                  bytes32[] memory store = _values(set._inner);
                  address[] memory result;
                  assembly {
                      result := store
                  }
                  return result;
              }
              // UintSet
              struct UintSet {
                  Set _inner;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(UintSet storage set, uint256 value) internal returns (bool) {
                  return _add(set._inner, bytes32(value));
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(UintSet storage set, uint256 value) internal returns (bool) {
                  return _remove(set._inner, bytes32(value));
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(UintSet storage set, uint256 value) internal view returns (bool) {
                  return _contains(set._inner, bytes32(value));
              }
              /**
               * @dev Returns the number of values on the set. O(1).
               */
              function length(UintSet storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(UintSet storage set, uint256 index) internal view returns (uint256) {
                  return uint256(_at(set._inner, index));
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(UintSet storage set) internal view returns (uint256[] memory) {
                  bytes32[] memory store = _values(set._inner);
                  uint256[] memory result;
                  assembly {
                      result := store
                  }
                  return result;
              }
          }
          // SPDX-FileCopyrightText: 2023 Lido <[email protected]>
          // SPDX-License-Identifier: MIT
          // See contracts/COMPILERS.md
          pragma solidity 0.8.9;
          library Math {
              function max(uint256 a, uint256 b) internal pure returns (uint256) {
                  return a > b ? a : b;
              }
              function min(uint256 a, uint256 b) internal pure returns (uint256) {
                  return a < b ? a : b;
              }
              /// @notice Tests if x ∈ [a, b) (mod n)
              ///
              function pointInHalfOpenIntervalModN(uint256 x, uint256 a, uint256 b, uint256 n)
                  internal pure returns (bool)
              {
                  return (x + n - a) % n < (b - a) % n;
              }
              /// @notice Tests if x ∈ [a, b] (mod n)
              ///
              function pointInClosedIntervalModN(uint256 x, uint256 a, uint256 b, uint256 n)
                  internal pure returns (bool)
              {
                  return (x + n - a) % n <= (b - a) % n;
              }
          }
          // SPDX-FileCopyrightText: 2023 Lido <[email protected]>
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity 0.8.9;
          import { SafeCast } from "@openzeppelin/contracts-v4.4/utils/math/SafeCast.sol";
          import { Math } from "../lib/Math.sol";
          import { AccessControlEnumerable } from "../utils/access/AccessControlEnumerable.sol";
          /// @notice A contract that gets consensus reports (i.e. hashes) pushed to and processes them
          /// asynchronously.
          ///
          /// HashConsensus doesn't expect any specific behavior from a report processor, and guarantees
          /// the following:
          ///
          /// 1. HashConsensus won't submit reports via `IReportAsyncProcessor.submitConsensusReport` or ask
          ///    to discard reports via `IReportAsyncProcessor.discardConsensusReport` for any slot up to (and
          ///    including) the slot returned from `IReportAsyncProcessor.getLastProcessingRefSlot`.
          ///
          /// 2. HashConsensus won't accept member reports (and thus won't include such reports in calculating
          ///    the consensus) that have `consensusVersion` argument of the `HashConsensus.submitReport` call
          ///    holding a diff. value than the one returned from `IReportAsyncProcessor.getConsensusVersion()`
          ///    at the moment of the `HashConsensus.submitReport` call.
          ///
          interface IReportAsyncProcessor {
              /// @notice Submits a consensus report for processing.
              ///
              /// Note that submitting the report doesn't require the processor to start processing it right
              /// away, this can happen later (see `getLastProcessingRefSlot`). Until processing is started,
              /// HashConsensus is free to reach consensus on another report for the same reporting frame an
              /// submit it using this same function, or to lose the consensus on the submitted report,
              /// notifying the processor via `discardConsensusReport`.
              ///
              function submitConsensusReport(bytes32 report, uint256 refSlot, uint256 deadline) external;
              /// @notice Notifies that the report for the given ref. slot is not a conensus report anymore
              /// and should be discarded. This can happen when a member changes their report, is removed
              /// from the set, or when the quorum value gets increased.
              ///
              /// Only called when, for the given reference slot:
              ///
              ///   1. there previously was a consensus report; AND
              ///   1. processing of the consensus report hasn't started yet; AND
              ///   2. report processing deadline is not expired yet; AND
              ///   3. there's no consensus report now (otherwise, `submitConsensusReport` is called instead).
              ///
              /// Can be called even when there's no submitted non-discarded consensus report for the current
              /// reference slot, i.e. can be called multiple times in succession.
              ///
              function discardConsensusReport(uint256 refSlot) external;
              /// @notice Returns the last reference slot for which processing of the report was started.
              ///
              /// HashConsensus won't submit reports for any slot less than or equal to this slot.
              ///
              function getLastProcessingRefSlot() external view returns (uint256);
              /// @notice Returns the current consensus version.
              ///
              /// Consensus version must change every time consensus rules change, meaning that
              /// an oracle looking at the same reference slot would calculate a different hash.
              ///
              /// HashConsensus won't accept member reports any consensus version different form the
              /// one returned from this function.
              ///
              function getConsensusVersion() external view returns (uint256);
          }
          /// @notice A contract managing oracle members committee and allowing the members to reach
          /// consensus on a hash for each reporting frame.
          ///
          /// Time is divided in frames of equal length, each having reference slot and processing
          /// deadline. Report data must be gathered by looking at the world state at the moment of
          /// the frame's reference slot (including any state changes made in that slot), and must
          /// be processed before the frame's processing deadline.
          ///
          /// Frame length is defined in Ethereum consensus layer epochs. Reference slot for each
          /// frame is set to the last slot of the epoch preceding the frame's first epoch. The
          /// processing deadline is set to the last slot of the last epoch of the frame.
          ///
          /// This means that all state changes a report processing could entail are guaranteed to be
          /// observed while gathering data for the next frame's report. This is an important property
          /// given that oracle reports sometimes have to contain diffs instead of the full state which
          /// might be impractical or even impossible to transmit and process.
          ///
          contract HashConsensus is AccessControlEnumerable {
              using SafeCast for uint256;
              error InvalidChainConfig();
              error NumericOverflow();
              error AdminCannotBeZero();
              error ReportProcessorCannotBeZero();
              error DuplicateMember();
              error AddressCannotBeZero();
              error InitialEpochIsYetToArrive();
              error InitialEpochAlreadyArrived();
              error InitialEpochRefSlotCannotBeEarlierThanProcessingSlot();
              error EpochsPerFrameCannotBeZero();
              error NonMember();
              error UnexpectedConsensusVersion(uint256 expected, uint256 received);
              error QuorumTooSmall(uint256 minQuorum, uint256 receivedQuorum);
              error InvalidSlot();
              error DuplicateReport();
              error EmptyReport();
              error StaleReport();
              error NonFastLaneMemberCannotReportWithinFastLaneInterval();
              error NewProcessorCannotBeTheSame();
              error ConsensusReportAlreadyProcessing();
              error FastLanePeriodCannotBeLongerThanFrame();
              event FrameConfigSet(uint256 newInitialEpoch, uint256 newEpochsPerFrame);
              event FastLaneConfigSet(uint256 fastLaneLengthSlots);
              event MemberAdded(address indexed addr, uint256 newTotalMembers, uint256 newQuorum);
              event MemberRemoved(address indexed addr, uint256 newTotalMembers, uint256 newQuorum);
              event QuorumSet(uint256 newQuorum, uint256 totalMembers, uint256 prevQuorum);
              event ReportReceived(uint256 indexed refSlot, address indexed member, bytes32 report);
              event ConsensusReached(uint256 indexed refSlot, bytes32 report, uint256 support);
              event ConsensusLost(uint256 indexed refSlot);
              event ReportProcessorSet(address indexed processor, address indexed prevProcessor);
              struct FrameConfig {
                  uint64 initialEpoch;
                  uint64 epochsPerFrame;
                  uint64 fastLaneLengthSlots;
              }
              /// @dev Oracle reporting is divided into frames, each lasting the same number of slots.
              ///
              /// The start slot of the next frame is always the next slot after the end slot of the previous
              /// frame.
              ///
              /// Each frame also has a reference slot: if the oracle report contains any data derived from
              /// onchain data, the onchain data should be sampled at the reference slot.
              ///
              struct ConsensusFrame {
                  // frame index; increments by 1 with each frame but resets to zero on frame size change
                  uint256 index;
                  // the slot at which to read the state around which consensus is being reached;
                  // if the slot contains a block, the state should include all changes from that block
                  uint256 refSlot;
                  // the last slot at which a report can be reported and processed
                  uint256 reportProcessingDeadlineSlot;
              }
              struct ReportingState {
                  // the last reference slot any report was received for
                  uint64 lastReportRefSlot;
                  // the last reference slot a consensus was reached for
                  uint64 lastConsensusRefSlot;
                  // the last consensus variant index
                  uint64 lastConsensusVariantIndex;
              }
              struct MemberState {
                  // the last reference slot a report from this member was received for
                  uint64 lastReportRefSlot;
                  // the variant index of the last report from this member
                  uint64 lastReportVariantIndex;
              }
              struct ReportVariant {
                  // the reported hash
                  bytes32 hash;
                  // how many unique members from the current set reported this hash in the current frame
                  uint64 support;
              }
              /// @notice An ACL role granting the permission to modify members list members and
              /// change the quorum by calling addMember, removeMember, and setQuorum functions.
              bytes32 public constant MANAGE_MEMBERS_AND_QUORUM_ROLE =
                  keccak256("MANAGE_MEMBERS_AND_QUORUM_ROLE");
              /// @notice An ACL role granting the permission to disable the consensus by calling
              /// the disableConsensus function. Enabling the consensus back requires the possession
              /// of the MANAGE_QUORUM_ROLE.
              bytes32 public constant DISABLE_CONSENSUS_ROLE = keccak256("DISABLE_CONSENSUS_ROLE");
              /// @notice An ACL role granting the permission to change reporting interval duration
              /// and fast lane reporting interval length by calling setFrameConfig.
              bytes32 public constant MANAGE_FRAME_CONFIG_ROLE = keccak256("MANAGE_FRAME_CONFIG_ROLE");
              /// @notice An ACL role granting the permission to change fast lane reporting interval
              /// length by calling setFastLaneLengthSlots.
              bytes32 public constant MANAGE_FAST_LANE_CONFIG_ROLE = keccak256("MANAGE_FAST_LANE_CONFIG_ROLE");
              /// @notice An ACL role granting the permission to change еру report processor
              /// contract by calling setReportProcessor.
              bytes32 public constant MANAGE_REPORT_PROCESSOR_ROLE = keccak256("MANAGE_REPORT_PROCESSOR_ROLE");
              /// Chain specification
              uint64 internal immutable SLOTS_PER_EPOCH;
              uint64 internal immutable SECONDS_PER_SLOT;
              uint64 internal immutable GENESIS_TIME;
              /// @dev A quorum value that effectively disables the oracle.
              uint256 internal constant UNREACHABLE_QUORUM = type(uint256).max;
              bytes32 internal constant ZERO_HASH = bytes32(0);
              /// @dev An offset from the processing deadline slot of the previous frame (i.e. the last slot
              /// at which a report for the prev. frame can be submitted and its processing started) to the
              /// reference slot of the next frame (equal to the last slot of the previous frame).
              /// frame[i].reportProcessingDeadlineSlot := frame[i + 1].refSlot - DEADLINE_SLOT_OFFSET
              uint256 internal constant DEADLINE_SLOT_OFFSET = 0;
              /// @dev Reporting frame configuration
              FrameConfig internal _frameConfig;
              /// @dev Oracle committee members states array
              MemberState[] internal _memberStates;
              /// @dev Oracle committee members' addresses array
              address[] internal _memberAddresses;
              /// @dev Mapping from an oracle committee member address to the 1-based index in the
              /// members array
              mapping(address => uint256) internal _memberIndices1b;
              /// @dev A structure containing the last reference slot any report was received for, the last
              /// reference slot consensus report was achieved for, and the last consensus variant index
              ReportingState internal _reportingState;
              /// @dev Oracle committee members quorum value, must be larger than totalMembers // 2
              uint256 internal _quorum;
              /// @dev Mapping from a report variant index to the ReportVariant structure
              mapping(uint256 => ReportVariant) internal _reportVariants;
              /// @dev The number of report variants
              uint256 internal _reportVariantsLength;
              /// @dev The address of the report processor contract
              address internal _reportProcessor;
              ///
              /// Initialization
              ///
              constructor(
                  uint256 slotsPerEpoch,
                  uint256 secondsPerSlot,
                  uint256 genesisTime,
                  uint256 epochsPerFrame,
                  uint256 fastLaneLengthSlots,
                  address admin,
                  address reportProcessor
              ) {
                  if (slotsPerEpoch == 0) revert InvalidChainConfig();
                  if (secondsPerSlot == 0) revert InvalidChainConfig();
                  SLOTS_PER_EPOCH = slotsPerEpoch.toUint64();
                  SECONDS_PER_SLOT = secondsPerSlot.toUint64();
                  GENESIS_TIME = genesisTime.toUint64();
                  if (admin == address(0)) revert AdminCannotBeZero();
                  if (reportProcessor == address(0)) revert ReportProcessorCannotBeZero();
                  _setupRole(DEFAULT_ADMIN_ROLE, admin);
                  uint256 farFutureEpoch = _computeEpochAtTimestamp(type(uint64).max);
                  _setFrameConfig(farFutureEpoch, epochsPerFrame, fastLaneLengthSlots, FrameConfig(0, 0, 0));
                  _reportProcessor = reportProcessor;
              }
              ///
              /// Time
              ///
              /// @notice Returns the immutable chain parameters required to calculate epoch and slot
              /// given a timestamp.
              ///
              function getChainConfig() external view returns (
                  uint256 slotsPerEpoch,
                  uint256 secondsPerSlot,
                  uint256 genesisTime
              ) {
                  return (SLOTS_PER_EPOCH, SECONDS_PER_SLOT, GENESIS_TIME);
              }
              /// @notice Returns the time-related configuration.
              ///
              /// @return initialEpoch Epoch of the frame with zero index.
              /// @return epochsPerFrame Length of a frame in epochs.
              /// @return fastLaneLengthSlots Length of the fast lane interval in slots; see `getIsFastLaneMember`.
              ///
              function getFrameConfig() external view returns (
                  uint256 initialEpoch,
                  uint256 epochsPerFrame,
                  uint256 fastLaneLengthSlots
              ) {
                  FrameConfig memory config = _frameConfig;
                  return (config.initialEpoch, config.epochsPerFrame, config.fastLaneLengthSlots);
              }
              /// @notice Returns the current reporting frame.
              ///
              /// @return refSlot The frame's reference slot: if the data the consensus is being reached upon
              ///         includes or depends on any onchain state, this state should be queried at the
              ///         reference slot. If the slot contains a block, the state should include all changes
              ///         from that block.
              ///
              /// @return reportProcessingDeadlineSlot The last slot at which the report can be processed by
              ///         the report processor contract.
              ///
              function getCurrentFrame() external view returns (
                  uint256 refSlot,
                  uint256 reportProcessingDeadlineSlot
              ) {
                  ConsensusFrame memory frame = _getCurrentFrame();
                  return (frame.refSlot, frame.reportProcessingDeadlineSlot);
              }
              /// @notice Returns the earliest possible reference slot, i.e. the reference slot of the
              /// reporting frame with zero index.
              ///
              function getInitialRefSlot() external view returns (uint256) {
                  return _getInitialFrame().refSlot;
              }
              /// @notice Sets a new initial epoch given that the current initial epoch is in the future.
              ///
              /// @param initialEpoch The new initial epoch.
              ///
              function updateInitialEpoch(uint256 initialEpoch) external onlyRole(DEFAULT_ADMIN_ROLE) {
                  FrameConfig memory prevConfig = _frameConfig;
                  if (_computeEpochAtTimestamp(_getTime()) >= prevConfig.initialEpoch) {
                      revert InitialEpochAlreadyArrived();
                  }
                  _setFrameConfig(
                      initialEpoch,
                      prevConfig.epochsPerFrame,
                      prevConfig.fastLaneLengthSlots,
                      prevConfig
                  );
                  if (_getInitialFrame().refSlot < _getLastProcessingRefSlot()) {
                      revert InitialEpochRefSlotCannotBeEarlierThanProcessingSlot();
                  }
              }
              /// @notice Updates the time-related configuration.
              ///
              /// @param epochsPerFrame Length of a frame in epochs.
              /// @param fastLaneLengthSlots Length of the fast lane interval in slots; see `getIsFastLaneMember`.
              ///
              function setFrameConfig(uint256 epochsPerFrame, uint256 fastLaneLengthSlots)
                  external onlyRole(MANAGE_FRAME_CONFIG_ROLE)
              {
                  // Updates epochsPerFrame in a way that either keeps the current reference slot the same
                  // or increases it by at least the minimum of old and new frame sizes.
                  uint256 timestamp = _getTime();
                  uint256 currentFrameStartEpoch = _computeFrameStartEpoch(timestamp, _frameConfig);
                  _setFrameConfig(currentFrameStartEpoch, epochsPerFrame, fastLaneLengthSlots, _frameConfig);
              }
              ///
              /// Members
              ///
              /// @notice Returns whether the given address is currently a member of the consensus.
              ///
              function getIsMember(address addr) external view returns (bool) {
                  return _isMember(addr);
              }
              /// @notice Returns whether the given address is a fast lane member for the current reporting
              /// frame.
              ///
              /// Fast lane members is a subset of all members that changes each reporting frame. These
              /// members can, and are expected to, submit a report during the first part of the frame called
              /// the "fast lane interval" and defined via `setFrameConfig` or `setFastLaneLengthSlots`. Under
              /// regular circumstances, all other members are only allowed to submit a report after the fast
              /// lane interval passes.
              ///
              /// The fast lane subset consists of `quorum` members; selection is implemented as a sliding
              /// window of the `quorum` width over member indices (mod total members). The window advances
              /// by one index each reporting frame.
              ///
              /// This is done to encourage each member from the full set to participate in reporting on a
              /// regular basis, and identify any malfunctioning members.
              ///
              /// With the fast lane mechanism active, it's sufficient for the monitoring to check that
              /// consensus is consistently reached during the fast lane part of each frame to conclude that
              /// all members are active and share the same consensus rules.
              ///
              /// However, there is no guarantee that, at any given time, it holds true that only the current
              /// fast lane members can or were able to report during the currently-configured fast lane
              /// interval of the current frame. In particular, this assumption can be violated in any frame
              /// during which the members set, initial epoch, or the quorum number was changed, or the fast
              /// lane interval length was increased. Thus, the fast lane mechanism should not be used for any
              /// purpose other than monitoring of the members liveness, and monitoring tools should take into
              /// consideration the potential irregularities within frames with any configuration changes.
              ///
              function getIsFastLaneMember(address addr) external view returns (bool) {
                  uint256 index1b = _memberIndices1b[addr];
                  unchecked {
                      return index1b > 0 && _isFastLaneMember(index1b - 1, _getCurrentFrame().index);
                  }
              }
              /// @notice Returns all current members, together with the last reference slot each member
              /// submitted a report for.
              ///
              function getMembers() external view returns (
                  address[] memory addresses,
                  uint256[] memory lastReportedRefSlots
              ) {
                  return _getMembers(false);
              }
              /// @notice Returns the subset of the oracle committee members (consisting of `quorum` items)
              /// that changes each frame.
              ///
              /// See `getIsFastLaneMember`.
              ///
              function getFastLaneMembers() external view returns (
                  address[] memory addresses,
                  uint256[] memory lastReportedRefSlots
              ) {
                  return _getMembers(true);
              }
              /// @notice Sets the duration of the fast lane interval of the reporting frame.
              ///
              /// See `getIsFastLaneMember`.
              ///
              /// @param fastLaneLengthSlots The length of the fast lane reporting interval in slots. Setting
              ///        it to zero disables the fast lane subset, allowing any oracle to report starting from
              ///        the first slot of a frame and until the frame's reporting deadline.
              ///
              function setFastLaneLengthSlots(uint256 fastLaneLengthSlots)
                  external onlyRole(MANAGE_FAST_LANE_CONFIG_ROLE)
              {
                  _setFastLaneLengthSlots(fastLaneLengthSlots);
              }
              function addMember(address addr, uint256 quorum)
                  external
                  onlyRole(MANAGE_MEMBERS_AND_QUORUM_ROLE)
              {
                  _addMember(addr, quorum);
              }
              function removeMember(address addr, uint256 quorum)
                  external
                  onlyRole(MANAGE_MEMBERS_AND_QUORUM_ROLE)
              {
                  _removeMember(addr, quorum);
              }
              function getQuorum() external view returns (uint256) {
                  return _quorum;
              }
              function setQuorum(uint256 quorum) external {
                  // access control is performed inside the next call
                  _setQuorumAndCheckConsensus(quorum, _memberStates.length);
              }
              /// @notice Disables the oracle by setting the quorum to an unreachable value.
              ///
              function disableConsensus() external {
                  // access control is performed inside the next call
                  _setQuorumAndCheckConsensus(UNREACHABLE_QUORUM, _memberStates.length);
              }
              ///
              /// Report processor
              ///
              function getReportProcessor() external view returns (address) {
                  return _reportProcessor;
              }
              function setReportProcessor(address newProcessor)
                  external
                  onlyRole(MANAGE_REPORT_PROCESSOR_ROLE)
              {
                  _setReportProcessor(newProcessor);
              }
              ///
              /// Consensus
              ///
              /// @notice Returns info about the current frame and consensus state in that frame.
              ///
              /// @return refSlot Reference slot of the current reporting frame.
              ///
              /// @return consensusReport Consensus report for the current frame, if any.
              ///         Zero bytes otherwise.
              ///
              /// @return isReportProcessing If consensus report for the current frame is already
              ///         being processed. Consensus can be changed before the processing starts.
              ///
              function getConsensusState() external view returns (
                  uint256 refSlot,
                  bytes32 consensusReport,
                  bool isReportProcessing
              ) {
                  refSlot = _getCurrentFrame().refSlot;
                  (consensusReport,,) = _getConsensusReport(refSlot, _quorum);
                  isReportProcessing = _getLastProcessingRefSlot() == refSlot;
              }
              /// @notice Returns report variants and their support for the current reference slot.
              ///
              function getReportVariants() external view returns (
                  bytes32[] memory variants,
                  uint256[] memory support
              ) {
                  if (_reportingState.lastReportRefSlot != _getCurrentFrame().refSlot) {
                      return (variants, support);
                  }
                  uint256 variantsLength = _reportVariantsLength;
                  variants = new bytes32[](variantsLength);
                  support = new uint256[](variantsLength);
                  for (uint256 i = 0; i < variantsLength; ++i) {
                      ReportVariant memory variant = _reportVariants[i];
                      variants[i] = variant.hash;
                      support[i] = variant.support;
                  }
              }
              struct MemberConsensusState {
                  /// @notice Current frame's reference slot.
                  uint256 currentFrameRefSlot;
                  /// @notice Consensus report for the current frame, if any. Zero bytes otherwise.
                  bytes32 currentFrameConsensusReport;
                  /// @notice Whether the provided address is a member of the oracle committee.
                  bool isMember;
                  /// @notice Whether the oracle committee member is in the fast lane members subset
                  /// of the current reporting frame. See `getIsFastLaneMember`.
                  bool isFastLane;
                  /// @notice Whether the oracle committee member is allowed to submit a report at
                  /// the moment of the call.
                  bool canReport;
                  /// @notice The last reference slot for which the member submitted a report.
                  uint256 lastMemberReportRefSlot;
                  /// @notice The hash reported by the member for the current frame, if any.
                  /// Zero bytes otherwise.
                  bytes32 currentFrameMemberReport;
              }
              /// @notice Returns the extended information related to an oracle committee member with the
              /// given address and the current consensus state. Provides all the information needed for
              /// an oracle daemon to decide if it needs to submit a report.
              ///
              /// @param addr The member address.
              /// @return result See the docs for `MemberConsensusState`.
              ///
              function getConsensusStateForMember(address addr)
                  external view returns (MemberConsensusState memory result)
              {
                  ConsensusFrame memory frame = _getCurrentFrame();
                  result.currentFrameRefSlot = frame.refSlot;
                  (result.currentFrameConsensusReport,,) = _getConsensusReport(frame.refSlot, _quorum);
                  uint256 index = _memberIndices1b[addr];
                  result.isMember = index != 0;
                  if (index != 0) {
                      unchecked { --index; } // convert to 0-based
                      MemberState memory memberState = _memberStates[index];
                      result.lastMemberReportRefSlot = memberState.lastReportRefSlot;
                      result.currentFrameMemberReport =
                          result.lastMemberReportRefSlot == frame.refSlot
                              ? _reportVariants[memberState.lastReportVariantIndex].hash
                              : ZERO_HASH;
                      uint256 slot = _computeSlotAtTimestamp(_getTime());
                      result.canReport = slot <= frame.reportProcessingDeadlineSlot &&
                          frame.refSlot > _getLastProcessingRefSlot();
                      result.isFastLane = _isFastLaneMember(index, frame.index);
                      if (!result.isFastLane && result.canReport) {
                          result.canReport = slot > frame.refSlot + _frameConfig.fastLaneLengthSlots;
                      }
                  }
              }
              /// @notice Used by oracle members to submit hash of the data calculated for the given
              /// reference slot.
              ///
              /// @param slot The reference slot the data was calculated for. Reverts if doesn't match
              ///        the current reference slot.
              ///
              /// @param report Hash of the data calculated for the given reference slot.
              ///
              /// @param consensusVersion Version of the oracle consensus rules. Reverts if doesn't
              ///        match the version returned by the currently set consensus report processor,
              ///        or zero if no report processor is set.
              ///
              function submitReport(uint256 slot, bytes32 report, uint256 consensusVersion) external {
                  _submitReport(slot, report, consensusVersion);
              }
              ///
              /// Implementation: time
              ///
              function _setFrameConfig(
                  uint256 initialEpoch,
                  uint256 epochsPerFrame,
                  uint256 fastLaneLengthSlots,
                  FrameConfig memory prevConfig
              ) internal {
                  if (epochsPerFrame == 0) revert EpochsPerFrameCannotBeZero();
                  if (fastLaneLengthSlots > epochsPerFrame * SLOTS_PER_EPOCH) {
                      revert FastLanePeriodCannotBeLongerThanFrame();
                  }
                  _frameConfig = FrameConfig(
                      initialEpoch.toUint64(),
                      epochsPerFrame.toUint64(),
                      fastLaneLengthSlots.toUint64()
                  );
                  if (initialEpoch != prevConfig.initialEpoch || epochsPerFrame != prevConfig.epochsPerFrame) {
                      emit FrameConfigSet(initialEpoch, epochsPerFrame);
                  }
                  if (fastLaneLengthSlots != prevConfig.fastLaneLengthSlots) {
                      emit FastLaneConfigSet(fastLaneLengthSlots);
                  }
              }
              function _getCurrentFrame() internal view returns (ConsensusFrame memory) {
                  return _getFrameAtTimestamp(_getTime(), _frameConfig);
              }
              function _getInitialFrame() internal view returns (ConsensusFrame memory) {
                  return _getFrameAtIndex(0, _frameConfig);
              }
              function _getFrameAtTimestamp(uint256 timestamp, FrameConfig memory config)
                  internal view returns (ConsensusFrame memory)
              {
                  return _getFrameAtIndex(_computeFrameIndex(timestamp, config), config);
              }
              function _getFrameAtIndex(uint256 frameIndex, FrameConfig memory config)
                  internal view returns (ConsensusFrame memory)
              {
                  uint256 frameStartEpoch = _computeStartEpochOfFrameWithIndex(frameIndex, config);
                  uint256 frameStartSlot = _computeStartSlotAtEpoch(frameStartEpoch);
                  uint256 nextFrameStartSlot = frameStartSlot + config.epochsPerFrame * SLOTS_PER_EPOCH;
                  return ConsensusFrame({
                      index: frameIndex,
                      refSlot: uint64(frameStartSlot - 1),
                      reportProcessingDeadlineSlot: uint64(nextFrameStartSlot - 1 - DEADLINE_SLOT_OFFSET)
                  });
              }
              function _computeFrameStartEpoch(uint256 timestamp, FrameConfig memory config)
                  internal view returns (uint256)
              {
                  return _computeStartEpochOfFrameWithIndex(_computeFrameIndex(timestamp, config), config);
              }
              function _computeStartEpochOfFrameWithIndex(uint256 frameIndex, FrameConfig memory config)
                  internal pure returns (uint256)
              {
                  return config.initialEpoch + frameIndex * config.epochsPerFrame;
              }
              function _computeFrameIndex(uint256 timestamp, FrameConfig memory config)
                  internal view returns (uint256)
              {
                  uint256 epoch = _computeEpochAtTimestamp(timestamp);
                  if (epoch < config.initialEpoch) {
                      revert InitialEpochIsYetToArrive();
                  }
                  return (epoch - config.initialEpoch) / config.epochsPerFrame;
              }
              function _computeTimestampAtSlot(uint256 slot) internal view returns (uint256) {
                  // See: github.com/ethereum/consensus-specs/blob/dev/specs/bellatrix/beacon-chain.md#compute_timestamp_at_slot
                  return GENESIS_TIME + slot * SECONDS_PER_SLOT;
              }
              function _computeSlotAtTimestamp(uint256 timestamp) internal view returns (uint256) {
                  return (timestamp - GENESIS_TIME) / SECONDS_PER_SLOT;
              }
              function _computeEpochAtSlot(uint256 slot) internal view returns (uint256) {
                  // See: github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#compute_epoch_at_slot
                  return slot / SLOTS_PER_EPOCH;
              }
              function _computeEpochAtTimestamp(uint256 timestamp) internal view returns (uint256) {
                  return _computeEpochAtSlot(_computeSlotAtTimestamp(timestamp));
              }
              function _computeStartSlotAtEpoch(uint256 epoch) internal view returns (uint256) {
                  // See: github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#compute_start_slot_at_epoch
                  return epoch * SLOTS_PER_EPOCH;
              }
              function _getTime() internal virtual view returns (uint256) {
                  return block.timestamp; // solhint-disable-line not-rely-on-time
              }
              ///
              /// Implementation: members
              ///
              function _isMember(address addr) internal view returns (bool) {
                  return _memberIndices1b[addr] != 0;
              }
              function _getMemberIndex(address addr) internal view returns (uint256) {
                  uint256 index1b = _memberIndices1b[addr];
                  if (index1b == 0) {
                      revert NonMember();
                  }
                  unchecked {
                      return uint256(index1b - 1);
                  }
              }
              function _addMember(address addr, uint256 quorum) internal {
                  if (_isMember(addr)) revert DuplicateMember();
                  if (addr == address(0)) revert AddressCannotBeZero();
                  _memberStates.push(MemberState(0, 0));
                  _memberAddresses.push(addr);
                  uint256 newTotalMembers = _memberStates.length;
                  _memberIndices1b[addr] = newTotalMembers;
                  emit MemberAdded(addr, newTotalMembers, quorum);
                  _setQuorumAndCheckConsensus(quorum, newTotalMembers);
              }
              function _removeMember(address addr, uint256 quorum) internal {
                  uint256 index = _getMemberIndex(addr);
                  uint256 newTotalMembers = _memberStates.length - 1;
                  assert(index <= newTotalMembers);
                  MemberState memory memberState = _memberStates[index];
                  if (index != newTotalMembers) {
                      address addrToMove = _memberAddresses[newTotalMembers];
                      _memberAddresses[index] = addrToMove;
                      _memberStates[index] = _memberStates[newTotalMembers];
                      _memberIndices1b[addrToMove] = index + 1;
                  }
                  _memberStates.pop();
                  _memberAddresses.pop();
                  _memberIndices1b[addr] = 0;
                  emit MemberRemoved(addr, newTotalMembers, quorum);
                  if (memberState.lastReportRefSlot > 0) {
                      // member reported at least once
                      ConsensusFrame memory frame = _getCurrentFrame();
                      if (memberState.lastReportRefSlot == frame.refSlot &&
                          _getLastProcessingRefSlot() < frame.refSlot
                      ) {
                          // member reported for the current ref. slot and the consensus report
                          // is not processing yet => need to cancel the member's report
                          --_reportVariants[memberState.lastReportVariantIndex].support;
                      }
                  }
                  _setQuorumAndCheckConsensus(quorum, newTotalMembers);
              }
              function _setFastLaneLengthSlots(uint256 fastLaneLengthSlots) internal {
                  FrameConfig memory frameConfig = _frameConfig;
                  if (fastLaneLengthSlots > frameConfig.epochsPerFrame * SLOTS_PER_EPOCH) {
                      revert FastLanePeriodCannotBeLongerThanFrame();
                  }
                  if (fastLaneLengthSlots != frameConfig.fastLaneLengthSlots) {
                      _frameConfig.fastLaneLengthSlots = fastLaneLengthSlots.toUint64();
                      emit FastLaneConfigSet(fastLaneLengthSlots);
                  }
              }
              /// @dev Returns start and past-end incides (mod totalMembers) of the fast lane members subset.
              ///
              function _getFastLaneSubset(uint256 frameIndex, uint256 totalMembers)
                  internal view returns (uint256 startIndex, uint256 pastEndIndex)
              {
                  uint256 quorum = _quorum;
                  if (quorum >= totalMembers) {
                      startIndex = 0;
                      pastEndIndex = totalMembers;
                  } else {
                      startIndex = frameIndex % totalMembers;
                      pastEndIndex = startIndex + quorum;
                  }
              }
              /// @dev Tests whether the member with the given `index` is in the fast lane subset for the
              /// given reporting `frameIndex`.
              ///
              function _isFastLaneMember(uint256 index, uint256 frameIndex) internal view returns (bool) {
                  uint256 totalMembers = _memberStates.length;
                  (uint256 flLeft, uint256 flPastRight) = _getFastLaneSubset(frameIndex, totalMembers);
                  unchecked {
                      return (
                          flPastRight != 0 &&
                          Math.pointInClosedIntervalModN(index, flLeft, flPastRight - 1, totalMembers)
                      );
                  }
              }
              function _getMembers(bool fastLane) internal view returns (
                  address[] memory addresses,
                  uint256[] memory lastReportedRefSlots
              ) {
                  uint256 totalMembers = _memberStates.length;
                  uint256 left;
                  uint256 right;
                  if (fastLane) {
                      (left, right) = _getFastLaneSubset(_getCurrentFrame().index, totalMembers);
                  } else {
                      right = totalMembers;
                  }
                  addresses = new address[](right - left);
                  lastReportedRefSlots = new uint256[](addresses.length);
                  for (uint256 i = left; i < right; ++i) {
                      uint256 iModTotal = i % totalMembers;
                      MemberState memory memberState = _memberStates[iModTotal];
                      uint256 k = i - left;
                      addresses[k] = _memberAddresses[iModTotal];
                      lastReportedRefSlots[k] = memberState.lastReportRefSlot;
                  }
              }
              ///
              /// Implementation: consensus
              ///
              function _submitReport(uint256 slot, bytes32 report, uint256 consensusVersion) internal {
                  if (slot == 0) revert InvalidSlot();
                  if (slot > type(uint64).max) revert NumericOverflow();
                  if (report == ZERO_HASH) revert EmptyReport();
                  uint256 memberIndex = _getMemberIndex(_msgSender());
                  MemberState memory memberState = _memberStates[memberIndex];
                  uint256 expectedConsensusVersion = _getConsensusVersion();
                  if (consensusVersion != expectedConsensusVersion) {
                      revert UnexpectedConsensusVersion(expectedConsensusVersion, consensusVersion);
                  }
                  uint256 timestamp = _getTime();
                  uint256 currentSlot = _computeSlotAtTimestamp(timestamp);
                  FrameConfig memory config = _frameConfig;
                  ConsensusFrame memory frame = _getFrameAtTimestamp(timestamp, config);
                  if (slot != frame.refSlot) revert InvalidSlot();
                  if (currentSlot > frame.reportProcessingDeadlineSlot) revert StaleReport();
                  if (currentSlot <= frame.refSlot + config.fastLaneLengthSlots &&
                      !_isFastLaneMember(memberIndex, frame.index)
                  ) {
                      revert NonFastLaneMemberCannotReportWithinFastLaneInterval();
                  }
                  if (slot <= _getLastProcessingRefSlot()) {
                      // consensus for the ref. slot was already reached and consensus report is processing
                      if (slot == memberState.lastReportRefSlot) {
                          // member sends a report for the same slot => let them know via a revert
                          revert ConsensusReportAlreadyProcessing();
                      } else {
                          // member hasn't sent a report for this slot => normal operation, do nothing
                          return;
                      }
                  }
                  uint256 variantsLength;
                  if (_reportingState.lastReportRefSlot != slot) {
                      // first report for a new slot => clear report variants
                      _reportingState.lastReportRefSlot = uint64(slot);
                      variantsLength = 0;
                  } else {
                      variantsLength = _reportVariantsLength;
                  }
                  uint64 varIndex = 0;
                  bool prevConsensusLost = false;
                  while (varIndex < variantsLength && _reportVariants[varIndex].hash != report) {
                      ++varIndex;
                  }
                  if (slot == memberState.lastReportRefSlot) {
                      uint64 prevVarIndex = memberState.lastReportVariantIndex;
                      assert(prevVarIndex < variantsLength);
                      if (varIndex == prevVarIndex) {
                          revert DuplicateReport();
                      } else {
                          uint256 support = --_reportVariants[prevVarIndex].support;
                          if (support == _quorum - 1) {
                              prevConsensusLost = true;
                          }
                      }
                  }
                  uint256 support;
                  if (varIndex < variantsLength) {
                      support = ++_reportVariants[varIndex].support;
                  } else {
                      support = 1;
                      _reportVariants[varIndex] = ReportVariant({hash: report, support: 1});
                      _reportVariantsLength = ++variantsLength;
                  }
                  _memberStates[memberIndex] = MemberState({
                      lastReportRefSlot: uint64(slot),
                      lastReportVariantIndex: varIndex
                  });
                  emit ReportReceived(slot, _msgSender(), report);
                  if (support >= _quorum) {
                      _consensusReached(frame, report, varIndex, support);
                  } else if (prevConsensusLost) {
                      _consensusNotReached(frame);
                  }
              }
              function _consensusReached(
                  ConsensusFrame memory frame,
                  bytes32 report,
                  uint256 variantIndex,
                  uint256 support
              ) internal {
                  if (_reportingState.lastConsensusRefSlot != frame.refSlot ||
                      _reportingState.lastConsensusVariantIndex != variantIndex
                  ) {
                      _reportingState.lastConsensusRefSlot = uint64(frame.refSlot);
                      _reportingState.lastConsensusVariantIndex = uint64(variantIndex);
                      emit ConsensusReached(frame.refSlot, report, support);
                      _submitReportForProcessing(frame, report);
                  }
              }
              function _consensusNotReached(ConsensusFrame memory frame) internal {
                  if (_reportingState.lastConsensusRefSlot == frame.refSlot) {
                      _reportingState.lastConsensusRefSlot = 0;
                      emit ConsensusLost(frame.refSlot);
                      _cancelReportProcessing(frame);
                  }
              }
              function _setQuorumAndCheckConsensus(uint256 quorum, uint256 totalMembers) internal {
                  if (quorum <= totalMembers / 2) {
                      revert QuorumTooSmall(totalMembers / 2 + 1, quorum);
                  }
                  // we're explicitly allowing quorum values greater than the number of members to
                  // allow effectively disabling the oracle in case something unpredictable happens
                  uint256 prevQuorum = _quorum;
                  if (quorum != prevQuorum) {
                      _checkRole(
                          quorum == UNREACHABLE_QUORUM ? DISABLE_CONSENSUS_ROLE : MANAGE_MEMBERS_AND_QUORUM_ROLE,
                          _msgSender()
                      );
                      _quorum = quorum;
                      emit QuorumSet(quorum, totalMembers, prevQuorum);
                  }
                  if (_computeEpochAtTimestamp(_getTime()) >= _frameConfig.initialEpoch) {
                      _checkConsensus(quorum);
                  }
              }
              function _checkConsensus(uint256 quorum) internal {
                  uint256 timestamp = _getTime();
                  ConsensusFrame memory frame = _getFrameAtTimestamp(timestamp, _frameConfig);
                  if (_computeSlotAtTimestamp(timestamp) > frame.reportProcessingDeadlineSlot) {
                      // a report for the current ref. slot cannot be processed anymore
                      return;
                  }
                  if (_getLastProcessingRefSlot() >= frame.refSlot) {
                      // a consensus report for the current ref. slot is already being processed
                      return;
                  }
                  (bytes32 consensusReport, int256 consensusVariantIndex, uint256 support) =
                      _getConsensusReport(frame.refSlot, quorum);
                  if (consensusVariantIndex >= 0) {
                      _consensusReached(frame, consensusReport, uint256(consensusVariantIndex), support);
                  } else {
                      _consensusNotReached(frame);
                  }
              }
              function _getConsensusReport(uint256 currentRefSlot, uint256 quorum)
                  internal view returns (bytes32 report, int256 variantIndex, uint256 support)
              {
                  if (_reportingState.lastReportRefSlot != currentRefSlot) {
                      // there were no reports for the current ref. slot
                      return (ZERO_HASH, -1, 0);
                  }
                  uint256 variantsLength = _reportVariantsLength;
                  variantIndex = -1;
                  report = ZERO_HASH;
                  support = 0;
                  for (uint256 i = 0; i < variantsLength; ++i) {
                      uint256 iSupport = _reportVariants[i].support;
                      if (iSupport >= quorum) {
                          variantIndex = int256(i);
                          report = _reportVariants[i].hash;
                          support = iSupport;
                          break;
                      }
                  }
                  return (report, variantIndex, support);
              }
              ///
              /// Implementation: report processing
              ///
              function _setReportProcessor(address newProcessor) internal {
                  address prevProcessor = _reportProcessor;
                  if (newProcessor == address(0)) revert ReportProcessorCannotBeZero();
                  if (newProcessor == prevProcessor) revert NewProcessorCannotBeTheSame();
                  _reportProcessor = newProcessor;
                  emit ReportProcessorSet(newProcessor, prevProcessor);
                  ConsensusFrame memory frame = _getCurrentFrame();
                  uint256 lastConsensusRefSlot = _reportingState.lastConsensusRefSlot;
                  uint256 processingRefSlotPrev = IReportAsyncProcessor(prevProcessor).getLastProcessingRefSlot();
                  uint256 processingRefSlotNext = IReportAsyncProcessor(newProcessor).getLastProcessingRefSlot();
                  if (
                      processingRefSlotPrev < frame.refSlot &&
                      processingRefSlotNext < frame.refSlot &&
                      lastConsensusRefSlot == frame.refSlot
                  ) {
                      bytes32 report = _reportVariants[_reportingState.lastConsensusVariantIndex].hash;
                      _submitReportForProcessing(frame, report);
                  }
              }
              function _getLastProcessingRefSlot() internal view returns (uint256) {
                  return IReportAsyncProcessor(_reportProcessor).getLastProcessingRefSlot();
              }
              function _submitReportForProcessing(ConsensusFrame memory frame, bytes32 report) internal {
                  IReportAsyncProcessor(_reportProcessor).submitConsensusReport(
                      report,
                      frame.refSlot,
                      _computeTimestampAtSlot(frame.reportProcessingDeadlineSlot)
                  );
              }
              function _cancelReportProcessing(ConsensusFrame memory frame) internal {
                  IReportAsyncProcessor(_reportProcessor).discardConsensusReport(frame.refSlot);
              }
              function _getConsensusVersion() internal view returns (uint256) {
                  return IReportAsyncProcessor(_reportProcessor).getConsensusVersion();
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
          //
          // A modified AccessControl contract using unstructured storage. Copied from tree:
          // https://github.com/OpenZeppelin/openzeppelin-contracts/tree/6bd6b76/contracts/access
          //
          /* See contracts/COMPILERS.md */
          pragma solidity 0.8.9;
          import "@openzeppelin/contracts-v4.4/access/IAccessControl.sol";
          import "@openzeppelin/contracts-v4.4/utils/Context.sol";
          import "@openzeppelin/contracts-v4.4/utils/Strings.sol";
          import "@openzeppelin/contracts-v4.4/utils/introspection/ERC165.sol";
          /**
           * @dev Contract module that allows children to implement role-based access
           * control mechanisms. This is a lightweight version that doesn't allow enumerating role
           * members except through off-chain means by accessing the contract event logs. Some
           * applications may benefit from on-chain enumerability, for those cases see
           * {AccessControlEnumerable}.
           *
           * Roles are referred to by their `bytes32` identifier. These should be exposed
           * in the external API and be unique. The best way to achieve this is by
           * using `public constant` hash digests:
           *
           * ```
           * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
           * ```
           *
           * Roles can be used to represent a set of permissions. To restrict access to a
           * function call, use {hasRole}:
           *
           * ```
           * function foo() public {
           *     require(hasRole(MY_ROLE, msg.sender));
           *     ...
           * }
           * ```
           *
           * Roles can be granted and revoked dynamically via the {grantRole} and
           * {revokeRole} functions. Each role has an associated admin role, and only
           * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
           *
           * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
           * that only accounts with this role will be able to grant or revoke other
           * roles. More complex role relationships can be created by using
           * {_setRoleAdmin}.
           *
           * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
           * grant and revoke this role. Extra precautions should be taken to secure
           * accounts that have been granted it.
           */
          abstract contract AccessControl is Context, IAccessControl, ERC165 {
              struct RoleData {
                  mapping(address => bool) members;
                  bytes32 adminRole;
              }
              /// @dev Storage slot: mapping(bytes32 => RoleData) _roles
              bytes32 private constant ROLES_POSITION = keccak256("openzeppelin.AccessControl._roles");
              function _storageRoles() private pure returns (mapping(bytes32 => RoleData) storage _roles) {
                  bytes32 position = ROLES_POSITION;
                  assembly { _roles.slot := position }
              }
              bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
              /**
               * @dev Modifier that checks that an account has a specific role. Reverts
               * with a standardized message including the required role.
               *
               * The format of the revert reason is given by the following regular expression:
               *
               *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
               *
               * _Available since v4.1._
               */
              modifier onlyRole(bytes32 role) {
                  _checkRole(role, _msgSender());
                  _;
              }
              /**
               * @dev See {IERC165-supportsInterface}.
               */
              function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                  return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
              }
              /**
               * @dev Returns `true` if `account` has been granted `role`.
               */
              function hasRole(bytes32 role, address account) public view override returns (bool) {
                  return _storageRoles()[role].members[account];
              }
              /**
               * @dev Revert with a standard message if `account` is missing `role`.
               *
               * The format of the revert reason is given by the following regular expression:
               *
               *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
               */
              function _checkRole(bytes32 role, address account) internal view {
                  if (!hasRole(role, account)) {
                      revert(
                          string(
                              abi.encodePacked(
                                  "AccessControl: account ",
                                  Strings.toHexString(uint160(account), 20),
                                  " is missing role ",
                                  Strings.toHexString(uint256(role), 32)
                              )
                          )
                      );
                  }
              }
              /**
               * @dev Returns the admin role that controls `role`. See {grantRole} and
               * {revokeRole}.
               *
               * To change a role's admin, use {_setRoleAdmin}.
               */
              function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
                  return _storageRoles()[role].adminRole;
              }
              /**
               * @dev Grants `role` to `account`.
               *
               * If `account` had not been already granted `role`, emits a {RoleGranted}
               * event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               */
              function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
                  _grantRole(role, account);
              }
              /**
               * @dev Revokes `role` from `account`.
               *
               * If `account` had been granted `role`, emits a {RoleRevoked} event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               */
              function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
                  _revokeRole(role, account);
              }
              /**
               * @dev Revokes `role` from the calling account.
               *
               * Roles are often managed via {grantRole} and {revokeRole}: this function's
               * purpose is to provide a mechanism for accounts to lose their privileges
               * if they are compromised (such as when a trusted device is misplaced).
               *
               * If the calling account had been revoked `role`, emits a {RoleRevoked}
               * event.
               *
               * Requirements:
               *
               * - the caller must be `account`.
               */
              function renounceRole(bytes32 role, address account) public virtual override {
                  require(account == _msgSender(), "AccessControl: can only renounce roles for self");
                  _revokeRole(role, account);
              }
              /**
               * @dev Grants `role` to `account`.
               *
               * If `account` had not been already granted `role`, emits a {RoleGranted}
               * event. Note that unlike {grantRole}, this function doesn't perform any
               * checks on the calling account.
               *
               * [WARNING]
               * ====
               * This function should only be called from the constructor when setting
               * up the initial roles for the system.
               *
               * Using this function in any other way is effectively circumventing the admin
               * system imposed by {AccessControl}.
               * ====
               *
               * NOTE: This function is deprecated in favor of {_grantRole}.
               */
              function _setupRole(bytes32 role, address account) internal virtual {
                  _grantRole(role, account);
              }
              /**
               * @dev Sets `adminRole` as ``role``'s admin role.
               *
               * Emits a {RoleAdminChanged} event.
               */
              function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
                  bytes32 previousAdminRole = getRoleAdmin(role);
                  _storageRoles()[role].adminRole = adminRole;
                  emit RoleAdminChanged(role, previousAdminRole, adminRole);
              }
              /**
               * @dev Grants `role` to `account`.
               *
               * Internal function without access restriction.
               */
              function _grantRole(bytes32 role, address account) internal virtual {
                  if (!hasRole(role, account)) {
                      _storageRoles()[role].members[account] = true;
                      emit RoleGranted(role, account, _msgSender());
                  }
              }
              /**
               * @dev Revokes `role` from `account`.
               *
               * Internal function without access restriction.
               */
              function _revokeRole(bytes32 role, address account) internal virtual {
                  if (hasRole(role, account)) {
                      _storageRoles()[role].members[account] = false;
                      emit RoleRevoked(role, account, _msgSender());
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (access/AccessControlEnumerable.sol)
          //
          // A modified AccessControlEnumerable contract using unstructured storage. Copied from tree:
          // https://github.com/OpenZeppelin/openzeppelin-contracts/tree/6bd6b76/contracts/access
          //
          /* See contracts/COMPILERS.md */
          pragma solidity 0.8.9;
          import "@openzeppelin/contracts-v4.4/access/IAccessControlEnumerable.sol";
          import "@openzeppelin/contracts-v4.4/utils/structs/EnumerableSet.sol";
          import "./AccessControl.sol";
          /**
           * @dev Extension of {AccessControl} that allows enumerating the members of each role.
           */
          abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
              using EnumerableSet for EnumerableSet.AddressSet;
              /// @dev Storage slot: mapping(bytes32 => EnumerableSet.AddressSet) _roleMembers
              bytes32 private constant ROLE_MEMBERS_POSITION = keccak256("openzeppelin.AccessControlEnumerable._roleMembers");
              function _storageRoleMembers() private pure returns (
                  mapping(bytes32 => EnumerableSet.AddressSet) storage _roleMembers
              ) {
                  bytes32 position = ROLE_MEMBERS_POSITION;
                  assembly { _roleMembers.slot := position }
              }
              /**
               * @dev See {IERC165-supportsInterface}.
               */
              function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                  return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
              }
              /**
               * @dev Returns one of the accounts that have `role`. `index` must be a
               * value between 0 and {getRoleMemberCount}, non-inclusive.
               *
               * Role bearers are not sorted in any particular way, and their ordering may
               * change at any point.
               *
               * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
               * you perform all queries on the same block. See the following
               * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
               * for more information.
               */
              function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
                  return _storageRoleMembers()[role].at(index);
              }
              /**
               * @dev Returns the number of accounts that have `role`. Can be used
               * together with {getRoleMember} to enumerate all bearers of a role.
               */
              function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
                  return _storageRoleMembers()[role].length();
              }
              /**
               * @dev Overload {_grantRole} to track enumerable memberships
               */
              function _grantRole(bytes32 role, address account) internal virtual override {
                  super._grantRole(role, account);
                  _storageRoleMembers()[role].add(account);
              }
              /**
               * @dev Overload {_revokeRole} to track enumerable memberships
               */
              function _revokeRole(bytes32 role, address account) internal virtual override {
                  super._revokeRole(role, account);
                  _storageRoleMembers()[role].remove(account);
              }
          }
          

          File 2 of 3: OssifiableProxy
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev This is the interface that {BeaconProxy} expects of its beacon.
           */
          interface IBeacon {
              /**
               * @dev Must return an address that can be used as a delegate call target.
               *
               * {BeaconProxy} will check that this address is a contract.
               */
              function implementation() external view returns (address);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Proxy.sol)
          pragma solidity ^0.8.0;
          import "../Proxy.sol";
          import "./ERC1967Upgrade.sol";
          /**
           * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
           * implementation address that can be changed. This address is stored in storage in the location specified by
           * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
           * implementation behind the proxy.
           */
          contract ERC1967Proxy is Proxy, ERC1967Upgrade {
              /**
               * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
               *
               * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
               * function call, and allows initializating the storage of the proxy like a Solidity constructor.
               */
              constructor(address _logic, bytes memory _data) payable {
                  assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
                  _upgradeToAndCall(_logic, _data, false);
              }
              /**
               * @dev Returns the current implementation address.
               */
              function _implementation() internal view virtual override returns (address impl) {
                  return ERC1967Upgrade._getImplementation();
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol)
          pragma solidity ^0.8.2;
          import "../beacon/IBeacon.sol";
          import "../../utils/Address.sol";
          import "../../utils/StorageSlot.sol";
          /**
           * @dev This abstract contract provides getters and event emitting update functions for
           * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
           *
           * _Available since v4.1._
           *
           * @custom:oz-upgrades-unsafe-allow delegatecall
           */
          abstract contract ERC1967Upgrade {
              // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
              bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
              /**
               * @dev Storage slot with the address of the current implementation.
               * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
               * validated in the constructor.
               */
              bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
              /**
               * @dev Emitted when the implementation is upgraded.
               */
              event Upgraded(address indexed implementation);
              /**
               * @dev Returns the current implementation address.
               */
              function _getImplementation() internal view returns (address) {
                  return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
              }
              /**
               * @dev Stores a new address in the EIP1967 implementation slot.
               */
              function _setImplementation(address newImplementation) private {
                  require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
                  StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
              }
              /**
               * @dev Perform implementation upgrade
               *
               * Emits an {Upgraded} event.
               */
              function _upgradeTo(address newImplementation) internal {
                  _setImplementation(newImplementation);
                  emit Upgraded(newImplementation);
              }
              /**
               * @dev Perform implementation upgrade with additional setup call.
               *
               * Emits an {Upgraded} event.
               */
              function _upgradeToAndCall(
                  address newImplementation,
                  bytes memory data,
                  bool forceCall
              ) internal {
                  _upgradeTo(newImplementation);
                  if (data.length > 0 || forceCall) {
                      Address.functionDelegateCall(newImplementation, data);
                  }
              }
              /**
               * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
               *
               * Emits an {Upgraded} event.
               */
              function _upgradeToAndCallSecure(
                  address newImplementation,
                  bytes memory data,
                  bool forceCall
              ) internal {
                  address oldImplementation = _getImplementation();
                  // Initial upgrade and setup call
                  _setImplementation(newImplementation);
                  if (data.length > 0 || forceCall) {
                      Address.functionDelegateCall(newImplementation, data);
                  }
                  // Perform rollback test if not already in progress
                  StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT);
                  if (!rollbackTesting.value) {
                      // Trigger rollback using upgradeTo from the new implementation
                      rollbackTesting.value = true;
                      Address.functionDelegateCall(
                          newImplementation,
                          abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
                      );
                      rollbackTesting.value = false;
                      // Check rollback was effective
                      require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
                      // Finally reset to the new implementation and log the upgrade
                      _upgradeTo(newImplementation);
                  }
              }
              /**
               * @dev Storage slot with the admin of the contract.
               * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
               * validated in the constructor.
               */
              bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
              /**
               * @dev Emitted when the admin account has changed.
               */
              event AdminChanged(address previousAdmin, address newAdmin);
              /**
               * @dev Returns the current admin.
               */
              function _getAdmin() internal view returns (address) {
                  return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
              }
              /**
               * @dev Stores a new address in the EIP1967 admin slot.
               */
              function _setAdmin(address newAdmin) private {
                  require(newAdmin != address(0), "ERC1967: new admin is the zero address");
                  StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
              }
              /**
               * @dev Changes the admin of the proxy.
               *
               * Emits an {AdminChanged} event.
               */
              function _changeAdmin(address newAdmin) internal {
                  emit AdminChanged(_getAdmin(), newAdmin);
                  _setAdmin(newAdmin);
              }
              /**
               * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
               * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
               */
              bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
              /**
               * @dev Emitted when the beacon is upgraded.
               */
              event BeaconUpgraded(address indexed beacon);
              /**
               * @dev Returns the current beacon.
               */
              function _getBeacon() internal view returns (address) {
                  return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
              }
              /**
               * @dev Stores a new beacon in the EIP1967 beacon slot.
               */
              function _setBeacon(address newBeacon) private {
                  require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
                  require(
                      Address.isContract(IBeacon(newBeacon).implementation()),
                      "ERC1967: beacon implementation is not a contract"
                  );
                  StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
              }
              /**
               * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
               * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
               *
               * Emits a {BeaconUpgraded} event.
               */
              function _upgradeBeaconToAndCall(
                  address newBeacon,
                  bytes memory data,
                  bool forceCall
              ) internal {
                  _setBeacon(newBeacon);
                  emit BeaconUpgraded(newBeacon);
                  if (data.length > 0 || forceCall) {
                      Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (proxy/Proxy.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
           * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
           * be specified by overriding the virtual {_implementation} function.
           *
           * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
           * different contract through the {_delegate} function.
           *
           * The success and return data of the delegated call will be returned back to the caller of the proxy.
           */
          abstract contract Proxy {
              /**
               * @dev Delegates the current call to `implementation`.
               *
               * This function does not return to its internall call site, it will return directly to the external caller.
               */
              function _delegate(address implementation) internal virtual {
                  assembly {
                      // Copy msg.data. We take full control of memory in this inline assembly
                      // block because it will not return to Solidity code. We overwrite the
                      // Solidity scratch pad at memory position 0.
                      calldatacopy(0, 0, calldatasize())
                      // Call the implementation.
                      // out and outsize are 0 because we don't know the size yet.
                      let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
                      // Copy the returned data.
                      returndatacopy(0, 0, returndatasize())
                      switch result
                      // delegatecall returns 0 on error.
                      case 0 {
                          revert(0, returndatasize())
                      }
                      default {
                          return(0, returndatasize())
                      }
                  }
              }
              /**
               * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
               * and {_fallback} should delegate.
               */
              function _implementation() internal view virtual returns (address);
              /**
               * @dev Delegates the current call to the address returned by `_implementation()`.
               *
               * This function does not return to its internall call site, it will return directly to the external caller.
               */
              function _fallback() internal virtual {
                  _beforeFallback();
                  _delegate(_implementation());
              }
              /**
               * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
               * function in the contract matches the call data.
               */
              fallback() external payable virtual {
                  _fallback();
              }
              /**
               * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
               * is empty.
               */
              receive() external payable virtual {
                  _fallback();
              }
              /**
               * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
               * call, or as part of the Solidity `fallback` or `receive` functions.
               *
               * If overriden should call `super._beforeFallback()`.
               */
              function _beforeFallback() internal virtual {}
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Collection of functions related to the address type
           */
          library Address {
              /**
               * @dev Returns true if `account` is a contract.
               *
               * [IMPORTANT]
               * ====
               * It is unsafe to assume that an address for which this function returns
               * false is an externally-owned account (EOA) and not a contract.
               *
               * Among others, `isContract` will return false for the following
               * types of addresses:
               *
               *  - an externally-owned account
               *  - a contract in construction
               *  - an address where a contract will be created
               *  - an address where a contract lived, but was destroyed
               * ====
               */
              function isContract(address account) internal view returns (bool) {
                  // This method relies on extcodesize, which returns 0 for contracts in
                  // construction, since the code is only stored at the end of the
                  // constructor execution.
                  uint256 size;
                  assembly {
                      size := extcodesize(account)
                  }
                  return size > 0;
              }
              /**
               * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
               * `recipient`, forwarding all available gas and reverting on errors.
               *
               * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
               * of certain opcodes, possibly making contracts go over the 2300 gas limit
               * imposed by `transfer`, making them unable to receive funds via
               * `transfer`. {sendValue} removes this limitation.
               *
               * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
               *
               * IMPORTANT: because control is transferred to `recipient`, care must be
               * taken to not create reentrancy vulnerabilities. Consider using
               * {ReentrancyGuard} or the
               * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
               */
              function sendValue(address payable recipient, uint256 amount) internal {
                  require(address(this).balance >= amount, "Address: insufficient balance");
                  (bool success, ) = recipient.call{value: amount}("");
                  require(success, "Address: unable to send value, recipient may have reverted");
              }
              /**
               * @dev Performs a Solidity function call using a low level `call`. A
               * plain `call` is an unsafe replacement for a function call: use this
               * function instead.
               *
               * If `target` reverts with a revert reason, it is bubbled up by this
               * function (like regular Solidity function calls).
               *
               * Returns the raw returned data. To convert to the expected return value,
               * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
               *
               * Requirements:
               *
               * - `target` must be a contract.
               * - calling `target` with `data` must not revert.
               *
               * _Available since v3.1._
               */
              function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                  return functionCall(target, data, "Address: low-level call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
               * `errorMessage` as a fallback revert reason when `target` reverts.
               *
               * _Available since v3.1._
               */
              function functionCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, 0, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but also transferring `value` wei to `target`.
               *
               * Requirements:
               *
               * - the calling contract must have an ETH balance of at least `value`.
               * - the called Solidity function must be `payable`.
               *
               * _Available since v3.1._
               */
              function functionCallWithValue(
                  address target,
                  bytes memory data,
                  uint256 value
              ) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
              }
              /**
               * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
               * with `errorMessage` as a fallback revert reason when `target` reverts.
               *
               * _Available since v3.1._
               */
              function functionCallWithValue(
                  address target,
                  bytes memory data,
                  uint256 value,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  require(address(this).balance >= value, "Address: insufficient balance for call");
                  require(isContract(target), "Address: call to non-contract");
                  (bool success, bytes memory returndata) = target.call{value: value}(data);
                  return verifyCallResult(success, returndata, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but performing a static call.
               *
               * _Available since v3.3._
               */
              function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                  return functionStaticCall(target, data, "Address: low-level static call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
               * but performing a static call.
               *
               * _Available since v3.3._
               */
              function functionStaticCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  require(isContract(target), "Address: static call to non-contract");
                  (bool success, bytes memory returndata) = target.staticcall(data);
                  return verifyCallResult(success, returndata, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but performing a delegate call.
               *
               * _Available since v3.4._
               */
              function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                  return functionDelegateCall(target, data, "Address: low-level delegate call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
               * but performing a delegate call.
               *
               * _Available since v3.4._
               */
              function functionDelegateCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  require(isContract(target), "Address: delegate call to non-contract");
                  (bool success, bytes memory returndata) = target.delegatecall(data);
                  return verifyCallResult(success, returndata, errorMessage);
              }
              /**
               * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
               * revert reason using the provided one.
               *
               * _Available since v4.3._
               */
              function verifyCallResult(
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal pure returns (bytes memory) {
                  if (success) {
                      return returndata;
                  } else {
                      // Look for revert reason and bubble it up if present
                      if (returndata.length > 0) {
                          // The easiest way to bubble the revert reason is using memory via assembly
                          assembly {
                              let returndata_size := mload(returndata)
                              revert(add(32, returndata), returndata_size)
                          }
                      } else {
                          revert(errorMessage);
                      }
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Library for reading and writing primitive types to specific storage slots.
           *
           * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
           * This library helps with reading and writing to such slots without the need for inline assembly.
           *
           * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
           *
           * Example usage to set ERC1967 implementation slot:
           * ```
           * contract ERC1967 {
           *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
           *
           *     function _getImplementation() internal view returns (address) {
           *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
           *     }
           *
           *     function _setImplementation(address newImplementation) internal {
           *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
           *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
           *     }
           * }
           * ```
           *
           * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
           */
          library StorageSlot {
              struct AddressSlot {
                  address value;
              }
              struct BooleanSlot {
                  bool value;
              }
              struct Bytes32Slot {
                  bytes32 value;
              }
              struct Uint256Slot {
                  uint256 value;
              }
              /**
               * @dev Returns an `AddressSlot` with member `value` located at `slot`.
               */
              function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
               */
              function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
               */
              function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
               */
              function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
                  assembly {
                      r.slot := slot
                  }
              }
          }
          // SPDX-FileCopyrightText: 2023 Lido <[email protected]>
          // SPDX-License-Identifier: GPL-3.0
          /* See contracts/COMPILERS.md */
          pragma solidity 0.8.9;
          import {Address} from "@openzeppelin/contracts-v4.4/utils/Address.sol";
          import {StorageSlot} from "@openzeppelin/contracts-v4.4/utils/StorageSlot.sol";
          import {ERC1967Proxy} from "@openzeppelin/contracts-v4.4/proxy/ERC1967/ERC1967Proxy.sol";
          /// @notice An ossifiable proxy contract. Extends the ERC1967Proxy contract by
          ///     adding admin functionality
          contract OssifiableProxy is ERC1967Proxy {
              /// @dev Initializes the upgradeable proxy with the initial implementation and admin
              /// @param implementation_ Address of the implementation
              /// @param admin_ Address of the admin of the proxy
              /// @param data_ Data used in a delegate call to implementation. The delegate call will be
              ///     skipped if the data is empty bytes
              constructor(
                  address implementation_,
                  address admin_,
                  bytes memory data_
              ) ERC1967Proxy(implementation_, data_) {
                  _changeAdmin(admin_);
              }
              /// @notice Returns the current admin of the proxy
              function proxy__getAdmin() external view returns (address) {
                  return _getAdmin();
              }
              /// @notice Returns the current implementation address
              function proxy__getImplementation() external view returns (address) {
                  return _implementation();
              }
              /// @notice Returns whether the implementation is locked forever
              function proxy__getIsOssified() external view returns (bool) {
                  return _getAdmin() == address(0);
              }
              /// @notice Allows to transfer admin rights to zero address and prevent future
              ///     upgrades of the proxy
              function proxy__ossify() external onlyAdmin {
                  address prevAdmin = _getAdmin();
                  StorageSlot.getAddressSlot(_ADMIN_SLOT).value = address(0);
                  emit AdminChanged(prevAdmin, address(0));
                  emit ProxyOssified();
              }
              /// @notice Changes the admin of the proxy
              /// @param newAdmin_ Address of the new admin
              function proxy__changeAdmin(address newAdmin_) external onlyAdmin {
                  _changeAdmin(newAdmin_);
              }
              /// @notice Upgrades the implementation of the proxy
              /// @param newImplementation_ Address of the new implementation
              function proxy__upgradeTo(address newImplementation_) external onlyAdmin {
                  _upgradeTo(newImplementation_);
              }
              /// @notice Upgrades the proxy to a new implementation, optionally performing an additional
              ///     setup call.
              /// @param newImplementation_ Address of the new implementation
              /// @param setupCalldata_ Data for the setup call. The call is skipped if setupCalldata_ is
              ///     empty and forceCall_ is false
              /// @param forceCall_ Forces make delegate call to the implementation even with empty data_
              function proxy__upgradeToAndCall(
                  address newImplementation_,
                  bytes memory setupCalldata_,
                  bool forceCall_
              ) external onlyAdmin {
                  _upgradeToAndCall(newImplementation_, setupCalldata_, forceCall_);
              }
              /// @dev Validates that proxy is not ossified and that method is called by the admin
              ///     of the proxy
              modifier onlyAdmin() {
                  address admin = _getAdmin();
                  if (admin == address(0)) {
                      revert ProxyIsOssified();
                  }
                  if (admin != msg.sender) {
                      revert NotAdmin();
                  }
                  _;
              }
              event ProxyOssified();
              error NotAdmin();
              error ProxyIsOssified();
          }
          

          File 3 of 3: ValidatorsExitBusOracle
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev External interface of AccessControl declared to support ERC165 detection.
           */
          interface IAccessControl {
              /**
               * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
               *
               * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
               * {RoleAdminChanged} not being emitted signaling this.
               *
               * _Available since v3.1._
               */
              event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
              /**
               * @dev Emitted when `account` is granted `role`.
               *
               * `sender` is the account that originated the contract call, an admin role
               * bearer except when using {AccessControl-_setupRole}.
               */
              event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
              /**
               * @dev Emitted when `account` is revoked `role`.
               *
               * `sender` is the account that originated the contract call:
               *   - if using `revokeRole`, it is the admin role bearer
               *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
               */
              event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
              /**
               * @dev Returns `true` if `account` has been granted `role`.
               */
              function hasRole(bytes32 role, address account) external view returns (bool);
              /**
               * @dev Returns the admin role that controls `role`. See {grantRole} and
               * {revokeRole}.
               *
               * To change a role's admin, use {AccessControl-_setRoleAdmin}.
               */
              function getRoleAdmin(bytes32 role) external view returns (bytes32);
              /**
               * @dev Grants `role` to `account`.
               *
               * If `account` had not been already granted `role`, emits a {RoleGranted}
               * event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               */
              function grantRole(bytes32 role, address account) external;
              /**
               * @dev Revokes `role` from `account`.
               *
               * If `account` had been granted `role`, emits a {RoleRevoked} event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               */
              function revokeRole(bytes32 role, address account) external;
              /**
               * @dev Revokes `role` from the calling account.
               *
               * Roles are often managed via {grantRole} and {revokeRole}: this function's
               * purpose is to provide a mechanism for accounts to lose their privileges
               * if they are compromised (such as when a trusted device is misplaced).
               *
               * If the calling account had been granted `role`, emits a {RoleRevoked}
               * event.
               *
               * Requirements:
               *
               * - the caller must be `account`.
               */
              function renounceRole(bytes32 role, address account) external;
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
          pragma solidity ^0.8.0;
          import "./IAccessControl.sol";
          /**
           * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
           */
          interface IAccessControlEnumerable is IAccessControl {
              /**
               * @dev Returns one of the accounts that have `role`. `index` must be a
               * value between 0 and {getRoleMemberCount}, non-inclusive.
               *
               * Role bearers are not sorted in any particular way, and their ordering may
               * change at any point.
               *
               * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
               * you perform all queries on the same block. See the following
               * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
               * for more information.
               */
              function getRoleMember(bytes32 role, uint256 index) external view returns (address);
              /**
               * @dev Returns the number of accounts that have `role`. Can be used
               * together with {getRoleMember} to enumerate all bearers of a role.
               */
              function getRoleMemberCount(bytes32 role) external view returns (uint256);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Provides information about the current execution context, including the
           * sender of the transaction and its data. While these are generally available
           * via msg.sender and msg.data, they should not be accessed in such a direct
           * manner, since when dealing with meta-transactions the account sending and
           * paying for execution may not be the actual sender (as far as an application
           * is concerned).
           *
           * This contract is only required for intermediate, library-like contracts.
           */
          abstract contract Context {
              function _msgSender() internal view virtual returns (address) {
                  return msg.sender;
              }
              function _msgData() internal view virtual returns (bytes calldata) {
                  return msg.data;
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
          pragma solidity ^0.8.0;
          import "./IERC165.sol";
          /**
           * @dev Implementation of the {IERC165} interface.
           *
           * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
           * for the additional interface id that will be supported. For example:
           *
           * ```solidity
           * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
           *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
           * }
           * ```
           *
           * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
           */
          abstract contract ERC165 is IERC165 {
              /**
               * @dev See {IERC165-supportsInterface}.
               */
              function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                  return interfaceId == type(IERC165).interfaceId;
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Interface of the ERC165 standard, as defined in the
           * https://eips.ethereum.org/EIPS/eip-165[EIP].
           *
           * Implementers can declare support of contract interfaces, which can then be
           * queried by others ({ERC165Checker}).
           *
           * For an implementation, see {ERC165}.
           */
          interface IERC165 {
              /**
               * @dev Returns true if this contract implements the interface defined by
               * `interfaceId`. See the corresponding
               * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
               * to learn more about how these ids are created.
               *
               * This function call must use less than 30 000 gas.
               */
              function supportsInterface(bytes4 interfaceId) external view returns (bool);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
           * checks.
           *
           * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
           * easily result in undesired exploitation or bugs, since developers usually
           * assume that overflows raise errors. `SafeCast` restores this intuition by
           * reverting the transaction when such an operation overflows.
           *
           * Using this library instead of the unchecked operations eliminates an entire
           * class of bugs, so it's recommended to use it always.
           *
           * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
           * all math on `uint256` and `int256` and then downcasting.
           */
          library SafeCast {
              /**
               * @dev Returns the downcasted uint224 from uint256, reverting on
               * overflow (when the input is greater than largest uint224).
               *
               * Counterpart to Solidity's `uint224` operator.
               *
               * Requirements:
               *
               * - input must fit into 224 bits
               */
              function toUint224(uint256 value) internal pure returns (uint224) {
                  require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
                  return uint224(value);
              }
              /**
               * @dev Returns the downcasted uint128 from uint256, reverting on
               * overflow (when the input is greater than largest uint128).
               *
               * Counterpart to Solidity's `uint128` operator.
               *
               * Requirements:
               *
               * - input must fit into 128 bits
               */
              function toUint128(uint256 value) internal pure returns (uint128) {
                  require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
                  return uint128(value);
              }
              /**
               * @dev Returns the downcasted uint96 from uint256, reverting on
               * overflow (when the input is greater than largest uint96).
               *
               * Counterpart to Solidity's `uint96` operator.
               *
               * Requirements:
               *
               * - input must fit into 96 bits
               */
              function toUint96(uint256 value) internal pure returns (uint96) {
                  require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
                  return uint96(value);
              }
              /**
               * @dev Returns the downcasted uint64 from uint256, reverting on
               * overflow (when the input is greater than largest uint64).
               *
               * Counterpart to Solidity's `uint64` operator.
               *
               * Requirements:
               *
               * - input must fit into 64 bits
               */
              function toUint64(uint256 value) internal pure returns (uint64) {
                  require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
                  return uint64(value);
              }
              /**
               * @dev Returns the downcasted uint32 from uint256, reverting on
               * overflow (when the input is greater than largest uint32).
               *
               * Counterpart to Solidity's `uint32` operator.
               *
               * Requirements:
               *
               * - input must fit into 32 bits
               */
              function toUint32(uint256 value) internal pure returns (uint32) {
                  require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
                  return uint32(value);
              }
              /**
               * @dev Returns the downcasted uint16 from uint256, reverting on
               * overflow (when the input is greater than largest uint16).
               *
               * Counterpart to Solidity's `uint16` operator.
               *
               * Requirements:
               *
               * - input must fit into 16 bits
               */
              function toUint16(uint256 value) internal pure returns (uint16) {
                  require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
                  return uint16(value);
              }
              /**
               * @dev Returns the downcasted uint8 from uint256, reverting on
               * overflow (when the input is greater than largest uint8).
               *
               * Counterpart to Solidity's `uint8` operator.
               *
               * Requirements:
               *
               * - input must fit into 8 bits.
               */
              function toUint8(uint256 value) internal pure returns (uint8) {
                  require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
                  return uint8(value);
              }
              /**
               * @dev Converts a signed int256 into an unsigned uint256.
               *
               * Requirements:
               *
               * - input must be greater than or equal to 0.
               */
              function toUint256(int256 value) internal pure returns (uint256) {
                  require(value >= 0, "SafeCast: value must be positive");
                  return uint256(value);
              }
              /**
               * @dev Returns the downcasted int128 from int256, reverting on
               * overflow (when the input is less than smallest int128 or
               * greater than largest int128).
               *
               * Counterpart to Solidity's `int128` operator.
               *
               * Requirements:
               *
               * - input must fit into 128 bits
               *
               * _Available since v3.1._
               */
              function toInt128(int256 value) internal pure returns (int128) {
                  require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
                  return int128(value);
              }
              /**
               * @dev Returns the downcasted int64 from int256, reverting on
               * overflow (when the input is less than smallest int64 or
               * greater than largest int64).
               *
               * Counterpart to Solidity's `int64` operator.
               *
               * Requirements:
               *
               * - input must fit into 64 bits
               *
               * _Available since v3.1._
               */
              function toInt64(int256 value) internal pure returns (int64) {
                  require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
                  return int64(value);
              }
              /**
               * @dev Returns the downcasted int32 from int256, reverting on
               * overflow (when the input is less than smallest int32 or
               * greater than largest int32).
               *
               * Counterpart to Solidity's `int32` operator.
               *
               * Requirements:
               *
               * - input must fit into 32 bits
               *
               * _Available since v3.1._
               */
              function toInt32(int256 value) internal pure returns (int32) {
                  require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
                  return int32(value);
              }
              /**
               * @dev Returns the downcasted int16 from int256, reverting on
               * overflow (when the input is less than smallest int16 or
               * greater than largest int16).
               *
               * Counterpart to Solidity's `int16` operator.
               *
               * Requirements:
               *
               * - input must fit into 16 bits
               *
               * _Available since v3.1._
               */
              function toInt16(int256 value) internal pure returns (int16) {
                  require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
                  return int16(value);
              }
              /**
               * @dev Returns the downcasted int8 from int256, reverting on
               * overflow (when the input is less than smallest int8 or
               * greater than largest int8).
               *
               * Counterpart to Solidity's `int8` operator.
               *
               * Requirements:
               *
               * - input must fit into 8 bits.
               *
               * _Available since v3.1._
               */
              function toInt8(int256 value) internal pure returns (int8) {
                  require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
                  return int8(value);
              }
              /**
               * @dev Converts an unsigned uint256 into a signed int256.
               *
               * Requirements:
               *
               * - input must be less than or equal to maxInt256.
               */
              function toInt256(uint256 value) internal pure returns (int256) {
                  // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
                  require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
                  return int256(value);
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev String operations.
           */
          library Strings {
              bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
              /**
               * @dev Converts a `uint256` to its ASCII `string` decimal representation.
               */
              function toString(uint256 value) internal pure returns (string memory) {
                  // Inspired by OraclizeAPI's implementation - MIT licence
                  // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
                  if (value == 0) {
                      return "0";
                  }
                  uint256 temp = value;
                  uint256 digits;
                  while (temp != 0) {
                      digits++;
                      temp /= 10;
                  }
                  bytes memory buffer = new bytes(digits);
                  while (value != 0) {
                      digits -= 1;
                      buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
                      value /= 10;
                  }
                  return string(buffer);
              }
              /**
               * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
               */
              function toHexString(uint256 value) internal pure returns (string memory) {
                  if (value == 0) {
                      return "0x00";
                  }
                  uint256 temp = value;
                  uint256 length = 0;
                  while (temp != 0) {
                      length++;
                      temp >>= 8;
                  }
                  return toHexString(value, length);
              }
              /**
               * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
               */
              function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
                  bytes memory buffer = new bytes(2 * length + 2);
                  buffer[0] = "0";
                  buffer[1] = "x";
                  for (uint256 i = 2 * length + 1; i > 1; --i) {
                      buffer[i] = _HEX_SYMBOLS[value & 0xf];
                      value >>= 4;
                  }
                  require(value == 0, "Strings: hex length insufficient");
                  return string(buffer);
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Library for managing
           * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
           * types.
           *
           * Sets have the following properties:
           *
           * - Elements are added, removed, and checked for existence in constant time
           * (O(1)).
           * - Elements are enumerated in O(n). No guarantees are made on the ordering.
           *
           * ```
           * contract Example {
           *     // Add the library methods
           *     using EnumerableSet for EnumerableSet.AddressSet;
           *
           *     // Declare a set state variable
           *     EnumerableSet.AddressSet private mySet;
           * }
           * ```
           *
           * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
           * and `uint256` (`UintSet`) are supported.
           */
          library EnumerableSet {
              // To implement this library for multiple types with as little code
              // repetition as possible, we write it in terms of a generic Set type with
              // bytes32 values.
              // The Set implementation uses private functions, and user-facing
              // implementations (such as AddressSet) are just wrappers around the
              // underlying Set.
              // This means that we can only create new EnumerableSets for types that fit
              // in bytes32.
              struct Set {
                  // Storage of set values
                  bytes32[] _values;
                  // Position of the value in the `values` array, plus 1 because index 0
                  // means a value is not in the set.
                  mapping(bytes32 => uint256) _indexes;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function _add(Set storage set, bytes32 value) private returns (bool) {
                  if (!_contains(set, value)) {
                      set._values.push(value);
                      // The value is stored at length-1, but we add 1 to all indexes
                      // and use 0 as a sentinel value
                      set._indexes[value] = set._values.length;
                      return true;
                  } else {
                      return false;
                  }
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function _remove(Set storage set, bytes32 value) private returns (bool) {
                  // We read and store the value's index to prevent multiple reads from the same storage slot
                  uint256 valueIndex = set._indexes[value];
                  if (valueIndex != 0) {
                      // Equivalent to contains(set, value)
                      // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
                      // the array, and then remove the last element (sometimes called as 'swap and pop').
                      // This modifies the order of the array, as noted in {at}.
                      uint256 toDeleteIndex = valueIndex - 1;
                      uint256 lastIndex = set._values.length - 1;
                      if (lastIndex != toDeleteIndex) {
                          bytes32 lastvalue = set._values[lastIndex];
                          // Move the last value to the index where the value to delete is
                          set._values[toDeleteIndex] = lastvalue;
                          // Update the index for the moved value
                          set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
                      }
                      // Delete the slot where the moved value was stored
                      set._values.pop();
                      // Delete the index for the deleted slot
                      delete set._indexes[value];
                      return true;
                  } else {
                      return false;
                  }
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function _contains(Set storage set, bytes32 value) private view returns (bool) {
                  return set._indexes[value] != 0;
              }
              /**
               * @dev Returns the number of values on the set. O(1).
               */
              function _length(Set storage set) private view returns (uint256) {
                  return set._values.length;
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function _at(Set storage set, uint256 index) private view returns (bytes32) {
                  return set._values[index];
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function _values(Set storage set) private view returns (bytes32[] memory) {
                  return set._values;
              }
              // Bytes32Set
              struct Bytes32Set {
                  Set _inner;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                  return _add(set._inner, value);
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                  return _remove(set._inner, value);
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
                  return _contains(set._inner, value);
              }
              /**
               * @dev Returns the number of values in the set. O(1).
               */
              function length(Bytes32Set storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
                  return _at(set._inner, index);
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
                  return _values(set._inner);
              }
              // AddressSet
              struct AddressSet {
                  Set _inner;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(AddressSet storage set, address value) internal returns (bool) {
                  return _add(set._inner, bytes32(uint256(uint160(value))));
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(AddressSet storage set, address value) internal returns (bool) {
                  return _remove(set._inner, bytes32(uint256(uint160(value))));
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(AddressSet storage set, address value) internal view returns (bool) {
                  return _contains(set._inner, bytes32(uint256(uint160(value))));
              }
              /**
               * @dev Returns the number of values in the set. O(1).
               */
              function length(AddressSet storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(AddressSet storage set, uint256 index) internal view returns (address) {
                  return address(uint160(uint256(_at(set._inner, index))));
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(AddressSet storage set) internal view returns (address[] memory) {
                  bytes32[] memory store = _values(set._inner);
                  address[] memory result;
                  assembly {
                      result := store
                  }
                  return result;
              }
              // UintSet
              struct UintSet {
                  Set _inner;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(UintSet storage set, uint256 value) internal returns (bool) {
                  return _add(set._inner, bytes32(value));
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(UintSet storage set, uint256 value) internal returns (bool) {
                  return _remove(set._inner, bytes32(value));
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(UintSet storage set, uint256 value) internal view returns (bool) {
                  return _contains(set._inner, bytes32(value));
              }
              /**
               * @dev Returns the number of values on the set. O(1).
               */
              function length(UintSet storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(UintSet storage set, uint256 index) internal view returns (uint256) {
                  return uint256(_at(set._inner, index));
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(UintSet storage set) internal view returns (uint256[] memory) {
                  bytes32[] memory store = _values(set._inner);
                  uint256[] memory result;
                  assembly {
                      result := store
                  }
                  return result;
              }
          }
          // SPDX-FileCopyrightText: 2023 Lido <[email protected]>
          // SPDX-License-Identifier: MIT
          // See contracts/COMPILERS.md
          pragma solidity 0.8.9;
          library Math {
              function max(uint256 a, uint256 b) internal pure returns (uint256) {
                  return a > b ? a : b;
              }
              function min(uint256 a, uint256 b) internal pure returns (uint256) {
                  return a < b ? a : b;
              }
              /// @notice Tests if x ∈ [a, b) (mod n)
              ///
              function pointInHalfOpenIntervalModN(uint256 x, uint256 a, uint256 b, uint256 n)
                  internal pure returns (bool)
              {
                  return (x + n - a) % n < (b - a) % n;
              }
              /// @notice Tests if x ∈ [a, b] (mod n)
              ///
              function pointInClosedIntervalModN(uint256 x, uint256 a, uint256 b, uint256 n)
                  internal pure returns (bool)
              {
                  return (x + n - a) % n <= (b - a) % n;
              }
          }
          /*
           * SPDX-License-Identifier: MIT
           */
          pragma solidity 0.8.9;
          /**
           * @notice Aragon Unstructured Storage library
           */
          library UnstructuredStorage {
              function getStorageBool(bytes32 position) internal view returns (bool data) {
                  assembly { data := sload(position) }
              }
              function getStorageAddress(bytes32 position) internal view returns (address data) {
                  assembly { data := sload(position) }
              }
              function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) {
                  assembly { data := sload(position) }
              }
              function getStorageUint256(bytes32 position) internal view returns (uint256 data) {
                  assembly { data := sload(position) }
              }
              function setStorageBool(bytes32 position, bool data) internal {
                  assembly { sstore(position, data) }
              }
              function setStorageAddress(bytes32 position, address data) internal {
                  assembly { sstore(position, data) }
              }
              function setStorageBytes32(bytes32 position, bytes32 data) internal {
                  assembly { sstore(position, data) }
              }
              function setStorageUint256(bytes32 position, uint256 data) internal {
                  assembly { sstore(position, data) }
              }
          }
          // SPDX-FileCopyrightText: 2023 Lido <[email protected]>
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity 0.8.9;
          import { SafeCast } from "@openzeppelin/contracts-v4.4/utils/math/SafeCast.sol";
          import { UnstructuredStorage } from "../lib/UnstructuredStorage.sol";
          import { Versioned } from "../utils/Versioned.sol";
          import { AccessControlEnumerable } from "../utils/access/AccessControlEnumerable.sol";
          import { IReportAsyncProcessor } from "./HashConsensus.sol";
          interface IConsensusContract {
              function getIsMember(address addr) external view returns (bool);
              function getCurrentFrame() external view returns (
                  uint256 refSlot,
                  uint256 reportProcessingDeadlineSlot
              );
              function getChainConfig() external view returns (
                  uint256 slotsPerEpoch,
                  uint256 secondsPerSlot,
                  uint256 genesisTime
              );
              function getFrameConfig() external view returns (uint256 initialEpoch, uint256 epochsPerFrame);
              function getInitialRefSlot() external view returns (uint256);
          }
          abstract contract BaseOracle is IReportAsyncProcessor, AccessControlEnumerable, Versioned {
              using UnstructuredStorage for bytes32;
              using SafeCast for uint256;
              error AddressCannotBeZero();
              error AddressCannotBeSame();
              error VersionCannotBeSame();
              error UnexpectedChainConfig();
              error SenderIsNotTheConsensusContract();
              error InitialRefSlotCannotBeLessThanProcessingOne(uint256 initialRefSlot, uint256 processingRefSlot);
              error RefSlotMustBeGreaterThanProcessingOne(uint256 refSlot, uint256 processingRefSlot);
              error RefSlotCannotDecrease(uint256 refSlot, uint256 prevRefSlot);
              error NoConsensusReportToProcess();
              error ProcessingDeadlineMissed(uint256 deadline);
              error RefSlotAlreadyProcessing();
              error UnexpectedRefSlot(uint256 consensusRefSlot, uint256 dataRefSlot);
              error UnexpectedConsensusVersion(uint256 expectedVersion, uint256 receivedVersion);
              error HashCannotBeZero();
              error UnexpectedDataHash(bytes32 consensusHash, bytes32 receivedHash);
              error SecondsPerSlotCannotBeZero();
              event ConsensusHashContractSet(address indexed addr, address indexed prevAddr);
              event ConsensusVersionSet(uint256 indexed version, uint256 indexed prevVersion);
              event ReportSubmitted(uint256 indexed refSlot, bytes32 hash, uint256 processingDeadlineTime);
              event ReportDiscarded(uint256 indexed refSlot, bytes32 hash);
              event ProcessingStarted(uint256 indexed refSlot, bytes32 hash);
              event WarnProcessingMissed(uint256 indexed refSlot);
              struct ConsensusReport {
                  bytes32 hash;
                  uint64 refSlot;
                  uint64 processingDeadlineTime;
              }
              /// @notice An ACL role granting the permission to set the consensus
              /// contract address by calling setConsensusContract.
              bytes32 public constant MANAGE_CONSENSUS_CONTRACT_ROLE =
                  keccak256("MANAGE_CONSENSUS_CONTRACT_ROLE");
              /// @notice An ACL role granting the permission to set the consensus
              /// version by calling setConsensusVersion.
              bytes32 public constant MANAGE_CONSENSUS_VERSION_ROLE =
                  keccak256("MANAGE_CONSENSUS_VERSION_ROLE");
              /// @dev Storage slot: address consensusContract
              bytes32 internal constant CONSENSUS_CONTRACT_POSITION =
                  keccak256("lido.BaseOracle.consensusContract");
              /// @dev Storage slot: uint256 consensusVersion
              bytes32 internal constant CONSENSUS_VERSION_POSITION =
                  keccak256("lido.BaseOracle.consensusVersion");
              /// @dev Storage slot: uint256 lastProcessingRefSlot
              bytes32 internal constant LAST_PROCESSING_REF_SLOT_POSITION =
                  keccak256("lido.BaseOracle.lastProcessingRefSlot");
              /// @dev Storage slot: ConsensusReport consensusReport
              bytes32 internal constant CONSENSUS_REPORT_POSITION =
                  keccak256("lido.BaseOracle.consensusReport");
              uint256 public immutable SECONDS_PER_SLOT;
              uint256 public immutable GENESIS_TIME;
              ///
              /// Initialization & admin functions
              ///
              constructor(uint256 secondsPerSlot, uint256 genesisTime) {
                  if (secondsPerSlot == 0) revert SecondsPerSlotCannotBeZero();
                  SECONDS_PER_SLOT = secondsPerSlot;
                  GENESIS_TIME = genesisTime;
              }
              /// @notice Returns the address of the HashConsensus contract.
              ///
              function getConsensusContract() external view returns (address) {
                  return CONSENSUS_CONTRACT_POSITION.getStorageAddress();
              }
              /// @notice Sets the address of the HashConsensus contract.
              ///
              function setConsensusContract(address addr) external onlyRole(MANAGE_CONSENSUS_CONTRACT_ROLE) {
                  _setConsensusContract(addr, LAST_PROCESSING_REF_SLOT_POSITION.getStorageUint256());
              }
              /// @notice Returns the current consensus version expected by the oracle contract.
              ///
              /// Consensus version must change every time consensus rules change, meaning that
              /// an oracle looking at the same reference slot would calculate a different hash.
              ///
              function getConsensusVersion() external view returns (uint256) {
                  return CONSENSUS_VERSION_POSITION.getStorageUint256();
              }
              /// @notice Sets the consensus version expected by the oracle contract.
              ///
              function setConsensusVersion(uint256 version) external onlyRole(MANAGE_CONSENSUS_VERSION_ROLE) {
                  _setConsensusVersion(version);
              }
              ///
              /// Data provider interface
              ///
              /// @notice Returns the last consensus report hash and metadata.
              ///
              function getConsensusReport() external view returns (
                  bytes32 hash,
                  uint256 refSlot,
                  uint256 processingDeadlineTime,
                  bool processingStarted
              ) {
                  ConsensusReport memory report = _storageConsensusReport().value;
                  uint256 processingRefSlot = LAST_PROCESSING_REF_SLOT_POSITION.getStorageUint256();
                  return (
                      report.hash,
                      report.refSlot,
                      report.processingDeadlineTime,
                      report.hash != bytes32(0) && report.refSlot == processingRefSlot
                  );
              }
              ///
              /// Consensus contract interface
              ///
              /// @notice Called by HashConsensus contract to push a consensus report for processing.
              ///
              /// Note that submitting the report doesn't require the processor to start processing it right
              /// away, this can happen later (see `getLastProcessingRefSlot`). Until processing is started,
              /// HashConsensus is free to reach consensus on another report for the same reporting frame an
              /// submit it using this same function, or to lose the consensus on the submitted report,
              /// notifying the processor via `discardConsensusReport`.
              ///
              function submitConsensusReport(bytes32 reportHash, uint256 refSlot, uint256 deadline) external {
                  _checkSenderIsConsensusContract();
                  uint256 prevSubmittedRefSlot = _storageConsensusReport().value.refSlot;
                  if (refSlot < prevSubmittedRefSlot) {
                      revert RefSlotCannotDecrease(refSlot, prevSubmittedRefSlot);
                  }
                  uint256 prevProcessingRefSlot = LAST_PROCESSING_REF_SLOT_POSITION.getStorageUint256();
                  if (refSlot <= prevProcessingRefSlot) {
                      revert RefSlotMustBeGreaterThanProcessingOne(refSlot, prevProcessingRefSlot);
                  }
                  if (_getTime() > deadline) {
                      revert ProcessingDeadlineMissed(deadline);
                  }
                  if (refSlot != prevSubmittedRefSlot && prevProcessingRefSlot != prevSubmittedRefSlot) {
                      emit WarnProcessingMissed(prevSubmittedRefSlot);
                  }
                  if (reportHash == bytes32(0)) {
                      revert HashCannotBeZero();
                  }
                  emit ReportSubmitted(refSlot, reportHash, deadline);
                  ConsensusReport memory report = ConsensusReport({
                      hash: reportHash,
                      refSlot: refSlot.toUint64(),
                      processingDeadlineTime: deadline.toUint64()
                  });
                  _storageConsensusReport().value = report;
                  _handleConsensusReport(report, prevSubmittedRefSlot, prevProcessingRefSlot);
              }
              /// @notice Called by HashConsensus contract to notify that the report for the given ref. slot
              /// is not a conensus report anymore and should be discarded. This can happen when a member
              /// changes their report, is removed from the set, or when the quorum value gets increased.
              ///
              /// Only called when, for the given reference slot:
              ///
              ///   1. there previously was a consensus report; AND
              ///   1. processing of the consensus report hasn't started yet; AND
              ///   2. report processing deadline is not expired yet; AND
              ///   3. there's no consensus report now (otherwise, `submitConsensusReport` is called instead).
              ///
              /// Can be called even when there's no submitted non-discarded consensus report for the current
              /// reference slot, i.e. can be called multiple times in succession.
              ///
              function discardConsensusReport(uint256 refSlot) external {
                  _checkSenderIsConsensusContract();
                  ConsensusReport memory submittedReport = _storageConsensusReport().value;
                  if (refSlot < submittedReport.refSlot) {
                      revert RefSlotCannotDecrease(refSlot, submittedReport.refSlot);
                  } else if (refSlot > submittedReport.refSlot) {
                      return;
                  }
                  uint256 lastProcessingRefSlot = LAST_PROCESSING_REF_SLOT_POSITION.getStorageUint256();
                  if (refSlot <= lastProcessingRefSlot) {
                      revert RefSlotAlreadyProcessing();
                  }
                  _storageConsensusReport().value.hash = bytes32(0);
                  _handleConsensusReportDiscarded(submittedReport);
                  emit ReportDiscarded(submittedReport.refSlot, submittedReport.hash);
              }
              /// @notice Returns the last reference slot for which processing of the report was started.
              ///
              function getLastProcessingRefSlot() external view returns (uint256) {
                  return LAST_PROCESSING_REF_SLOT_POSITION.getStorageUint256();
              }
              ///
              /// Descendant contract interface
              ///
              /// @notice Initializes the contract storage. Must be called by a descendant
              /// contract as part of its initialization.
              ///
              function _initialize(
                  address consensusContract,
                  uint256 consensusVersion,
                  uint256 lastProcessingRefSlot
              ) internal virtual {
                  _initializeContractVersionTo(1);
                  _setConsensusContract(consensusContract, lastProcessingRefSlot);
                  _setConsensusVersion(consensusVersion);
                  LAST_PROCESSING_REF_SLOT_POSITION.setStorageUint256(lastProcessingRefSlot);
                  _storageConsensusReport().value.refSlot = lastProcessingRefSlot.toUint64();
              }
              /// @notice Returns whether the given address is a member of the oracle committee.
              ///
              function _isConsensusMember(address addr) internal view returns (bool) {
                  address consensus = CONSENSUS_CONTRACT_POSITION.getStorageAddress();
                  return IConsensusContract(consensus).getIsMember(addr);
              }
              /// @notice Called when the oracle gets a new consensus report from the HashConsensus contract.
              ///
              /// Keep in mind that, until you call `_startProcessing`, the oracle committee is free to
              /// reach consensus on another report for the same reporting frame and re-submit it using
              /// this function, or lose consensus on the report and ask to discard it by calling the
              /// `_handleConsensusReportDiscarded` function.
              ///
              function _handleConsensusReport(
                  ConsensusReport memory report,
                  uint256 prevSubmittedRefSlot,
                  uint256 prevProcessingRefSlot
              ) internal virtual;
              /// @notice Called when the HashConsensus contract loses consensus on a previously submitted
              /// report that is not processing yet and asks to discard this report. Only called if there is
              /// no new consensus report at the moment; otherwise, `_handleConsensusReport` is called instead.
              ///
              function _handleConsensusReportDiscarded(ConsensusReport memory report) internal virtual {}
              /// @notice May be called by a descendant contract to check if the received data matches
              /// the currently submitted consensus report. Reverts otherwise.
              ///
              function _checkConsensusData(uint256 refSlot, uint256 consensusVersion, bytes32 hash)
                  internal view
              {
                  ConsensusReport memory report = _storageConsensusReport().value;
                  if (refSlot != report.refSlot) {
                      revert UnexpectedRefSlot(report.refSlot, refSlot);
                  }
                  uint256 expectedConsensusVersion = CONSENSUS_VERSION_POSITION.getStorageUint256();
                  if (consensusVersion != expectedConsensusVersion) {
                      revert UnexpectedConsensusVersion(expectedConsensusVersion, consensusVersion);
                  }
                  if (hash != report.hash) {
                      revert UnexpectedDataHash(report.hash, hash);
                  }
              }
              /// @notice Called by a descendant contract to mark the current consensus report
              /// as being processed. Returns the last ref. slot which processing was started
              /// before the call.
              ///
              /// Before this function is called, the oracle committee is free to reach consensus
              /// on another report for the same reporting frame. After this function is called,
              /// the consensus report for the current frame is guaranteed to remain the same.
              ///
              function _startProcessing() internal returns (uint256) {
                  ConsensusReport memory report = _storageConsensusReport().value;
                  if (report.hash == bytes32(0)) {
                      revert NoConsensusReportToProcess();
                  }
                  _checkProcessingDeadline(report.processingDeadlineTime);
                  uint256 prevProcessingRefSlot = LAST_PROCESSING_REF_SLOT_POSITION.getStorageUint256();
                  if (prevProcessingRefSlot == report.refSlot) {
                      revert RefSlotAlreadyProcessing();
                  }
                  LAST_PROCESSING_REF_SLOT_POSITION.setStorageUint256(report.refSlot);
                  emit ProcessingStarted(report.refSlot, report.hash);
                  return prevProcessingRefSlot;
              }
              /// @notice Reverts if the processing deadline for the current consensus report is missed.
              ///
              function _checkProcessingDeadline() internal view {
                  _checkProcessingDeadline(_storageConsensusReport().value.processingDeadlineTime);
              }
              function _checkProcessingDeadline(uint256 deadlineTime) internal view {
                  if (_getTime() > deadlineTime) revert ProcessingDeadlineMissed(deadlineTime);
              }
              /// @notice Returns the reference slot for the current frame.
              ///
              function _getCurrentRefSlot() internal view returns (uint256) {
                  address consensusContract = CONSENSUS_CONTRACT_POSITION.getStorageAddress();
                  (uint256 refSlot, ) = IConsensusContract(consensusContract).getCurrentFrame();
                  return refSlot;
              }
              ///
              /// Implementation & helpers
              ///
              function _setConsensusVersion(uint256 version) internal {
                  uint256 prevVersion = CONSENSUS_VERSION_POSITION.getStorageUint256();
                  if (version == prevVersion) revert VersionCannotBeSame();
                  CONSENSUS_VERSION_POSITION.setStorageUint256(version);
                  emit ConsensusVersionSet(version, prevVersion);
              }
              function _setConsensusContract(address addr, uint256 lastProcessingRefSlot) internal {
                  if (addr == address(0)) revert AddressCannotBeZero();
                  address prevAddr = CONSENSUS_CONTRACT_POSITION.getStorageAddress();
                  if (addr == prevAddr) revert AddressCannotBeSame();
                  (, uint256 secondsPerSlot, uint256 genesisTime) = IConsensusContract(addr).getChainConfig();
                  if (secondsPerSlot != SECONDS_PER_SLOT || genesisTime != GENESIS_TIME) {
                      revert UnexpectedChainConfig();
                  }
                  uint256 initialRefSlot = IConsensusContract(addr).getInitialRefSlot();
                  if (initialRefSlot < lastProcessingRefSlot) {
                      revert InitialRefSlotCannotBeLessThanProcessingOne(initialRefSlot, lastProcessingRefSlot);
                  }
                  CONSENSUS_CONTRACT_POSITION.setStorageAddress(addr);
                  emit ConsensusHashContractSet(addr, prevAddr);
              }
              function _checkSenderIsConsensusContract() internal view {
                  if (_msgSender() != CONSENSUS_CONTRACT_POSITION.getStorageAddress()) {
                      revert SenderIsNotTheConsensusContract();
                  }
              }
              function _getTime() internal virtual view returns (uint256) {
                  return block.timestamp; // solhint-disable-line not-rely-on-time
              }
              ///
              /// Storage helpers
              ///
              struct StorageConsensusReport {
                  ConsensusReport value;
              }
              function _storageConsensusReport() internal pure returns (StorageConsensusReport storage r) {
                  bytes32 position = CONSENSUS_REPORT_POSITION;
                  assembly { r.slot := position }
              }
          }
          // SPDX-FileCopyrightText: 2023 Lido <[email protected]>
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity 0.8.9;
          import { SafeCast } from "@openzeppelin/contracts-v4.4/utils/math/SafeCast.sol";
          import { Math } from "../lib/Math.sol";
          import { AccessControlEnumerable } from "../utils/access/AccessControlEnumerable.sol";
          /// @notice A contract that gets consensus reports (i.e. hashes) pushed to and processes them
          /// asynchronously.
          ///
          /// HashConsensus doesn't expect any specific behavior from a report processor, and guarantees
          /// the following:
          ///
          /// 1. HashConsensus won't submit reports via `IReportAsyncProcessor.submitConsensusReport` or ask
          ///    to discard reports via `IReportAsyncProcessor.discardConsensusReport` for any slot up to (and
          ///    including) the slot returned from `IReportAsyncProcessor.getLastProcessingRefSlot`.
          ///
          /// 2. HashConsensus won't accept member reports (and thus won't include such reports in calculating
          ///    the consensus) that have `consensusVersion` argument of the `HashConsensus.submitReport` call
          ///    holding a diff. value than the one returned from `IReportAsyncProcessor.getConsensusVersion()`
          ///    at the moment of the `HashConsensus.submitReport` call.
          ///
          interface IReportAsyncProcessor {
              /// @notice Submits a consensus report for processing.
              ///
              /// Note that submitting the report doesn't require the processor to start processing it right
              /// away, this can happen later (see `getLastProcessingRefSlot`). Until processing is started,
              /// HashConsensus is free to reach consensus on another report for the same reporting frame an
              /// submit it using this same function, or to lose the consensus on the submitted report,
              /// notifying the processor via `discardConsensusReport`.
              ///
              function submitConsensusReport(bytes32 report, uint256 refSlot, uint256 deadline) external;
              /// @notice Notifies that the report for the given ref. slot is not a conensus report anymore
              /// and should be discarded. This can happen when a member changes their report, is removed
              /// from the set, or when the quorum value gets increased.
              ///
              /// Only called when, for the given reference slot:
              ///
              ///   1. there previously was a consensus report; AND
              ///   1. processing of the consensus report hasn't started yet; AND
              ///   2. report processing deadline is not expired yet; AND
              ///   3. there's no consensus report now (otherwise, `submitConsensusReport` is called instead).
              ///
              /// Can be called even when there's no submitted non-discarded consensus report for the current
              /// reference slot, i.e. can be called multiple times in succession.
              ///
              function discardConsensusReport(uint256 refSlot) external;
              /// @notice Returns the last reference slot for which processing of the report was started.
              ///
              /// HashConsensus won't submit reports for any slot less than or equal to this slot.
              ///
              function getLastProcessingRefSlot() external view returns (uint256);
              /// @notice Returns the current consensus version.
              ///
              /// Consensus version must change every time consensus rules change, meaning that
              /// an oracle looking at the same reference slot would calculate a different hash.
              ///
              /// HashConsensus won't accept member reports any consensus version different form the
              /// one returned from this function.
              ///
              function getConsensusVersion() external view returns (uint256);
          }
          /// @notice A contract managing oracle members committee and allowing the members to reach
          /// consensus on a hash for each reporting frame.
          ///
          /// Time is divided in frames of equal length, each having reference slot and processing
          /// deadline. Report data must be gathered by looking at the world state at the moment of
          /// the frame's reference slot (including any state changes made in that slot), and must
          /// be processed before the frame's processing deadline.
          ///
          /// Frame length is defined in Ethereum consensus layer epochs. Reference slot for each
          /// frame is set to the last slot of the epoch preceding the frame's first epoch. The
          /// processing deadline is set to the last slot of the last epoch of the frame.
          ///
          /// This means that all state changes a report processing could entail are guaranteed to be
          /// observed while gathering data for the next frame's report. This is an important property
          /// given that oracle reports sometimes have to contain diffs instead of the full state which
          /// might be impractical or even impossible to transmit and process.
          ///
          contract HashConsensus is AccessControlEnumerable {
              using SafeCast for uint256;
              error InvalidChainConfig();
              error NumericOverflow();
              error AdminCannotBeZero();
              error ReportProcessorCannotBeZero();
              error DuplicateMember();
              error AddressCannotBeZero();
              error InitialEpochIsYetToArrive();
              error InitialEpochAlreadyArrived();
              error InitialEpochRefSlotCannotBeEarlierThanProcessingSlot();
              error EpochsPerFrameCannotBeZero();
              error NonMember();
              error UnexpectedConsensusVersion(uint256 expected, uint256 received);
              error QuorumTooSmall(uint256 minQuorum, uint256 receivedQuorum);
              error InvalidSlot();
              error DuplicateReport();
              error EmptyReport();
              error StaleReport();
              error NonFastLaneMemberCannotReportWithinFastLaneInterval();
              error NewProcessorCannotBeTheSame();
              error ConsensusReportAlreadyProcessing();
              error FastLanePeriodCannotBeLongerThanFrame();
              event FrameConfigSet(uint256 newInitialEpoch, uint256 newEpochsPerFrame);
              event FastLaneConfigSet(uint256 fastLaneLengthSlots);
              event MemberAdded(address indexed addr, uint256 newTotalMembers, uint256 newQuorum);
              event MemberRemoved(address indexed addr, uint256 newTotalMembers, uint256 newQuorum);
              event QuorumSet(uint256 newQuorum, uint256 totalMembers, uint256 prevQuorum);
              event ReportReceived(uint256 indexed refSlot, address indexed member, bytes32 report);
              event ConsensusReached(uint256 indexed refSlot, bytes32 report, uint256 support);
              event ConsensusLost(uint256 indexed refSlot);
              event ReportProcessorSet(address indexed processor, address indexed prevProcessor);
              struct FrameConfig {
                  uint64 initialEpoch;
                  uint64 epochsPerFrame;
                  uint64 fastLaneLengthSlots;
              }
              /// @dev Oracle reporting is divided into frames, each lasting the same number of slots.
              ///
              /// The start slot of the next frame is always the next slot after the end slot of the previous
              /// frame.
              ///
              /// Each frame also has a reference slot: if the oracle report contains any data derived from
              /// onchain data, the onchain data should be sampled at the reference slot.
              ///
              struct ConsensusFrame {
                  // frame index; increments by 1 with each frame but resets to zero on frame size change
                  uint256 index;
                  // the slot at which to read the state around which consensus is being reached;
                  // if the slot contains a block, the state should include all changes from that block
                  uint256 refSlot;
                  // the last slot at which a report can be reported and processed
                  uint256 reportProcessingDeadlineSlot;
              }
              struct ReportingState {
                  // the last reference slot any report was received for
                  uint64 lastReportRefSlot;
                  // the last reference slot a consensus was reached for
                  uint64 lastConsensusRefSlot;
                  // the last consensus variant index
                  uint64 lastConsensusVariantIndex;
              }
              struct MemberState {
                  // the last reference slot a report from this member was received for
                  uint64 lastReportRefSlot;
                  // the variant index of the last report from this member
                  uint64 lastReportVariantIndex;
              }
              struct ReportVariant {
                  // the reported hash
                  bytes32 hash;
                  // how many unique members from the current set reported this hash in the current frame
                  uint64 support;
              }
              /// @notice An ACL role granting the permission to modify members list members and
              /// change the quorum by calling addMember, removeMember, and setQuorum functions.
              bytes32 public constant MANAGE_MEMBERS_AND_QUORUM_ROLE =
                  keccak256("MANAGE_MEMBERS_AND_QUORUM_ROLE");
              /// @notice An ACL role granting the permission to disable the consensus by calling
              /// the disableConsensus function. Enabling the consensus back requires the possession
              /// of the MANAGE_QUORUM_ROLE.
              bytes32 public constant DISABLE_CONSENSUS_ROLE = keccak256("DISABLE_CONSENSUS_ROLE");
              /// @notice An ACL role granting the permission to change reporting interval duration
              /// and fast lane reporting interval length by calling setFrameConfig.
              bytes32 public constant MANAGE_FRAME_CONFIG_ROLE = keccak256("MANAGE_FRAME_CONFIG_ROLE");
              /// @notice An ACL role granting the permission to change fast lane reporting interval
              /// length by calling setFastLaneLengthSlots.
              bytes32 public constant MANAGE_FAST_LANE_CONFIG_ROLE = keccak256("MANAGE_FAST_LANE_CONFIG_ROLE");
              /// @notice An ACL role granting the permission to change еру report processor
              /// contract by calling setReportProcessor.
              bytes32 public constant MANAGE_REPORT_PROCESSOR_ROLE = keccak256("MANAGE_REPORT_PROCESSOR_ROLE");
              /// Chain specification
              uint64 internal immutable SLOTS_PER_EPOCH;
              uint64 internal immutable SECONDS_PER_SLOT;
              uint64 internal immutable GENESIS_TIME;
              /// @dev A quorum value that effectively disables the oracle.
              uint256 internal constant UNREACHABLE_QUORUM = type(uint256).max;
              bytes32 internal constant ZERO_HASH = bytes32(0);
              /// @dev An offset from the processing deadline slot of the previous frame (i.e. the last slot
              /// at which a report for the prev. frame can be submitted and its processing started) to the
              /// reference slot of the next frame (equal to the last slot of the previous frame).
              /// frame[i].reportProcessingDeadlineSlot := frame[i + 1].refSlot - DEADLINE_SLOT_OFFSET
              uint256 internal constant DEADLINE_SLOT_OFFSET = 0;
              /// @dev Reporting frame configuration
              FrameConfig internal _frameConfig;
              /// @dev Oracle committee members states array
              MemberState[] internal _memberStates;
              /// @dev Oracle committee members' addresses array
              address[] internal _memberAddresses;
              /// @dev Mapping from an oracle committee member address to the 1-based index in the
              /// members array
              mapping(address => uint256) internal _memberIndices1b;
              /// @dev A structure containing the last reference slot any report was received for, the last
              /// reference slot consensus report was achieved for, and the last consensus variant index
              ReportingState internal _reportingState;
              /// @dev Oracle committee members quorum value, must be larger than totalMembers // 2
              uint256 internal _quorum;
              /// @dev Mapping from a report variant index to the ReportVariant structure
              mapping(uint256 => ReportVariant) internal _reportVariants;
              /// @dev The number of report variants
              uint256 internal _reportVariantsLength;
              /// @dev The address of the report processor contract
              address internal _reportProcessor;
              ///
              /// Initialization
              ///
              constructor(
                  uint256 slotsPerEpoch,
                  uint256 secondsPerSlot,
                  uint256 genesisTime,
                  uint256 epochsPerFrame,
                  uint256 fastLaneLengthSlots,
                  address admin,
                  address reportProcessor
              ) {
                  if (slotsPerEpoch == 0) revert InvalidChainConfig();
                  if (secondsPerSlot == 0) revert InvalidChainConfig();
                  SLOTS_PER_EPOCH = slotsPerEpoch.toUint64();
                  SECONDS_PER_SLOT = secondsPerSlot.toUint64();
                  GENESIS_TIME = genesisTime.toUint64();
                  if (admin == address(0)) revert AdminCannotBeZero();
                  if (reportProcessor == address(0)) revert ReportProcessorCannotBeZero();
                  _setupRole(DEFAULT_ADMIN_ROLE, admin);
                  uint256 farFutureEpoch = _computeEpochAtTimestamp(type(uint64).max);
                  _setFrameConfig(farFutureEpoch, epochsPerFrame, fastLaneLengthSlots, FrameConfig(0, 0, 0));
                  _reportProcessor = reportProcessor;
              }
              ///
              /// Time
              ///
              /// @notice Returns the immutable chain parameters required to calculate epoch and slot
              /// given a timestamp.
              ///
              function getChainConfig() external view returns (
                  uint256 slotsPerEpoch,
                  uint256 secondsPerSlot,
                  uint256 genesisTime
              ) {
                  return (SLOTS_PER_EPOCH, SECONDS_PER_SLOT, GENESIS_TIME);
              }
              /// @notice Returns the time-related configuration.
              ///
              /// @return initialEpoch Epoch of the frame with zero index.
              /// @return epochsPerFrame Length of a frame in epochs.
              /// @return fastLaneLengthSlots Length of the fast lane interval in slots; see `getIsFastLaneMember`.
              ///
              function getFrameConfig() external view returns (
                  uint256 initialEpoch,
                  uint256 epochsPerFrame,
                  uint256 fastLaneLengthSlots
              ) {
                  FrameConfig memory config = _frameConfig;
                  return (config.initialEpoch, config.epochsPerFrame, config.fastLaneLengthSlots);
              }
              /// @notice Returns the current reporting frame.
              ///
              /// @return refSlot The frame's reference slot: if the data the consensus is being reached upon
              ///         includes or depends on any onchain state, this state should be queried at the
              ///         reference slot. If the slot contains a block, the state should include all changes
              ///         from that block.
              ///
              /// @return reportProcessingDeadlineSlot The last slot at which the report can be processed by
              ///         the report processor contract.
              ///
              function getCurrentFrame() external view returns (
                  uint256 refSlot,
                  uint256 reportProcessingDeadlineSlot
              ) {
                  ConsensusFrame memory frame = _getCurrentFrame();
                  return (frame.refSlot, frame.reportProcessingDeadlineSlot);
              }
              /// @notice Returns the earliest possible reference slot, i.e. the reference slot of the
              /// reporting frame with zero index.
              ///
              function getInitialRefSlot() external view returns (uint256) {
                  return _getInitialFrame().refSlot;
              }
              /// @notice Sets a new initial epoch given that the current initial epoch is in the future.
              ///
              /// @param initialEpoch The new initial epoch.
              ///
              function updateInitialEpoch(uint256 initialEpoch) external onlyRole(DEFAULT_ADMIN_ROLE) {
                  FrameConfig memory prevConfig = _frameConfig;
                  if (_computeEpochAtTimestamp(_getTime()) >= prevConfig.initialEpoch) {
                      revert InitialEpochAlreadyArrived();
                  }
                  _setFrameConfig(
                      initialEpoch,
                      prevConfig.epochsPerFrame,
                      prevConfig.fastLaneLengthSlots,
                      prevConfig
                  );
                  if (_getInitialFrame().refSlot < _getLastProcessingRefSlot()) {
                      revert InitialEpochRefSlotCannotBeEarlierThanProcessingSlot();
                  }
              }
              /// @notice Updates the time-related configuration.
              ///
              /// @param epochsPerFrame Length of a frame in epochs.
              /// @param fastLaneLengthSlots Length of the fast lane interval in slots; see `getIsFastLaneMember`.
              ///
              function setFrameConfig(uint256 epochsPerFrame, uint256 fastLaneLengthSlots)
                  external onlyRole(MANAGE_FRAME_CONFIG_ROLE)
              {
                  // Updates epochsPerFrame in a way that either keeps the current reference slot the same
                  // or increases it by at least the minimum of old and new frame sizes.
                  uint256 timestamp = _getTime();
                  uint256 currentFrameStartEpoch = _computeFrameStartEpoch(timestamp, _frameConfig);
                  _setFrameConfig(currentFrameStartEpoch, epochsPerFrame, fastLaneLengthSlots, _frameConfig);
              }
              ///
              /// Members
              ///
              /// @notice Returns whether the given address is currently a member of the consensus.
              ///
              function getIsMember(address addr) external view returns (bool) {
                  return _isMember(addr);
              }
              /// @notice Returns whether the given address is a fast lane member for the current reporting
              /// frame.
              ///
              /// Fast lane members is a subset of all members that changes each reporting frame. These
              /// members can, and are expected to, submit a report during the first part of the frame called
              /// the "fast lane interval" and defined via `setFrameConfig` or `setFastLaneLengthSlots`. Under
              /// regular circumstances, all other members are only allowed to submit a report after the fast
              /// lane interval passes.
              ///
              /// The fast lane subset consists of `quorum` members; selection is implemented as a sliding
              /// window of the `quorum` width over member indices (mod total members). The window advances
              /// by one index each reporting frame.
              ///
              /// This is done to encourage each member from the full set to participate in reporting on a
              /// regular basis, and identify any malfunctioning members.
              ///
              /// With the fast lane mechanism active, it's sufficient for the monitoring to check that
              /// consensus is consistently reached during the fast lane part of each frame to conclude that
              /// all members are active and share the same consensus rules.
              ///
              /// However, there is no guarantee that, at any given time, it holds true that only the current
              /// fast lane members can or were able to report during the currently-configured fast lane
              /// interval of the current frame. In particular, this assumption can be violated in any frame
              /// during which the members set, initial epoch, or the quorum number was changed, or the fast
              /// lane interval length was increased. Thus, the fast lane mechanism should not be used for any
              /// purpose other than monitoring of the members liveness, and monitoring tools should take into
              /// consideration the potential irregularities within frames with any configuration changes.
              ///
              function getIsFastLaneMember(address addr) external view returns (bool) {
                  uint256 index1b = _memberIndices1b[addr];
                  unchecked {
                      return index1b > 0 && _isFastLaneMember(index1b - 1, _getCurrentFrame().index);
                  }
              }
              /// @notice Returns all current members, together with the last reference slot each member
              /// submitted a report for.
              ///
              function getMembers() external view returns (
                  address[] memory addresses,
                  uint256[] memory lastReportedRefSlots
              ) {
                  return _getMembers(false);
              }
              /// @notice Returns the subset of the oracle committee members (consisting of `quorum` items)
              /// that changes each frame.
              ///
              /// See `getIsFastLaneMember`.
              ///
              function getFastLaneMembers() external view returns (
                  address[] memory addresses,
                  uint256[] memory lastReportedRefSlots
              ) {
                  return _getMembers(true);
              }
              /// @notice Sets the duration of the fast lane interval of the reporting frame.
              ///
              /// See `getIsFastLaneMember`.
              ///
              /// @param fastLaneLengthSlots The length of the fast lane reporting interval in slots. Setting
              ///        it to zero disables the fast lane subset, allowing any oracle to report starting from
              ///        the first slot of a frame and until the frame's reporting deadline.
              ///
              function setFastLaneLengthSlots(uint256 fastLaneLengthSlots)
                  external onlyRole(MANAGE_FAST_LANE_CONFIG_ROLE)
              {
                  _setFastLaneLengthSlots(fastLaneLengthSlots);
              }
              function addMember(address addr, uint256 quorum)
                  external
                  onlyRole(MANAGE_MEMBERS_AND_QUORUM_ROLE)
              {
                  _addMember(addr, quorum);
              }
              function removeMember(address addr, uint256 quorum)
                  external
                  onlyRole(MANAGE_MEMBERS_AND_QUORUM_ROLE)
              {
                  _removeMember(addr, quorum);
              }
              function getQuorum() external view returns (uint256) {
                  return _quorum;
              }
              function setQuorum(uint256 quorum) external {
                  // access control is performed inside the next call
                  _setQuorumAndCheckConsensus(quorum, _memberStates.length);
              }
              /// @notice Disables the oracle by setting the quorum to an unreachable value.
              ///
              function disableConsensus() external {
                  // access control is performed inside the next call
                  _setQuorumAndCheckConsensus(UNREACHABLE_QUORUM, _memberStates.length);
              }
              ///
              /// Report processor
              ///
              function getReportProcessor() external view returns (address) {
                  return _reportProcessor;
              }
              function setReportProcessor(address newProcessor)
                  external
                  onlyRole(MANAGE_REPORT_PROCESSOR_ROLE)
              {
                  _setReportProcessor(newProcessor);
              }
              ///
              /// Consensus
              ///
              /// @notice Returns info about the current frame and consensus state in that frame.
              ///
              /// @return refSlot Reference slot of the current reporting frame.
              ///
              /// @return consensusReport Consensus report for the current frame, if any.
              ///         Zero bytes otherwise.
              ///
              /// @return isReportProcessing If consensus report for the current frame is already
              ///         being processed. Consensus can be changed before the processing starts.
              ///
              function getConsensusState() external view returns (
                  uint256 refSlot,
                  bytes32 consensusReport,
                  bool isReportProcessing
              ) {
                  refSlot = _getCurrentFrame().refSlot;
                  (consensusReport,,) = _getConsensusReport(refSlot, _quorum);
                  isReportProcessing = _getLastProcessingRefSlot() == refSlot;
              }
              /// @notice Returns report variants and their support for the current reference slot.
              ///
              function getReportVariants() external view returns (
                  bytes32[] memory variants,
                  uint256[] memory support
              ) {
                  if (_reportingState.lastReportRefSlot != _getCurrentFrame().refSlot) {
                      return (variants, support);
                  }
                  uint256 variantsLength = _reportVariantsLength;
                  variants = new bytes32[](variantsLength);
                  support = new uint256[](variantsLength);
                  for (uint256 i = 0; i < variantsLength; ++i) {
                      ReportVariant memory variant = _reportVariants[i];
                      variants[i] = variant.hash;
                      support[i] = variant.support;
                  }
              }
              struct MemberConsensusState {
                  /// @notice Current frame's reference slot.
                  uint256 currentFrameRefSlot;
                  /// @notice Consensus report for the current frame, if any. Zero bytes otherwise.
                  bytes32 currentFrameConsensusReport;
                  /// @notice Whether the provided address is a member of the oracle committee.
                  bool isMember;
                  /// @notice Whether the oracle committee member is in the fast lane members subset
                  /// of the current reporting frame. See `getIsFastLaneMember`.
                  bool isFastLane;
                  /// @notice Whether the oracle committee member is allowed to submit a report at
                  /// the moment of the call.
                  bool canReport;
                  /// @notice The last reference slot for which the member submitted a report.
                  uint256 lastMemberReportRefSlot;
                  /// @notice The hash reported by the member for the current frame, if any.
                  /// Zero bytes otherwise.
                  bytes32 currentFrameMemberReport;
              }
              /// @notice Returns the extended information related to an oracle committee member with the
              /// given address and the current consensus state. Provides all the information needed for
              /// an oracle daemon to decide if it needs to submit a report.
              ///
              /// @param addr The member address.
              /// @return result See the docs for `MemberConsensusState`.
              ///
              function getConsensusStateForMember(address addr)
                  external view returns (MemberConsensusState memory result)
              {
                  ConsensusFrame memory frame = _getCurrentFrame();
                  result.currentFrameRefSlot = frame.refSlot;
                  (result.currentFrameConsensusReport,,) = _getConsensusReport(frame.refSlot, _quorum);
                  uint256 index = _memberIndices1b[addr];
                  result.isMember = index != 0;
                  if (index != 0) {
                      unchecked { --index; } // convert to 0-based
                      MemberState memory memberState = _memberStates[index];
                      result.lastMemberReportRefSlot = memberState.lastReportRefSlot;
                      result.currentFrameMemberReport =
                          result.lastMemberReportRefSlot == frame.refSlot
                              ? _reportVariants[memberState.lastReportVariantIndex].hash
                              : ZERO_HASH;
                      uint256 slot = _computeSlotAtTimestamp(_getTime());
                      result.canReport = slot <= frame.reportProcessingDeadlineSlot &&
                          frame.refSlot > _getLastProcessingRefSlot();
                      result.isFastLane = _isFastLaneMember(index, frame.index);
                      if (!result.isFastLane && result.canReport) {
                          result.canReport = slot > frame.refSlot + _frameConfig.fastLaneLengthSlots;
                      }
                  }
              }
              /// @notice Used by oracle members to submit hash of the data calculated for the given
              /// reference slot.
              ///
              /// @param slot The reference slot the data was calculated for. Reverts if doesn't match
              ///        the current reference slot.
              ///
              /// @param report Hash of the data calculated for the given reference slot.
              ///
              /// @param consensusVersion Version of the oracle consensus rules. Reverts if doesn't
              ///        match the version returned by the currently set consensus report processor,
              ///        or zero if no report processor is set.
              ///
              function submitReport(uint256 slot, bytes32 report, uint256 consensusVersion) external {
                  _submitReport(slot, report, consensusVersion);
              }
              ///
              /// Implementation: time
              ///
              function _setFrameConfig(
                  uint256 initialEpoch,
                  uint256 epochsPerFrame,
                  uint256 fastLaneLengthSlots,
                  FrameConfig memory prevConfig
              ) internal {
                  if (epochsPerFrame == 0) revert EpochsPerFrameCannotBeZero();
                  if (fastLaneLengthSlots > epochsPerFrame * SLOTS_PER_EPOCH) {
                      revert FastLanePeriodCannotBeLongerThanFrame();
                  }
                  _frameConfig = FrameConfig(
                      initialEpoch.toUint64(),
                      epochsPerFrame.toUint64(),
                      fastLaneLengthSlots.toUint64()
                  );
                  if (initialEpoch != prevConfig.initialEpoch || epochsPerFrame != prevConfig.epochsPerFrame) {
                      emit FrameConfigSet(initialEpoch, epochsPerFrame);
                  }
                  if (fastLaneLengthSlots != prevConfig.fastLaneLengthSlots) {
                      emit FastLaneConfigSet(fastLaneLengthSlots);
                  }
              }
              function _getCurrentFrame() internal view returns (ConsensusFrame memory) {
                  return _getFrameAtTimestamp(_getTime(), _frameConfig);
              }
              function _getInitialFrame() internal view returns (ConsensusFrame memory) {
                  return _getFrameAtIndex(0, _frameConfig);
              }
              function _getFrameAtTimestamp(uint256 timestamp, FrameConfig memory config)
                  internal view returns (ConsensusFrame memory)
              {
                  return _getFrameAtIndex(_computeFrameIndex(timestamp, config), config);
              }
              function _getFrameAtIndex(uint256 frameIndex, FrameConfig memory config)
                  internal view returns (ConsensusFrame memory)
              {
                  uint256 frameStartEpoch = _computeStartEpochOfFrameWithIndex(frameIndex, config);
                  uint256 frameStartSlot = _computeStartSlotAtEpoch(frameStartEpoch);
                  uint256 nextFrameStartSlot = frameStartSlot + config.epochsPerFrame * SLOTS_PER_EPOCH;
                  return ConsensusFrame({
                      index: frameIndex,
                      refSlot: uint64(frameStartSlot - 1),
                      reportProcessingDeadlineSlot: uint64(nextFrameStartSlot - 1 - DEADLINE_SLOT_OFFSET)
                  });
              }
              function _computeFrameStartEpoch(uint256 timestamp, FrameConfig memory config)
                  internal view returns (uint256)
              {
                  return _computeStartEpochOfFrameWithIndex(_computeFrameIndex(timestamp, config), config);
              }
              function _computeStartEpochOfFrameWithIndex(uint256 frameIndex, FrameConfig memory config)
                  internal pure returns (uint256)
              {
                  return config.initialEpoch + frameIndex * config.epochsPerFrame;
              }
              function _computeFrameIndex(uint256 timestamp, FrameConfig memory config)
                  internal view returns (uint256)
              {
                  uint256 epoch = _computeEpochAtTimestamp(timestamp);
                  if (epoch < config.initialEpoch) {
                      revert InitialEpochIsYetToArrive();
                  }
                  return (epoch - config.initialEpoch) / config.epochsPerFrame;
              }
              function _computeTimestampAtSlot(uint256 slot) internal view returns (uint256) {
                  // See: github.com/ethereum/consensus-specs/blob/dev/specs/bellatrix/beacon-chain.md#compute_timestamp_at_slot
                  return GENESIS_TIME + slot * SECONDS_PER_SLOT;
              }
              function _computeSlotAtTimestamp(uint256 timestamp) internal view returns (uint256) {
                  return (timestamp - GENESIS_TIME) / SECONDS_PER_SLOT;
              }
              function _computeEpochAtSlot(uint256 slot) internal view returns (uint256) {
                  // See: github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#compute_epoch_at_slot
                  return slot / SLOTS_PER_EPOCH;
              }
              function _computeEpochAtTimestamp(uint256 timestamp) internal view returns (uint256) {
                  return _computeEpochAtSlot(_computeSlotAtTimestamp(timestamp));
              }
              function _computeStartSlotAtEpoch(uint256 epoch) internal view returns (uint256) {
                  // See: github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#compute_start_slot_at_epoch
                  return epoch * SLOTS_PER_EPOCH;
              }
              function _getTime() internal virtual view returns (uint256) {
                  return block.timestamp; // solhint-disable-line not-rely-on-time
              }
              ///
              /// Implementation: members
              ///
              function _isMember(address addr) internal view returns (bool) {
                  return _memberIndices1b[addr] != 0;
              }
              function _getMemberIndex(address addr) internal view returns (uint256) {
                  uint256 index1b = _memberIndices1b[addr];
                  if (index1b == 0) {
                      revert NonMember();
                  }
                  unchecked {
                      return uint256(index1b - 1);
                  }
              }
              function _addMember(address addr, uint256 quorum) internal {
                  if (_isMember(addr)) revert DuplicateMember();
                  if (addr == address(0)) revert AddressCannotBeZero();
                  _memberStates.push(MemberState(0, 0));
                  _memberAddresses.push(addr);
                  uint256 newTotalMembers = _memberStates.length;
                  _memberIndices1b[addr] = newTotalMembers;
                  emit MemberAdded(addr, newTotalMembers, quorum);
                  _setQuorumAndCheckConsensus(quorum, newTotalMembers);
              }
              function _removeMember(address addr, uint256 quorum) internal {
                  uint256 index = _getMemberIndex(addr);
                  uint256 newTotalMembers = _memberStates.length - 1;
                  assert(index <= newTotalMembers);
                  MemberState memory memberState = _memberStates[index];
                  if (index != newTotalMembers) {
                      address addrToMove = _memberAddresses[newTotalMembers];
                      _memberAddresses[index] = addrToMove;
                      _memberStates[index] = _memberStates[newTotalMembers];
                      _memberIndices1b[addrToMove] = index + 1;
                  }
                  _memberStates.pop();
                  _memberAddresses.pop();
                  _memberIndices1b[addr] = 0;
                  emit MemberRemoved(addr, newTotalMembers, quorum);
                  if (memberState.lastReportRefSlot > 0) {
                      // member reported at least once
                      ConsensusFrame memory frame = _getCurrentFrame();
                      if (memberState.lastReportRefSlot == frame.refSlot &&
                          _getLastProcessingRefSlot() < frame.refSlot
                      ) {
                          // member reported for the current ref. slot and the consensus report
                          // is not processing yet => need to cancel the member's report
                          --_reportVariants[memberState.lastReportVariantIndex].support;
                      }
                  }
                  _setQuorumAndCheckConsensus(quorum, newTotalMembers);
              }
              function _setFastLaneLengthSlots(uint256 fastLaneLengthSlots) internal {
                  FrameConfig memory frameConfig = _frameConfig;
                  if (fastLaneLengthSlots > frameConfig.epochsPerFrame * SLOTS_PER_EPOCH) {
                      revert FastLanePeriodCannotBeLongerThanFrame();
                  }
                  if (fastLaneLengthSlots != frameConfig.fastLaneLengthSlots) {
                      _frameConfig.fastLaneLengthSlots = fastLaneLengthSlots.toUint64();
                      emit FastLaneConfigSet(fastLaneLengthSlots);
                  }
              }
              /// @dev Returns start and past-end incides (mod totalMembers) of the fast lane members subset.
              ///
              function _getFastLaneSubset(uint256 frameIndex, uint256 totalMembers)
                  internal view returns (uint256 startIndex, uint256 pastEndIndex)
              {
                  uint256 quorum = _quorum;
                  if (quorum >= totalMembers) {
                      startIndex = 0;
                      pastEndIndex = totalMembers;
                  } else {
                      startIndex = frameIndex % totalMembers;
                      pastEndIndex = startIndex + quorum;
                  }
              }
              /// @dev Tests whether the member with the given `index` is in the fast lane subset for the
              /// given reporting `frameIndex`.
              ///
              function _isFastLaneMember(uint256 index, uint256 frameIndex) internal view returns (bool) {
                  uint256 totalMembers = _memberStates.length;
                  (uint256 flLeft, uint256 flPastRight) = _getFastLaneSubset(frameIndex, totalMembers);
                  unchecked {
                      return (
                          flPastRight != 0 &&
                          Math.pointInClosedIntervalModN(index, flLeft, flPastRight - 1, totalMembers)
                      );
                  }
              }
              function _getMembers(bool fastLane) internal view returns (
                  address[] memory addresses,
                  uint256[] memory lastReportedRefSlots
              ) {
                  uint256 totalMembers = _memberStates.length;
                  uint256 left;
                  uint256 right;
                  if (fastLane) {
                      (left, right) = _getFastLaneSubset(_getCurrentFrame().index, totalMembers);
                  } else {
                      right = totalMembers;
                  }
                  addresses = new address[](right - left);
                  lastReportedRefSlots = new uint256[](addresses.length);
                  for (uint256 i = left; i < right; ++i) {
                      uint256 iModTotal = i % totalMembers;
                      MemberState memory memberState = _memberStates[iModTotal];
                      uint256 k = i - left;
                      addresses[k] = _memberAddresses[iModTotal];
                      lastReportedRefSlots[k] = memberState.lastReportRefSlot;
                  }
              }
              ///
              /// Implementation: consensus
              ///
              function _submitReport(uint256 slot, bytes32 report, uint256 consensusVersion) internal {
                  if (slot == 0) revert InvalidSlot();
                  if (slot > type(uint64).max) revert NumericOverflow();
                  if (report == ZERO_HASH) revert EmptyReport();
                  uint256 memberIndex = _getMemberIndex(_msgSender());
                  MemberState memory memberState = _memberStates[memberIndex];
                  uint256 expectedConsensusVersion = _getConsensusVersion();
                  if (consensusVersion != expectedConsensusVersion) {
                      revert UnexpectedConsensusVersion(expectedConsensusVersion, consensusVersion);
                  }
                  uint256 timestamp = _getTime();
                  uint256 currentSlot = _computeSlotAtTimestamp(timestamp);
                  FrameConfig memory config = _frameConfig;
                  ConsensusFrame memory frame = _getFrameAtTimestamp(timestamp, config);
                  if (slot != frame.refSlot) revert InvalidSlot();
                  if (currentSlot > frame.reportProcessingDeadlineSlot) revert StaleReport();
                  if (currentSlot <= frame.refSlot + config.fastLaneLengthSlots &&
                      !_isFastLaneMember(memberIndex, frame.index)
                  ) {
                      revert NonFastLaneMemberCannotReportWithinFastLaneInterval();
                  }
                  if (slot <= _getLastProcessingRefSlot()) {
                      // consensus for the ref. slot was already reached and consensus report is processing
                      if (slot == memberState.lastReportRefSlot) {
                          // member sends a report for the same slot => let them know via a revert
                          revert ConsensusReportAlreadyProcessing();
                      } else {
                          // member hasn't sent a report for this slot => normal operation, do nothing
                          return;
                      }
                  }
                  uint256 variantsLength;
                  if (_reportingState.lastReportRefSlot != slot) {
                      // first report for a new slot => clear report variants
                      _reportingState.lastReportRefSlot = uint64(slot);
                      variantsLength = 0;
                  } else {
                      variantsLength = _reportVariantsLength;
                  }
                  uint64 varIndex = 0;
                  bool prevConsensusLost = false;
                  while (varIndex < variantsLength && _reportVariants[varIndex].hash != report) {
                      ++varIndex;
                  }
                  if (slot == memberState.lastReportRefSlot) {
                      uint64 prevVarIndex = memberState.lastReportVariantIndex;
                      assert(prevVarIndex < variantsLength);
                      if (varIndex == prevVarIndex) {
                          revert DuplicateReport();
                      } else {
                          uint256 support = --_reportVariants[prevVarIndex].support;
                          if (support == _quorum - 1) {
                              prevConsensusLost = true;
                          }
                      }
                  }
                  uint256 support;
                  if (varIndex < variantsLength) {
                      support = ++_reportVariants[varIndex].support;
                  } else {
                      support = 1;
                      _reportVariants[varIndex] = ReportVariant({hash: report, support: 1});
                      _reportVariantsLength = ++variantsLength;
                  }
                  _memberStates[memberIndex] = MemberState({
                      lastReportRefSlot: uint64(slot),
                      lastReportVariantIndex: varIndex
                  });
                  emit ReportReceived(slot, _msgSender(), report);
                  if (support >= _quorum) {
                      _consensusReached(frame, report, varIndex, support);
                  } else if (prevConsensusLost) {
                      _consensusNotReached(frame);
                  }
              }
              function _consensusReached(
                  ConsensusFrame memory frame,
                  bytes32 report,
                  uint256 variantIndex,
                  uint256 support
              ) internal {
                  if (_reportingState.lastConsensusRefSlot != frame.refSlot ||
                      _reportingState.lastConsensusVariantIndex != variantIndex
                  ) {
                      _reportingState.lastConsensusRefSlot = uint64(frame.refSlot);
                      _reportingState.lastConsensusVariantIndex = uint64(variantIndex);
                      emit ConsensusReached(frame.refSlot, report, support);
                      _submitReportForProcessing(frame, report);
                  }
              }
              function _consensusNotReached(ConsensusFrame memory frame) internal {
                  if (_reportingState.lastConsensusRefSlot == frame.refSlot) {
                      _reportingState.lastConsensusRefSlot = 0;
                      emit ConsensusLost(frame.refSlot);
                      _cancelReportProcessing(frame);
                  }
              }
              function _setQuorumAndCheckConsensus(uint256 quorum, uint256 totalMembers) internal {
                  if (quorum <= totalMembers / 2) {
                      revert QuorumTooSmall(totalMembers / 2 + 1, quorum);
                  }
                  // we're explicitly allowing quorum values greater than the number of members to
                  // allow effectively disabling the oracle in case something unpredictable happens
                  uint256 prevQuorum = _quorum;
                  if (quorum != prevQuorum) {
                      _checkRole(
                          quorum == UNREACHABLE_QUORUM ? DISABLE_CONSENSUS_ROLE : MANAGE_MEMBERS_AND_QUORUM_ROLE,
                          _msgSender()
                      );
                      _quorum = quorum;
                      emit QuorumSet(quorum, totalMembers, prevQuorum);
                  }
                  if (_computeEpochAtTimestamp(_getTime()) >= _frameConfig.initialEpoch) {
                      _checkConsensus(quorum);
                  }
              }
              function _checkConsensus(uint256 quorum) internal {
                  uint256 timestamp = _getTime();
                  ConsensusFrame memory frame = _getFrameAtTimestamp(timestamp, _frameConfig);
                  if (_computeSlotAtTimestamp(timestamp) > frame.reportProcessingDeadlineSlot) {
                      // a report for the current ref. slot cannot be processed anymore
                      return;
                  }
                  if (_getLastProcessingRefSlot() >= frame.refSlot) {
                      // a consensus report for the current ref. slot is already being processed
                      return;
                  }
                  (bytes32 consensusReport, int256 consensusVariantIndex, uint256 support) =
                      _getConsensusReport(frame.refSlot, quorum);
                  if (consensusVariantIndex >= 0) {
                      _consensusReached(frame, consensusReport, uint256(consensusVariantIndex), support);
                  } else {
                      _consensusNotReached(frame);
                  }
              }
              function _getConsensusReport(uint256 currentRefSlot, uint256 quorum)
                  internal view returns (bytes32 report, int256 variantIndex, uint256 support)
              {
                  if (_reportingState.lastReportRefSlot != currentRefSlot) {
                      // there were no reports for the current ref. slot
                      return (ZERO_HASH, -1, 0);
                  }
                  uint256 variantsLength = _reportVariantsLength;
                  variantIndex = -1;
                  report = ZERO_HASH;
                  support = 0;
                  for (uint256 i = 0; i < variantsLength; ++i) {
                      uint256 iSupport = _reportVariants[i].support;
                      if (iSupport >= quorum) {
                          variantIndex = int256(i);
                          report = _reportVariants[i].hash;
                          support = iSupport;
                          break;
                      }
                  }
                  return (report, variantIndex, support);
              }
              ///
              /// Implementation: report processing
              ///
              function _setReportProcessor(address newProcessor) internal {
                  address prevProcessor = _reportProcessor;
                  if (newProcessor == address(0)) revert ReportProcessorCannotBeZero();
                  if (newProcessor == prevProcessor) revert NewProcessorCannotBeTheSame();
                  _reportProcessor = newProcessor;
                  emit ReportProcessorSet(newProcessor, prevProcessor);
                  ConsensusFrame memory frame = _getCurrentFrame();
                  uint256 lastConsensusRefSlot = _reportingState.lastConsensusRefSlot;
                  uint256 processingRefSlotPrev = IReportAsyncProcessor(prevProcessor).getLastProcessingRefSlot();
                  uint256 processingRefSlotNext = IReportAsyncProcessor(newProcessor).getLastProcessingRefSlot();
                  if (
                      processingRefSlotPrev < frame.refSlot &&
                      processingRefSlotNext < frame.refSlot &&
                      lastConsensusRefSlot == frame.refSlot
                  ) {
                      bytes32 report = _reportVariants[_reportingState.lastConsensusVariantIndex].hash;
                      _submitReportForProcessing(frame, report);
                  }
              }
              function _getLastProcessingRefSlot() internal view returns (uint256) {
                  return IReportAsyncProcessor(_reportProcessor).getLastProcessingRefSlot();
              }
              function _submitReportForProcessing(ConsensusFrame memory frame, bytes32 report) internal {
                  IReportAsyncProcessor(_reportProcessor).submitConsensusReport(
                      report,
                      frame.refSlot,
                      _computeTimestampAtSlot(frame.reportProcessingDeadlineSlot)
                  );
              }
              function _cancelReportProcessing(ConsensusFrame memory frame) internal {
                  IReportAsyncProcessor(_reportProcessor).discardConsensusReport(frame.refSlot);
              }
              function _getConsensusVersion() internal view returns (uint256) {
                  return IReportAsyncProcessor(_reportProcessor).getConsensusVersion();
              }
          }
          // SPDX-FileCopyrightText: 2023 Lido <[email protected]>
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity 0.8.9;
          import { SafeCast } from "@openzeppelin/contracts-v4.4/utils/math/SafeCast.sol";
          import { ILidoLocator } from "../../common/interfaces/ILidoLocator.sol";
          import { Math256 } from "../../common/lib/Math256.sol";
          import { PausableUntil } from "../utils/PausableUntil.sol";
          import { UnstructuredStorage } from "../lib/UnstructuredStorage.sol";
          import { BaseOracle } from "./BaseOracle.sol";
          interface IOracleReportSanityChecker {
              function checkExitBusOracleReport(uint256 _exitRequestsCount) external view;
          }
          contract ValidatorsExitBusOracle is BaseOracle, PausableUntil {
              using UnstructuredStorage for bytes32;
              using SafeCast for uint256;
              error AdminCannotBeZero();
              error SenderNotAllowed();
              error UnsupportedRequestsDataFormat(uint256 format);
              error InvalidRequestsData();
              error InvalidRequestsDataLength();
              error UnexpectedRequestsDataLength();
              error InvalidRequestsDataSortOrder();
              error ArgumentOutOfBounds();
              error NodeOpValidatorIndexMustIncrease(
                  uint256 moduleId,
                  uint256 nodeOpId,
                  uint256 prevRequestedValidatorIndex,
                  uint256 requestedValidatorIndex
              );
              event ValidatorExitRequest(
                  uint256 indexed stakingModuleId,
                  uint256 indexed nodeOperatorId,
                  uint256 indexed validatorIndex,
                  bytes validatorPubkey,
                  uint256 timestamp
              );
              event WarnDataIncompleteProcessing(
                  uint256 indexed refSlot,
                  uint256 requestsProcessed,
                  uint256 requestsCount
              );
              struct DataProcessingState {
                  uint64 refSlot;
                  uint64 requestsCount;
                  uint64 requestsProcessed;
                  uint16 dataFormat;
              }
              struct RequestedValidator {
                  bool requested;
                  uint64 index;
              }
              /// @notice An ACL role granting the permission to submit the data for a committee report.
              bytes32 public constant SUBMIT_DATA_ROLE = keccak256("SUBMIT_DATA_ROLE");
              /// @notice An ACL role granting the permission to pause accepting validator exit requests
              bytes32 public constant PAUSE_ROLE = keccak256("PAUSE_ROLE");
              /// @notice An ACL role granting the permission to resume accepting validator exit requests
              bytes32 public constant RESUME_ROLE = keccak256("RESUME_ROLE");
              /// @dev Storage slot: uint256 totalRequestsProcessed
              bytes32 internal constant TOTAL_REQUESTS_PROCESSED_POSITION =
                  keccak256("lido.ValidatorsExitBusOracle.totalRequestsProcessed");
              /// @dev Storage slot: mapping(uint256 => RequestedValidator) lastRequestedValidatorIndices
              /// A mapping from the (moduleId, nodeOpId) packed key to the last requested validator index.
              bytes32 internal constant LAST_REQUESTED_VALIDATOR_INDICES_POSITION =
                  keccak256("lido.ValidatorsExitBusOracle.lastRequestedValidatorIndices");
              /// @dev Storage slot: DataProcessingState dataProcessingState
              bytes32 internal constant DATA_PROCESSING_STATE_POSITION =
                  keccak256("lido.ValidatorsExitBusOracle.dataProcessingState");
              ILidoLocator internal immutable LOCATOR;
              ///
              /// Initialization & admin functions
              ///
              constructor(uint256 secondsPerSlot, uint256 genesisTime, address lidoLocator)
                  BaseOracle(secondsPerSlot, genesisTime)
              {
                  LOCATOR = ILidoLocator(lidoLocator);
              }
              function initialize(
                  address admin,
                  address consensusContract,
                  uint256 consensusVersion,
                  uint256 lastProcessingRefSlot
              ) external {
                  if (admin == address(0)) revert AdminCannotBeZero();
                  _setupRole(DEFAULT_ADMIN_ROLE, admin);
                  _pauseFor(PAUSE_INFINITELY);
                  _initialize(consensusContract, consensusVersion, lastProcessingRefSlot);
              }
              /// @notice Resume accepting validator exit requests
              ///
              /// @dev Reverts with `PausedExpected()` if contract is already resumed
              /// @dev Reverts with `AccessControl:...` reason if sender has no `RESUME_ROLE`
              ///
              function resume() external whenPaused onlyRole(RESUME_ROLE) {
                  _resume();
              }
              /// @notice Pause accepting validator exit requests util in after duration
              ///
              /// @param _duration pause duration, seconds (use `PAUSE_INFINITELY` for unlimited)
              /// @dev Reverts with `ResumedExpected()` if contract is already paused
              /// @dev Reverts with `AccessControl:...` reason if sender has no `PAUSE_ROLE`
              /// @dev Reverts with `ZeroPauseDuration()` if zero duration is passed
              ///
              function pauseFor(uint256 _duration) external onlyRole(PAUSE_ROLE) {
                  _pauseFor(_duration);
              }
              /// @notice Pause accepting report data
              /// @param _pauseUntilInclusive the last second to pause until
              /// @dev Reverts with `ResumeSinceInPast()` if the timestamp is in the past
              /// @dev Reverts with `AccessControl:...` reason if sender has no `PAUSE_ROLE`
              /// @dev Reverts with `ResumedExpected()` if contract is already paused
              function pauseUntil(uint256 _pauseUntilInclusive) external onlyRole(PAUSE_ROLE) {
                  _pauseUntil(_pauseUntilInclusive);
              }
              ///
              /// Data provider interface
              ///
              struct ReportData {
                  ///
                  /// Oracle consensus info
                  ///
                  /// @dev Version of the oracle consensus rules. Current version expected
                  /// by the oracle can be obtained by calling getConsensusVersion().
                  uint256 consensusVersion;
                  /// @dev Reference slot for which the report was calculated. If the slot
                  /// contains a block, the state being reported should include all state
                  /// changes resulting from that block. The epoch containing the slot
                  /// should be finalized prior to calculating the report.
                  uint256 refSlot;
                  ///
                  /// Requests data
                  ///
                  /// @dev Total number of validator exit requests in this report. Must not be greater
                  /// than limit checked in OracleReportSanityChecker.checkExitBusOracleReport.
                  uint256 requestsCount;
                  /// @dev Format of the validator exit requests data. Currently, only the
                  /// DATA_FORMAT_LIST=1 is supported.
                  uint256 dataFormat;
                  /// @dev Validator exit requests data. Can differ based on the data format,
                  /// see the constant defining a specific data format below for more info.
                  bytes data;
              }
              /// @notice The list format of the validator exit requests data. Used when all
              /// requests fit into a single transaction.
              ///
              /// Each validator exit request is described by the following 64-byte array:
              ///
              /// MSB <------------------------------------------------------- LSB
              /// |  3 bytes   |  5 bytes   |     8 bytes      |    48 bytes     |
              /// |  moduleId  |  nodeOpId  |  validatorIndex  | validatorPubkey |
              ///
              /// All requests are tightly packed into a byte array where requests follow
              /// one another without any separator or padding, and passed to the `data`
              /// field of the report structure.
              ///
              /// Requests must be sorted in the ascending order by the following compound
              /// key: (moduleId, nodeOpId, validatorIndex).
              ///
              uint256 public constant DATA_FORMAT_LIST = 1;
              /// Length in bytes of packed request
              uint256 internal constant PACKED_REQUEST_LENGTH = 64;
              /// @notice Submits report data for processing.
              ///
              /// @param data The data. See the `ReportData` structure's docs for details.
              /// @param contractVersion Expected version of the oracle contract.
              ///
              /// Reverts if:
              /// - The caller is not a member of the oracle committee and doesn't possess the
              ///   SUBMIT_DATA_ROLE.
              /// - The provided contract version is different from the current one.
              /// - The provided consensus version is different from the expected one.
              /// - The provided reference slot differs from the current consensus frame's one.
              /// - The processing deadline for the current consensus frame is missed.
              /// - The keccak256 hash of the ABI-encoded data is different from the last hash
              ///   provided by the hash consensus contract.
              /// - The provided data doesn't meet safety checks.
              ///
              function submitReportData(ReportData calldata data, uint256 contractVersion)
                  external whenResumed
              {
                  _checkMsgSenderIsAllowedToSubmitData();
                  _checkContractVersion(contractVersion);
                  // it's a waste of gas to copy the whole calldata into mem but seems there's no way around
                  _checkConsensusData(data.refSlot, data.consensusVersion, keccak256(abi.encode(data)));
                  _startProcessing();
                  _handleConsensusReportData(data);
              }
              /// @notice Returns the total number of validator exit requests ever processed
              /// across all received reports.
              ///
              function getTotalRequestsProcessed() external view returns (uint256) {
                  return TOTAL_REQUESTS_PROCESSED_POSITION.getStorageUint256();
              }
              /// @notice Returns the latest validator indices that were requested to exit for the given
              /// `nodeOpIds` in the given `moduleId`. For node operators that were never requested to exit
              /// any validator, index is set to -1.
              ///
              /// @param moduleId ID of the staking module.
              /// @param nodeOpIds IDs of the staking module's node operators.
              ///
              function getLastRequestedValidatorIndices(uint256 moduleId, uint256[] calldata nodeOpIds)
                  external view returns (int256[] memory)
              {
                  if (moduleId > type(uint24).max) revert ArgumentOutOfBounds();
                  int256[] memory indices = new int256[](nodeOpIds.length);
                  for (uint256 i = 0; i < nodeOpIds.length; ++i) {
                      uint256 nodeOpId = nodeOpIds[i];
                      if (nodeOpId > type(uint40).max) revert ArgumentOutOfBounds();
                      uint256 nodeOpKey = _computeNodeOpKey(moduleId, nodeOpId);
                      RequestedValidator memory validator = _storageLastRequestedValidatorIndices()[nodeOpKey];
                      indices[i] = validator.requested ? int256(uint256(validator.index)) : -1;
                  }
                  return indices;
              }
              struct ProcessingState {
                  /// @notice Reference slot for the current reporting frame.
                  uint256 currentFrameRefSlot;
                  /// @notice The last time at which a report data can be submitted for the current
                  /// reporting frame.
                  uint256 processingDeadlineTime;
                  /// @notice Hash of the report data. Zero bytes if consensus on the hash hasn't
                  /// been reached yet for the current reporting frame.
                  bytes32 dataHash;
                  /// @notice Whether any report data for the for the current reporting frame has been
                  /// already submitted.
                  bool dataSubmitted;
                  /// @notice Format of the report data for the current reporting frame.
                  uint256 dataFormat;
                  /// @notice Total number of validator exit requests for the current reporting frame.
                  uint256 requestsCount;
                  /// @notice How many validator exit requests are already submitted for the current
                  /// reporting frame.
                  uint256 requestsSubmitted;
              }
              /// @notice Returns data processing state for the current reporting frame.
              /// @return result See the docs for the `ProcessingState` struct.
              ///
              function getProcessingState() external view returns (ProcessingState memory result) {
                  ConsensusReport memory report = _storageConsensusReport().value;
                  result.currentFrameRefSlot = _getCurrentRefSlot();
                  if (report.hash == bytes32(0) || result.currentFrameRefSlot != report.refSlot) {
                      return result;
                  }
                  result.processingDeadlineTime = report.processingDeadlineTime;
                  result.dataHash = report.hash;
                  DataProcessingState memory procState = _storageDataProcessingState().value;
                  result.dataSubmitted = procState.refSlot == result.currentFrameRefSlot;
                  if (!result.dataSubmitted) {
                      return result;
                  }
                  result.dataFormat = procState.dataFormat;
                  result.requestsCount = procState.requestsCount;
                  result.requestsSubmitted = procState.requestsProcessed;
              }
              ///
              /// Implementation & helpers
              ///
              function _handleConsensusReport(
                  ConsensusReport memory /* report */,
                  uint256 /* prevSubmittedRefSlot */,
                  uint256 prevProcessingRefSlot
              ) internal override {
                  DataProcessingState memory state = _storageDataProcessingState().value;
                  if (state.refSlot == prevProcessingRefSlot && state.requestsProcessed < state.requestsCount) {
                      emit WarnDataIncompleteProcessing(
                          prevProcessingRefSlot,
                          state.requestsProcessed,
                          state.requestsCount
                      );
                  }
              }
              function _checkMsgSenderIsAllowedToSubmitData() internal view {
                  address sender = _msgSender();
                  if (!hasRole(SUBMIT_DATA_ROLE, sender) && !_isConsensusMember(sender)) {
                      revert SenderNotAllowed();
                  }
              }
              function _handleConsensusReportData(ReportData calldata data) internal {
                  if (data.dataFormat != DATA_FORMAT_LIST) {
                      revert UnsupportedRequestsDataFormat(data.dataFormat);
                  }
                  if (data.data.length % PACKED_REQUEST_LENGTH != 0) {
                      revert InvalidRequestsDataLength();
                  }
                  IOracleReportSanityChecker(LOCATOR.oracleReportSanityChecker())
                      .checkExitBusOracleReport(data.requestsCount);
                  if (data.data.length / PACKED_REQUEST_LENGTH != data.requestsCount) {
                      revert UnexpectedRequestsDataLength();
                  }
                  _processExitRequestsList(data.data);
                  _storageDataProcessingState().value = DataProcessingState({
                      refSlot: data.refSlot.toUint64(),
                      requestsCount: data.requestsCount.toUint64(),
                      requestsProcessed: data.requestsCount.toUint64(),
                      dataFormat: uint16(DATA_FORMAT_LIST)
                  });
                  if (data.requestsCount == 0) {
                      return;
                  }
                  TOTAL_REQUESTS_PROCESSED_POSITION.setStorageUint256(
                      TOTAL_REQUESTS_PROCESSED_POSITION.getStorageUint256() + data.requestsCount
                  );
              }
              function _processExitRequestsList(bytes calldata data) internal {
                  uint256 offset;
                  uint256 offsetPastEnd;
                  assembly {
                      offset := data.offset
                      offsetPastEnd := add(offset, data.length)
                  }
                  uint256 lastDataWithoutPubkey = 0;
                  uint256 lastNodeOpKey = 0;
                  RequestedValidator memory lastRequestedVal;
                  bytes calldata pubkey;
                  assembly {
                      pubkey.length := 48
                  }
                  uint256 timestamp = _getTime();
                  while (offset < offsetPastEnd) {
                      uint256 dataWithoutPubkey;
                      assembly {
                          // 16 most significant bytes are taken by module id, node op id, and val index
                          dataWithoutPubkey := shr(128, calldataload(offset))
                          // the next 48 bytes are taken by the pubkey
                          pubkey.offset := add(offset, 16)
                          // totalling to 64 bytes
                          offset := add(offset, 64)
                      }
                      //                              dataWithoutPubkey
                      // MSB <---------------------------------------------------------------------- LSB
                      // | 128 bits: zeros | 24 bits: moduleId | 40 bits: nodeOpId | 64 bits: valIndex |
                      //
                      if (dataWithoutPubkey <= lastDataWithoutPubkey) {
                          revert InvalidRequestsDataSortOrder();
                      }
                      uint64 valIndex = uint64(dataWithoutPubkey);
                      uint256 nodeOpId = uint40(dataWithoutPubkey >> 64);
                      uint256 moduleId = uint24(dataWithoutPubkey >> (64 + 40));
                      if (moduleId == 0) {
                          revert InvalidRequestsData();
                      }
                      uint256 nodeOpKey = _computeNodeOpKey(moduleId, nodeOpId);
                      if (nodeOpKey != lastNodeOpKey) {
                          if (lastNodeOpKey != 0) {
                              _storageLastRequestedValidatorIndices()[lastNodeOpKey] = lastRequestedVal;
                          }
                          lastRequestedVal = _storageLastRequestedValidatorIndices()[nodeOpKey];
                          lastNodeOpKey = nodeOpKey;
                      }
                      if (lastRequestedVal.requested && valIndex <= lastRequestedVal.index) {
                          revert NodeOpValidatorIndexMustIncrease(
                              moduleId,
                              nodeOpId,
                              lastRequestedVal.index,
                              valIndex
                          );
                      }
                      lastRequestedVal = RequestedValidator(true, valIndex);
                      lastDataWithoutPubkey = dataWithoutPubkey;
                      emit ValidatorExitRequest(moduleId, nodeOpId, valIndex, pubkey, timestamp);
                  }
                  if (lastNodeOpKey != 0) {
                      _storageLastRequestedValidatorIndices()[lastNodeOpKey] = lastRequestedVal;
                  }
              }
              function _computeNodeOpKey(uint256 moduleId, uint256 nodeOpId) internal pure returns (uint256) {
                  return (moduleId << 40) | nodeOpId;
              }
              ///
              /// Storage helpers
              ///
              function _storageLastRequestedValidatorIndices() internal pure returns (
                  mapping(uint256 => RequestedValidator) storage r
              ) {
                  bytes32 position = LAST_REQUESTED_VALIDATOR_INDICES_POSITION;
                  assembly { r.slot := position }
              }
              struct StorageDataProcessingState {
                  DataProcessingState value;
              }
              function _storageDataProcessingState() internal pure returns (
                  StorageDataProcessingState storage r
              ) {
                  bytes32 position = DATA_PROCESSING_STATE_POSITION;
                  assembly { r.slot := position }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
          //
          // A modified AccessControl contract using unstructured storage. Copied from tree:
          // https://github.com/OpenZeppelin/openzeppelin-contracts/tree/6bd6b76/contracts/access
          //
          /* See contracts/COMPILERS.md */
          pragma solidity 0.8.9;
          import "@openzeppelin/contracts-v4.4/access/IAccessControl.sol";
          import "@openzeppelin/contracts-v4.4/utils/Context.sol";
          import "@openzeppelin/contracts-v4.4/utils/Strings.sol";
          import "@openzeppelin/contracts-v4.4/utils/introspection/ERC165.sol";
          /**
           * @dev Contract module that allows children to implement role-based access
           * control mechanisms. This is a lightweight version that doesn't allow enumerating role
           * members except through off-chain means by accessing the contract event logs. Some
           * applications may benefit from on-chain enumerability, for those cases see
           * {AccessControlEnumerable}.
           *
           * Roles are referred to by their `bytes32` identifier. These should be exposed
           * in the external API and be unique. The best way to achieve this is by
           * using `public constant` hash digests:
           *
           * ```
           * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
           * ```
           *
           * Roles can be used to represent a set of permissions. To restrict access to a
           * function call, use {hasRole}:
           *
           * ```
           * function foo() public {
           *     require(hasRole(MY_ROLE, msg.sender));
           *     ...
           * }
           * ```
           *
           * Roles can be granted and revoked dynamically via the {grantRole} and
           * {revokeRole} functions. Each role has an associated admin role, and only
           * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
           *
           * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
           * that only accounts with this role will be able to grant or revoke other
           * roles. More complex role relationships can be created by using
           * {_setRoleAdmin}.
           *
           * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
           * grant and revoke this role. Extra precautions should be taken to secure
           * accounts that have been granted it.
           */
          abstract contract AccessControl is Context, IAccessControl, ERC165 {
              struct RoleData {
                  mapping(address => bool) members;
                  bytes32 adminRole;
              }
              /// @dev Storage slot: mapping(bytes32 => RoleData) _roles
              bytes32 private constant ROLES_POSITION = keccak256("openzeppelin.AccessControl._roles");
              function _storageRoles() private pure returns (mapping(bytes32 => RoleData) storage _roles) {
                  bytes32 position = ROLES_POSITION;
                  assembly { _roles.slot := position }
              }
              bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
              /**
               * @dev Modifier that checks that an account has a specific role. Reverts
               * with a standardized message including the required role.
               *
               * The format of the revert reason is given by the following regular expression:
               *
               *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
               *
               * _Available since v4.1._
               */
              modifier onlyRole(bytes32 role) {
                  _checkRole(role, _msgSender());
                  _;
              }
              /**
               * @dev See {IERC165-supportsInterface}.
               */
              function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                  return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
              }
              /**
               * @dev Returns `true` if `account` has been granted `role`.
               */
              function hasRole(bytes32 role, address account) public view override returns (bool) {
                  return _storageRoles()[role].members[account];
              }
              /**
               * @dev Revert with a standard message if `account` is missing `role`.
               *
               * The format of the revert reason is given by the following regular expression:
               *
               *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
               */
              function _checkRole(bytes32 role, address account) internal view {
                  if (!hasRole(role, account)) {
                      revert(
                          string(
                              abi.encodePacked(
                                  "AccessControl: account ",
                                  Strings.toHexString(uint160(account), 20),
                                  " is missing role ",
                                  Strings.toHexString(uint256(role), 32)
                              )
                          )
                      );
                  }
              }
              /**
               * @dev Returns the admin role that controls `role`. See {grantRole} and
               * {revokeRole}.
               *
               * To change a role's admin, use {_setRoleAdmin}.
               */
              function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
                  return _storageRoles()[role].adminRole;
              }
              /**
               * @dev Grants `role` to `account`.
               *
               * If `account` had not been already granted `role`, emits a {RoleGranted}
               * event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               */
              function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
                  _grantRole(role, account);
              }
              /**
               * @dev Revokes `role` from `account`.
               *
               * If `account` had been granted `role`, emits a {RoleRevoked} event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               */
              function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
                  _revokeRole(role, account);
              }
              /**
               * @dev Revokes `role` from the calling account.
               *
               * Roles are often managed via {grantRole} and {revokeRole}: this function's
               * purpose is to provide a mechanism for accounts to lose their privileges
               * if they are compromised (such as when a trusted device is misplaced).
               *
               * If the calling account had been revoked `role`, emits a {RoleRevoked}
               * event.
               *
               * Requirements:
               *
               * - the caller must be `account`.
               */
              function renounceRole(bytes32 role, address account) public virtual override {
                  require(account == _msgSender(), "AccessControl: can only renounce roles for self");
                  _revokeRole(role, account);
              }
              /**
               * @dev Grants `role` to `account`.
               *
               * If `account` had not been already granted `role`, emits a {RoleGranted}
               * event. Note that unlike {grantRole}, this function doesn't perform any
               * checks on the calling account.
               *
               * [WARNING]
               * ====
               * This function should only be called from the constructor when setting
               * up the initial roles for the system.
               *
               * Using this function in any other way is effectively circumventing the admin
               * system imposed by {AccessControl}.
               * ====
               *
               * NOTE: This function is deprecated in favor of {_grantRole}.
               */
              function _setupRole(bytes32 role, address account) internal virtual {
                  _grantRole(role, account);
              }
              /**
               * @dev Sets `adminRole` as ``role``'s admin role.
               *
               * Emits a {RoleAdminChanged} event.
               */
              function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
                  bytes32 previousAdminRole = getRoleAdmin(role);
                  _storageRoles()[role].adminRole = adminRole;
                  emit RoleAdminChanged(role, previousAdminRole, adminRole);
              }
              /**
               * @dev Grants `role` to `account`.
               *
               * Internal function without access restriction.
               */
              function _grantRole(bytes32 role, address account) internal virtual {
                  if (!hasRole(role, account)) {
                      _storageRoles()[role].members[account] = true;
                      emit RoleGranted(role, account, _msgSender());
                  }
              }
              /**
               * @dev Revokes `role` from `account`.
               *
               * Internal function without access restriction.
               */
              function _revokeRole(bytes32 role, address account) internal virtual {
                  if (hasRole(role, account)) {
                      _storageRoles()[role].members[account] = false;
                      emit RoleRevoked(role, account, _msgSender());
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (access/AccessControlEnumerable.sol)
          //
          // A modified AccessControlEnumerable contract using unstructured storage. Copied from tree:
          // https://github.com/OpenZeppelin/openzeppelin-contracts/tree/6bd6b76/contracts/access
          //
          /* See contracts/COMPILERS.md */
          pragma solidity 0.8.9;
          import "@openzeppelin/contracts-v4.4/access/IAccessControlEnumerable.sol";
          import "@openzeppelin/contracts-v4.4/utils/structs/EnumerableSet.sol";
          import "./AccessControl.sol";
          /**
           * @dev Extension of {AccessControl} that allows enumerating the members of each role.
           */
          abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
              using EnumerableSet for EnumerableSet.AddressSet;
              /// @dev Storage slot: mapping(bytes32 => EnumerableSet.AddressSet) _roleMembers
              bytes32 private constant ROLE_MEMBERS_POSITION = keccak256("openzeppelin.AccessControlEnumerable._roleMembers");
              function _storageRoleMembers() private pure returns (
                  mapping(bytes32 => EnumerableSet.AddressSet) storage _roleMembers
              ) {
                  bytes32 position = ROLE_MEMBERS_POSITION;
                  assembly { _roleMembers.slot := position }
              }
              /**
               * @dev See {IERC165-supportsInterface}.
               */
              function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                  return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
              }
              /**
               * @dev Returns one of the accounts that have `role`. `index` must be a
               * value between 0 and {getRoleMemberCount}, non-inclusive.
               *
               * Role bearers are not sorted in any particular way, and their ordering may
               * change at any point.
               *
               * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
               * you perform all queries on the same block. See the following
               * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
               * for more information.
               */
              function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
                  return _storageRoleMembers()[role].at(index);
              }
              /**
               * @dev Returns the number of accounts that have `role`. Can be used
               * together with {getRoleMember} to enumerate all bearers of a role.
               */
              function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
                  return _storageRoleMembers()[role].length();
              }
              /**
               * @dev Overload {_grantRole} to track enumerable memberships
               */
              function _grantRole(bytes32 role, address account) internal virtual override {
                  super._grantRole(role, account);
                  _storageRoleMembers()[role].add(account);
              }
              /**
               * @dev Overload {_revokeRole} to track enumerable memberships
               */
              function _revokeRole(bytes32 role, address account) internal virtual override {
                  super._revokeRole(role, account);
                  _storageRoleMembers()[role].remove(account);
              }
          }
          // SPDX-FileCopyrightText: 2023 Lido <[email protected]>
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity 0.8.9;
          import "../lib/UnstructuredStorage.sol";
          contract PausableUntil {
              using UnstructuredStorage for bytes32;
              /// Contract resume/pause control storage slot
              bytes32 internal constant RESUME_SINCE_TIMESTAMP_POSITION = keccak256("lido.PausableUntil.resumeSinceTimestamp");
              /// Special value for the infinite pause
              uint256 public constant PAUSE_INFINITELY = type(uint256).max;
              /// @notice Emitted when paused by the `pauseFor` or `pauseUntil` call
              event Paused(uint256 duration);
              /// @notice Emitted when resumed by the `resume` call
              event Resumed();
              error ZeroPauseDuration();
              error PausedExpected();
              error ResumedExpected();
              error PauseUntilMustBeInFuture();
              /// @notice Reverts when resumed
              modifier whenPaused() {
                  _checkPaused();
                  _;
              }
              /// @notice Reverts when paused
              modifier whenResumed() {
                  _checkResumed();
                  _;
              }
              function _checkPaused() internal view {
                  if (!isPaused()) {
                      revert PausedExpected();
                  }
              }
              function _checkResumed() internal view {
                  if (isPaused()) {
                      revert ResumedExpected();
                  }
              }
              /// @notice Returns whether the contract is paused
              function isPaused() public view returns (bool) {
                  return block.timestamp < RESUME_SINCE_TIMESTAMP_POSITION.getStorageUint256();
              }
              /// @notice Returns one of:
              ///  - PAUSE_INFINITELY if paused infinitely returns
              ///  - first second when get contract get resumed if paused for specific duration
              ///  - some timestamp in past if not paused
              function getResumeSinceTimestamp() external view returns (uint256) {
                  return RESUME_SINCE_TIMESTAMP_POSITION.getStorageUint256();
              }
              function _resume() internal {
                  _checkPaused();
                  RESUME_SINCE_TIMESTAMP_POSITION.setStorageUint256(block.timestamp);
                  emit Resumed();
              }
              function _pauseFor(uint256 _duration) internal {
                  _checkResumed();
                  if (_duration == 0) revert ZeroPauseDuration();
                  uint256 resumeSince;
                  if (_duration == PAUSE_INFINITELY) {
                      resumeSince = PAUSE_INFINITELY;
                  } else {
                      resumeSince = block.timestamp + _duration;
                  }
                  _setPausedState(resumeSince);
              }
              function _pauseUntil(uint256 _pauseUntilInclusive) internal {
                  _checkResumed();
                  if (_pauseUntilInclusive < block.timestamp) revert PauseUntilMustBeInFuture();
                  uint256 resumeSince;
                  if (_pauseUntilInclusive != PAUSE_INFINITELY) {
                      resumeSince = _pauseUntilInclusive + 1;
                  } else {
                      resumeSince = PAUSE_INFINITELY;
                  }
                  _setPausedState(resumeSince);
              }
              function _setPausedState(uint256 _resumeSince) internal {
                  RESUME_SINCE_TIMESTAMP_POSITION.setStorageUint256(_resumeSince);
                  if (_resumeSince == PAUSE_INFINITELY) {
                      emit Paused(PAUSE_INFINITELY);
                  } else {
                      emit Paused(_resumeSince - block.timestamp);
                  }
              }
          }
          // SPDX-FileCopyrightText: 2022 Lido <[email protected]>
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity 0.8.9;
          import "../lib/UnstructuredStorage.sol";
          contract Versioned {
              using UnstructuredStorage for bytes32;
              event ContractVersionSet(uint256 version);
              error NonZeroContractVersionOnInit();
              error InvalidContractVersionIncrement();
              error UnexpectedContractVersion(uint256 expected, uint256 received);
              /// @dev Storage slot: uint256 version
              /// Version of the initialized contract storage.
              /// The version stored in CONTRACT_VERSION_POSITION equals to:
              /// - 0 right after the deployment, before an initializer is invoked (and only at that moment);
              /// - N after calling initialize(), where N is the initially deployed contract version;
              /// - N after upgrading contract by calling finalizeUpgrade_vN().
              bytes32 internal constant CONTRACT_VERSION_POSITION = keccak256("lido.Versioned.contractVersion");
              uint256 internal constant PETRIFIED_VERSION_MARK = type(uint256).max;
              constructor() {
                  // lock version in the implementation's storage to prevent initialization
                  CONTRACT_VERSION_POSITION.setStorageUint256(PETRIFIED_VERSION_MARK);
              }
              /// @notice Returns the current contract version.
              function getContractVersion() public view returns (uint256) {
                  return CONTRACT_VERSION_POSITION.getStorageUint256();
              }
              function _checkContractVersion(uint256 version) internal view {
                  uint256 expectedVersion = getContractVersion();
                  if (version != expectedVersion) {
                      revert UnexpectedContractVersion(expectedVersion, version);
                  }
              }
              /// @dev Sets the contract version to N. Should be called from the initialize() function.
              function _initializeContractVersionTo(uint256 version) internal {
                  if (getContractVersion() != 0) revert NonZeroContractVersionOnInit();
                  _setContractVersion(version);
              }
              /// @dev Updates the contract version. Should be called from a finalizeUpgrade_vN() function.
              function _updateContractVersion(uint256 newVersion) internal {
                  if (newVersion != getContractVersion() + 1) revert InvalidContractVersionIncrement();
                  _setContractVersion(newVersion);
              }
              function _setContractVersion(uint256 version) private {
                  CONTRACT_VERSION_POSITION.setStorageUint256(version);
                  emit ContractVersionSet(version);
              }
          }
          // SPDX-FileCopyrightText: 2023 Lido <[email protected]>
          // SPDX-License-Identifier: GPL-3.0
          // See contracts/COMPILERS.md
          // solhint-disable-next-line
          pragma solidity >=0.4.24 <0.9.0;
          interface ILidoLocator {
              function accountingOracle() external view returns(address);
              function depositSecurityModule() external view returns(address);
              function elRewardsVault() external view returns(address);
              function legacyOracle() external view returns(address);
              function lido() external view returns(address);
              function oracleReportSanityChecker() external view returns(address);
              function burner() external view returns(address);
              function stakingRouter() external view returns(address);
              function treasury() external view returns(address);
              function validatorsExitBusOracle() external view returns(address);
              function withdrawalQueue() external view returns(address);
              function withdrawalVault() external view returns(address);
              function postTokenRebaseReceiver() external view returns(address);
              function oracleDaemonConfig() external view returns(address);
              function coreComponents() external view returns(
                  address elRewardsVault,
                  address oracleReportSanityChecker,
                  address stakingRouter,
                  address treasury,
                  address withdrawalQueue,
                  address withdrawalVault
              );
              function oracleReportComponentsForLido() external view returns(
                  address accountingOracle,
                  address elRewardsVault,
                  address oracleReportSanityChecker,
                  address burner,
                  address withdrawalQueue,
                  address withdrawalVault,
                  address postTokenRebaseReceiver
              );
          }
          // SPDX-FileCopyrightText: 2023 Lido <[email protected]>
          // SPDX-License-Identifier: MIT
          // Copied from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/0457042d93d9dfd760dbaa06a4d2f1216fdbe297/contracts/utils/math/Math.sol
          // See contracts/COMPILERS.md
          // solhint-disable-next-line
          pragma solidity >=0.4.24 <0.9.0;
          library Math256 {
              /// @dev Returns the largest of two numbers.
              function max(uint256 a, uint256 b) internal pure returns (uint256) {
                  return a > b ? a : b;
              }
              /// @dev Returns the smallest of two numbers.
              function min(uint256 a, uint256 b) internal pure returns (uint256) {
                  return a < b ? a : b;
              }
              /// @dev Returns the largest of two numbers.
              function max(int256 a, int256 b) internal pure returns (int256) {
                  return a > b ? a : b;
              }
              /// @dev Returns the smallest of two numbers.
              function min(int256 a, int256 b) internal pure returns (int256) {
                  return a < b ? a : b;
              }
              /// @dev Returns the ceiling of the division of two numbers.
              ///
              /// This differs from standard division with `/` in that it rounds up instead
              /// of rounding down.
              function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
                  // (a + b - 1) / b can overflow on addition, so we distribute.
                  return a == 0 ? 0 : (a - 1) / b + 1;
              }
              /// @dev Returns absolute difference of two numbers.
              function absDiff(uint256 a, uint256 b) internal pure returns (uint256) {
                  return a > b ? a - b : b - a;
              }
          }