// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/extensions/AccessControlEnumerable.sol)
pragma solidity ^0.8.20;
import {IAccessControlEnumerable} from "@openzeppelin/contracts/access/extensions/IAccessControlEnumerable.sol";
import {AccessControlUpgradeable} from "../AccessControlUpgradeable.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerable, AccessControlUpgradeable {
using EnumerableSet for EnumerableSet.AddressSet;
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControlEnumerable
struct AccessControlEnumerableStorage {
mapping(bytes32 role => EnumerableSet.AddressSet) _roleMembers;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControlEnumerable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlEnumerableStorageLocation = 0xc1f6fe24621ce81ec5827caf0253cadb74709b061630e6b55e82371705932000;
function _getAccessControlEnumerableStorage() private pure returns (AccessControlEnumerableStorage storage $) {
assembly {
$.slot := AccessControlEnumerableStorageLocation
}
}
function __AccessControlEnumerable_init() internal onlyInitializing {
}
function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
}
/**
* @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 virtual returns (address) {
AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
return $._roleMembers[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 virtual returns (uint256) {
AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
return $._roleMembers[role].length();
}
/**
* @dev Overload {AccessControl-_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override returns (bool) {
AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
bool granted = super._grantRole(role, account);
if (granted) {
$._roleMembers[role].add(account);
}
return granted;
}
/**
* @dev Overload {AccessControl-_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override returns (bool) {
AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
bool revoked = super._revokeRole(role, account);
if (revoked) {
$._roleMembers[role].remove(account);
}
return revoked;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* 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}:
*
* ```solidity
* 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. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
struct AccessControlStorage {
mapping(bytes32 role => RoleData) _roles;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;
function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
assembly {
$.slot := AccessControlStorageLocation
}
}
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
/**
* @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 virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual 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.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual 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 `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
AccessControlStorage storage $ = _getAccessControlStorage();
bytes32 previousAdminRole = getRoleAdmin(role);
$._roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (!hasRole(role, account)) {
$._roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (hasRole(role, account)) {
$._roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165Upgradeable is Initializable, IERC165 {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
/**
* @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.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @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._positions[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 cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 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 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[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._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
}
// SPDX-FileCopyrightText: 2024 Lido <info@lido.fi>
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { AccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/extensions/AccessControlEnumerableUpgradeable.sol";
import { IReportAsyncProcessor } from "./interfaces/IReportAsyncProcessor.sol";
import { IConsensusContract } from "./interfaces/IConsensusContract.sol";
/// @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.
///
// solhint-disable ordering
contract HashConsensus is
IConsensusContract,
AccessControlEnumerableUpgradeable
{
using SafeCast for uint256;
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 the report processor
/// contract by calling setReportProcessor.
bytes32 public constant MANAGE_REPORT_PROCESSOR_ROLE =
keccak256("MANAGE_REPORT_PROCESSOR_ROLE");
/// @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;
/// Chain specification
uint64 internal immutable SLOTS_PER_EPOCH;
uint64 internal immutable SECONDS_PER_SLOT;
uint64 internal immutable GENESIS_TIME;
/// @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;
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
);
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();
///
/// 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();
_grantRole(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 view virtual 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 indices (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 &&
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();
}
}
function pointInClosedIntervalModN(
uint256 x,
uint256 a,
uint256 b,
uint256 n
) pure returns (bool) {
return (x + n - a) % n <= (b - a) % n;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @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.
*/
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 `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/extensions/IAccessControlEnumerable.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "../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-FileCopyrightText: 2024 Lido <info@lido.fi>
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;
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 getInitialRefSlot() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @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-FileCopyrightText: 2024 Lido <info@lido.fi>
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;
/// @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 consensus 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
/// 2. processing of the consensus report hasn't started yet; AND
/// 3. report processing deadline is not expired yet; AND
/// 4. 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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @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.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @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) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(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) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(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) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(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) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(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) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(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) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
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) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
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) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, 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
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, 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
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, 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
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, 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
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, 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
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, 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
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
}
{
"compilationTarget": {
"src/lib/base-oracle/HashConsensus.sol": "HashConsensus"
},
"evmVersion": "cancun",
"libraries": {
"src/lib/AssetRecovererLib.sol:AssetRecovererLib": "0xa74528edc289b1a597faf83fcff7eff871cc01d9",
"src/lib/NOAddresses.sol:NOAddresses": "0xf8e5de8baf8ad7c93dcb61d13d00eb3d57131c72",
"src/lib/QueueLib.sol:QueueLib": "0xd19b40cb5401f1413d014a56529f03b3452f70f9"
},
"metadata": {
"bytecodeHash": "none"
},
"optimizer": {
"enabled": true,
"runs": 250
},
"remappings": [
":@openzeppelin/contracts-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable/",
":@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
":ds-test/=node_modules/ds-test/src/",
":forge-std/=node_modules/forge-std/src/"
]
}
[{"inputs":[{"internalType":"uint256","name":"slotsPerEpoch","type":"uint256"},{"internalType":"uint256","name":"secondsPerSlot","type":"uint256"},{"internalType":"uint256","name":"genesisTime","type":"uint256"},{"internalType":"uint256","name":"epochsPerFrame","type":"uint256"},{"internalType":"uint256","name":"fastLaneLengthSlots","type":"uint256"},{"internalType":"address","name":"admin","type":"address"},{"internalType":"address","name":"reportProcessor","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AccessControlBadConfirmation","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bytes32","name":"neededRole","type":"bytes32"}],"name":"AccessControlUnauthorizedAccount","type":"error"},{"inputs":[],"name":"AddressCannotBeZero","type":"error"},{"inputs":[],"name":"AdminCannotBeZero","type":"error"},{"inputs":[],"name":"ConsensusReportAlreadyProcessing","type":"error"},{"inputs":[],"name":"DuplicateMember","type":"error"},{"inputs":[],"name":"DuplicateReport","type":"error"},{"inputs":[],"name":"EmptyReport","type":"error"},{"inputs":[],"name":"EpochsPerFrameCannotBeZero","type":"error"},{"inputs":[],"name":"FastLanePeriodCannotBeLongerThanFrame","type":"error"},{"inputs":[],"name":"InitialEpochAlreadyArrived","type":"error"},{"inputs":[],"name":"InitialEpochIsYetToArrive","type":"error"},{"inputs":[],"name":"InitialEpochRefSlotCannotBeEarlierThanProcessingSlot","type":"error"},{"inputs":[],"name":"InvalidChainConfig","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"InvalidSlot","type":"error"},{"inputs":[],"name":"NewProcessorCannotBeTheSame","type":"error"},{"inputs":[],"name":"NonFastLaneMemberCannotReportWithinFastLaneInterval","type":"error"},{"inputs":[],"name":"NonMember","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[],"name":"NumericOverflow","type":"error"},{"inputs":[{"internalType":"uint256","name":"minQuorum","type":"uint256"},{"internalType":"uint256","name":"receivedQuorum","type":"uint256"}],"name":"QuorumTooSmall","type":"error"},{"inputs":[],"name":"ReportProcessorCannotBeZero","type":"error"},{"inputs":[{"internalType":"uint8","name":"bits","type":"uint8"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"SafeCastOverflowedUintDowncast","type":"error"},{"inputs":[],"name":"StaleReport","type":"error"},{"inputs":[{"internalType":"uint256","name":"expected","type":"uint256"},{"internalType":"uint256","name":"received","type":"uint256"}],"name":"UnexpectedConsensusVersion","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"refSlot","type":"uint256"}],"name":"ConsensusLost","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"refSlot","type":"uint256"},{"indexed":false,"internalType":"bytes32","name":"report","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"support","type":"uint256"}],"name":"ConsensusReached","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"fastLaneLengthSlots","type":"uint256"}],"name":"FastLaneConfigSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newInitialEpoch","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newEpochsPerFrame","type":"uint256"}],"name":"FrameConfigSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"addr","type":"address"},{"indexed":false,"internalType":"uint256","name":"newTotalMembers","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newQuorum","type":"uint256"}],"name":"MemberAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"addr","type":"address"},{"indexed":false,"internalType":"uint256","name":"newTotalMembers","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newQuorum","type":"uint256"}],"name":"MemberRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newQuorum","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalMembers","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"prevQuorum","type":"uint256"}],"name":"QuorumSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"processor","type":"address"},{"indexed":true,"internalType":"address","name":"prevProcessor","type":"address"}],"name":"ReportProcessorSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"refSlot","type":"uint256"},{"indexed":true,"internalType":"address","name":"member","type":"address"},{"indexed":false,"internalType":"bytes32","name":"report","type":"bytes32"}],"name":"ReportReceived","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DISABLE_CONSENSUS_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MANAGE_FAST_LANE_CONFIG_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MANAGE_FRAME_CONFIG_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MANAGE_MEMBERS_AND_QUORUM_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MANAGE_REPORT_PROCESSOR_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"addr","type":"address"},{"internalType":"uint256","name":"quorum","type":"uint256"}],"name":"addMember","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"disableConsensus","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getChainConfig","outputs":[{"internalType":"uint256","name":"slotsPerEpoch","type":"uint256"},{"internalType":"uint256","name":"secondsPerSlot","type":"uint256"},{"internalType":"uint256","name":"genesisTime","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getConsensusState","outputs":[{"internalType":"uint256","name":"refSlot","type":"uint256"},{"internalType":"bytes32","name":"consensusReport","type":"bytes32"},{"internalType":"bool","name":"isReportProcessing","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"addr","type":"address"}],"name":"getConsensusStateForMember","outputs":[{"components":[{"internalType":"uint256","name":"currentFrameRefSlot","type":"uint256"},{"internalType":"bytes32","name":"currentFrameConsensusReport","type":"bytes32"},{"internalType":"bool","name":"isMember","type":"bool"},{"internalType":"bool","name":"isFastLane","type":"bool"},{"internalType":"bool","name":"canReport","type":"bool"},{"internalType":"uint256","name":"lastMemberReportRefSlot","type":"uint256"},{"internalType":"bytes32","name":"currentFrameMemberReport","type":"bytes32"}],"internalType":"struct HashConsensus.MemberConsensusState","name":"result","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCurrentFrame","outputs":[{"internalType":"uint256","name":"refSlot","type":"uint256"},{"internalType":"uint256","name":"reportProcessingDeadlineSlot","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getFastLaneMembers","outputs":[{"internalType":"address[]","name":"addresses","type":"address[]"},{"internalType":"uint256[]","name":"lastReportedRefSlots","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getFrameConfig","outputs":[{"internalType":"uint256","name":"initialEpoch","type":"uint256"},{"internalType":"uint256","name":"epochsPerFrame","type":"uint256"},{"internalType":"uint256","name":"fastLaneLengthSlots","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getInitialRefSlot","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"addr","type":"address"}],"name":"getIsFastLaneMember","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"addr","type":"address"}],"name":"getIsMember","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"addresses","type":"address[]"},{"internalType":"uint256[]","name":"lastReportedRefSlots","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getQuorum","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getReportProcessor","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getReportVariants","outputs":[{"internalType":"bytes32[]","name":"variants","type":"bytes32[]"},{"internalType":"uint256[]","name":"support","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getRoleMember","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleMemberCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"addr","type":"address"},{"internalType":"uint256","name":"quorum","type":"uint256"}],"name":"removeMember","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"callerConfirmation","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"fastLaneLengthSlots","type":"uint256"}],"name":"setFastLaneLengthSlots","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"epochsPerFrame","type":"uint256"},{"internalType":"uint256","name":"fastLaneLengthSlots","type":"uint256"}],"name":"setFrameConfig","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"quorum","type":"uint256"}],"name":"setQuorum","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newProcessor","type":"address"}],"name":"setReportProcessor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"slot","type":"uint256"},{"internalType":"bytes32","name":"report","type":"bytes32"},{"internalType":"uint256","name":"consensusVersion","type":"uint256"}],"name":"submitReport","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"initialEpoch","type":"uint256"}],"name":"updateInitialEpoch","outputs":[],"stateMutability":"nonpayable","type":"function"}]