ETH Price: $2,117.80 (+2.48%)

Transaction Decoder

Block:
22567899 at May-26-2025 03:37:23 PM +UTC
Transaction Fee:
0.000326207452736904 ETH $0.69
Gas Used:
110,388 Gas / 2.955098858 Gwei

Execution Trace

TransparentUpgradeableProxy.c14c9204( )
  • MergedAdapterWithoutRoundsPufStakingV1.updateDataFeedsValues( dataPackagesTimestamp=1748273830000 )
    • Null: 0x000...001.2c5b6110( )
    • Null: 0x000...001.2c5b6110( )
    • Null: 0x000...001.5915520c( )
    • Null: 0x000...001.5915520c( )
    • ValidatorTicketPricer.setDailyRewardsAndPostMintPrice( dailyMevPayouts=228060000000000, dailyConsensusRewards=2548440000000000 )
      • AccessManager.canCall( caller=0xf9dfBF71F2d9C8A4e565e1346aEb2C3e1dC765De, target=0x9830aD1bD5Cf73640e253EdF97DeE3791C4a53C3, selector=System.Byte[] ) => ( immediate=True, delay=0 )
        updateDataFeedsValues[RedstoneAdapterBase (ln:2317)]
        File 1 of 4: TransparentUpgradeableProxy
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
        pragma solidity ^0.8.0;
        import "../utils/Context.sol";
        /**
         * @dev Contract module which provides a basic access control mechanism, where
         * there is an account (an owner) that can be granted exclusive access to
         * specific functions.
         *
         * By default, the owner account will be the one that deploys the contract. This
         * can later be changed with {transferOwnership}.
         *
         * This module is used through inheritance. It will make available the modifier
         * `onlyOwner`, which can be applied to your functions to restrict their use to
         * the owner.
         */
        abstract contract Ownable is Context {
            address private _owner;
            event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
            /**
             * @dev Initializes the contract setting the deployer as the initial owner.
             */
            constructor() {
                _transferOwnership(_msgSender());
            }
            /**
             * @dev Throws if called by any account other than the owner.
             */
            modifier onlyOwner() {
                _checkOwner();
                _;
            }
            /**
             * @dev Returns the address of the current owner.
             */
            function owner() public view virtual returns (address) {
                return _owner;
            }
            /**
             * @dev Throws if the sender is not the owner.
             */
            function _checkOwner() internal view virtual {
                require(owner() == _msgSender(), "Ownable: caller is not the owner");
            }
            /**
             * @dev Leaves the contract without owner. It will not be possible to call
             * `onlyOwner` functions anymore. Can only be called by the current owner.
             *
             * NOTE: Renouncing ownership will leave the contract without an owner,
             * thereby removing any functionality that is only available to the owner.
             */
            function renounceOwnership() public virtual onlyOwner {
                _transferOwnership(address(0));
            }
            /**
             * @dev Transfers ownership of the contract to a new account (`newOwner`).
             * Can only be called by the current owner.
             */
            function transferOwnership(address newOwner) public virtual onlyOwner {
                require(newOwner != address(0), "Ownable: new owner is the zero address");
                _transferOwnership(newOwner);
            }
            /**
             * @dev Transfers ownership of the contract to a new account (`newOwner`).
             * Internal function without access restriction.
             */
            function _transferOwnership(address newOwner) internal virtual {
                address oldOwner = _owner;
                _owner = newOwner;
                emit OwnershipTransferred(oldOwner, newOwner);
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
         * proxy whose upgrades are fully controlled by the current implementation.
         */
        interface IERC1822Proxiable {
            /**
             * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
             * address.
             *
             * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
             * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
             * function revert if invoked through a proxy.
             */
            function proxiableUUID() external view returns (bytes32);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.8.3) (interfaces/IERC1967.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
         *
         * _Available since v4.9._
         */
        interface IERC1967 {
            /**
             * @dev Emitted when the implementation is upgraded.
             */
            event Upgraded(address indexed implementation);
            /**
             * @dev Emitted when the admin account has changed.
             */
            event AdminChanged(address previousAdmin, address newAdmin);
            /**
             * @dev Emitted when the beacon is changed.
             */
            event BeaconUpgraded(address indexed beacon);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.7.0) (proxy/beacon/BeaconProxy.sol)
        pragma solidity ^0.8.0;
        import "./IBeacon.sol";
        import "../Proxy.sol";
        import "../ERC1967/ERC1967Upgrade.sol";
        /**
         * @dev This contract implements a proxy that gets the implementation address for each call from an {UpgradeableBeacon}.
         *
         * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't
         * conflict with the storage layout of the implementation behind the proxy.
         *
         * _Available since v3.4._
         */
        contract BeaconProxy is Proxy, ERC1967Upgrade {
            /**
             * @dev Initializes the proxy with `beacon`.
             *
             * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This
             * will typically be an encoded function call, and allows initializing the storage of the proxy like a Solidity
             * constructor.
             *
             * Requirements:
             *
             * - `beacon` must be a contract with the interface {IBeacon}.
             */
            constructor(address beacon, bytes memory data) payable {
                _upgradeBeaconToAndCall(beacon, data, false);
            }
            /**
             * @dev Returns the current beacon address.
             */
            function _beacon() internal view virtual returns (address) {
                return _getBeacon();
            }
            /**
             * @dev Returns the current implementation address of the associated beacon.
             */
            function _implementation() internal view virtual override returns (address) {
                return IBeacon(_getBeacon()).implementation();
            }
            /**
             * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}.
             *
             * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon.
             *
             * Requirements:
             *
             * - `beacon` must be a contract.
             * - The implementation returned by `beacon` must be a contract.
             */
            function _setBeacon(address beacon, bytes memory data) internal virtual {
                _upgradeBeaconToAndCall(beacon, data, false);
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev This is the interface that {BeaconProxy} expects of its beacon.
         */
        interface IBeacon {
            /**
             * @dev Must return an address that can be used as a delegate call target.
             *
             * {BeaconProxy} will check that this address is a contract.
             */
            function implementation() external view returns (address);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (proxy/beacon/UpgradeableBeacon.sol)
        pragma solidity ^0.8.0;
        import "./IBeacon.sol";
        import "../../access/Ownable.sol";
        import "../../utils/Address.sol";
        /**
         * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their
         * implementation contract, which is where they will delegate all function calls.
         *
         * An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon.
         */
        contract UpgradeableBeacon is IBeacon, Ownable {
            address private _implementation;
            /**
             * @dev Emitted when the implementation returned by the beacon is changed.
             */
            event Upgraded(address indexed implementation);
            /**
             * @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the
             * beacon.
             */
            constructor(address implementation_) {
                _setImplementation(implementation_);
            }
            /**
             * @dev Returns the current implementation address.
             */
            function implementation() public view virtual override returns (address) {
                return _implementation;
            }
            /**
             * @dev Upgrades the beacon to a new implementation.
             *
             * Emits an {Upgraded} event.
             *
             * Requirements:
             *
             * - msg.sender must be the owner of the contract.
             * - `newImplementation` must be a contract.
             */
            function upgradeTo(address newImplementation) public virtual onlyOwner {
                _setImplementation(newImplementation);
                emit Upgraded(newImplementation);
            }
            /**
             * @dev Sets the implementation contract address for this beacon
             *
             * Requirements:
             *
             * - `newImplementation` must be a contract.
             */
            function _setImplementation(address newImplementation) private {
                require(Address.isContract(newImplementation), "UpgradeableBeacon: implementation is not a contract");
                _implementation = newImplementation;
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol)
        pragma solidity ^0.8.0;
        import "../Proxy.sol";
        import "./ERC1967Upgrade.sol";
        /**
         * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
         * implementation address that can be changed. This address is stored in storage in the location specified by
         * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
         * implementation behind the proxy.
         */
        contract ERC1967Proxy is Proxy, ERC1967Upgrade {
            /**
             * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
             *
             * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
             * function call, and allows initializing the storage of the proxy like a Solidity constructor.
             */
            constructor(address _logic, bytes memory _data) payable {
                _upgradeToAndCall(_logic, _data, false);
            }
            /**
             * @dev Returns the current implementation address.
             */
            function _implementation() internal view virtual override returns (address impl) {
                return ERC1967Upgrade._getImplementation();
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.8.3) (proxy/ERC1967/ERC1967Upgrade.sol)
        pragma solidity ^0.8.2;
        import "../beacon/IBeacon.sol";
        import "../../interfaces/IERC1967.sol";
        import "../../interfaces/draft-IERC1822.sol";
        import "../../utils/Address.sol";
        import "../../utils/StorageSlot.sol";
        /**
         * @dev This abstract contract provides getters and event emitting update functions for
         * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
         *
         * _Available since v4.1._
         *
         * @custom:oz-upgrades-unsafe-allow delegatecall
         */
        abstract contract ERC1967Upgrade is IERC1967 {
            // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
            bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
            /**
             * @dev Storage slot with the address of the current implementation.
             * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
             * validated in the constructor.
             */
            bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
            /**
             * @dev Returns the current implementation address.
             */
            function _getImplementation() internal view returns (address) {
                return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
            }
            /**
             * @dev Stores a new address in the EIP1967 implementation slot.
             */
            function _setImplementation(address newImplementation) private {
                require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
                StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
            }
            /**
             * @dev Perform implementation upgrade
             *
             * Emits an {Upgraded} event.
             */
            function _upgradeTo(address newImplementation) internal {
                _setImplementation(newImplementation);
                emit Upgraded(newImplementation);
            }
            /**
             * @dev Perform implementation upgrade with additional setup call.
             *
             * Emits an {Upgraded} event.
             */
            function _upgradeToAndCall(
                address newImplementation,
                bytes memory data,
                bool forceCall
            ) internal {
                _upgradeTo(newImplementation);
                if (data.length > 0 || forceCall) {
                    Address.functionDelegateCall(newImplementation, data);
                }
            }
            /**
             * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
             *
             * Emits an {Upgraded} event.
             */
            function _upgradeToAndCallUUPS(
                address newImplementation,
                bytes memory data,
                bool forceCall
            ) internal {
                // Upgrades from old implementations will perform a rollback test. This test requires the new
                // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
                // this special case will break upgrade paths from old UUPS implementation to new ones.
                if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
                    _setImplementation(newImplementation);
                } else {
                    try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
                        require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
                    } catch {
                        revert("ERC1967Upgrade: new implementation is not UUPS");
                    }
                    _upgradeToAndCall(newImplementation, data, forceCall);
                }
            }
            /**
             * @dev Storage slot with the admin of the contract.
             * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
             * validated in the constructor.
             */
            bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
            /**
             * @dev Returns the current admin.
             */
            function _getAdmin() internal view returns (address) {
                return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
            }
            /**
             * @dev Stores a new address in the EIP1967 admin slot.
             */
            function _setAdmin(address newAdmin) private {
                require(newAdmin != address(0), "ERC1967: new admin is the zero address");
                StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
            }
            /**
             * @dev Changes the admin of the proxy.
             *
             * Emits an {AdminChanged} event.
             */
            function _changeAdmin(address newAdmin) internal {
                emit AdminChanged(_getAdmin(), newAdmin);
                _setAdmin(newAdmin);
            }
            /**
             * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
             * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
             */
            bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
            /**
             * @dev Returns the current beacon.
             */
            function _getBeacon() internal view returns (address) {
                return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
            }
            /**
             * @dev Stores a new beacon in the EIP1967 beacon slot.
             */
            function _setBeacon(address newBeacon) private {
                require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
                require(
                    Address.isContract(IBeacon(newBeacon).implementation()),
                    "ERC1967: beacon implementation is not a contract"
                );
                StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
            }
            /**
             * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
             * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
             *
             * Emits a {BeaconUpgraded} event.
             */
            function _upgradeBeaconToAndCall(
                address newBeacon,
                bytes memory data,
                bool forceCall
            ) internal {
                _setBeacon(newBeacon);
                emit BeaconUpgraded(newBeacon);
                if (data.length > 0 || forceCall) {
                    Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
         * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
         * be specified by overriding the virtual {_implementation} function.
         *
         * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
         * different contract through the {_delegate} function.
         *
         * The success and return data of the delegated call will be returned back to the caller of the proxy.
         */
        abstract contract Proxy {
            /**
             * @dev Delegates the current call to `implementation`.
             *
             * This function does not return to its internal call site, it will return directly to the external caller.
             */
            function _delegate(address implementation) internal virtual {
                assembly {
                    // Copy msg.data. We take full control of memory in this inline assembly
                    // block because it will not return to Solidity code. We overwrite the
                    // Solidity scratch pad at memory position 0.
                    calldatacopy(0, 0, calldatasize())
                    // Call the implementation.
                    // out and outsize are 0 because we don't know the size yet.
                    let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
                    // Copy the returned data.
                    returndatacopy(0, 0, returndatasize())
                    switch result
                    // delegatecall returns 0 on error.
                    case 0 {
                        revert(0, returndatasize())
                    }
                    default {
                        return(0, returndatasize())
                    }
                }
            }
            /**
             * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function
             * and {_fallback} should delegate.
             */
            function _implementation() internal view virtual returns (address);
            /**
             * @dev Delegates the current call to the address returned by `_implementation()`.
             *
             * This function does not return to its internal call site, it will return directly to the external caller.
             */
            function _fallback() internal virtual {
                _beforeFallback();
                _delegate(_implementation());
            }
            /**
             * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
             * function in the contract matches the call data.
             */
            fallback() external payable virtual {
                _fallback();
            }
            /**
             * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
             * is empty.
             */
            receive() external payable virtual {
                _fallback();
            }
            /**
             * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
             * call, or as part of the Solidity `fallback` or `receive` functions.
             *
             * If overridden should call `super._beforeFallback()`.
             */
            function _beforeFallback() internal virtual {}
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.8.3) (proxy/transparent/ProxyAdmin.sol)
        pragma solidity ^0.8.0;
        import "./TransparentUpgradeableProxy.sol";
        import "../../access/Ownable.sol";
        /**
         * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an
         * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
         */
        contract ProxyAdmin is Ownable {
            /**
             * @dev Returns the current implementation of `proxy`.
             *
             * Requirements:
             *
             * - This contract must be the admin of `proxy`.
             */
            function getProxyImplementation(ITransparentUpgradeableProxy proxy) public view virtual returns (address) {
                // We need to manually run the static call since the getter cannot be flagged as view
                // bytes4(keccak256("implementation()")) == 0x5c60da1b
                (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
                require(success);
                return abi.decode(returndata, (address));
            }
            /**
             * @dev Returns the current admin of `proxy`.
             *
             * Requirements:
             *
             * - This contract must be the admin of `proxy`.
             */
            function getProxyAdmin(ITransparentUpgradeableProxy proxy) public view virtual returns (address) {
                // We need to manually run the static call since the getter cannot be flagged as view
                // bytes4(keccak256("admin()")) == 0xf851a440
                (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
                require(success);
                return abi.decode(returndata, (address));
            }
            /**
             * @dev Changes the admin of `proxy` to `newAdmin`.
             *
             * Requirements:
             *
             * - This contract must be the current admin of `proxy`.
             */
            function changeProxyAdmin(ITransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner {
                proxy.changeAdmin(newAdmin);
            }
            /**
             * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
             *
             * Requirements:
             *
             * - This contract must be the admin of `proxy`.
             */
            function upgrade(ITransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner {
                proxy.upgradeTo(implementation);
            }
            /**
             * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See
             * {TransparentUpgradeableProxy-upgradeToAndCall}.
             *
             * Requirements:
             *
             * - This contract must be the admin of `proxy`.
             */
            function upgradeAndCall(
                ITransparentUpgradeableProxy proxy,
                address implementation,
                bytes memory data
            ) public payable virtual onlyOwner {
                proxy.upgradeToAndCall{value: msg.value}(implementation, data);
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.8.3) (proxy/transparent/TransparentUpgradeableProxy.sol)
        pragma solidity ^0.8.0;
        import "../ERC1967/ERC1967Proxy.sol";
        /**
         * @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy}
         * does not implement this interface directly, and some of its functions are implemented by an internal dispatch
         * mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not
         * include them in the ABI so this interface must be used to interact with it.
         */
        interface ITransparentUpgradeableProxy is IERC1967 {
            function admin() external view returns (address);
            function implementation() external view returns (address);
            function changeAdmin(address) external;
            function upgradeTo(address) external;
            function upgradeToAndCall(address, bytes memory) external payable;
        }
        /**
         * @dev This contract implements a proxy that is upgradeable by an admin.
         *
         * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
         * clashing], which can potentially be used in an attack, this contract uses the
         * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
         * things that go hand in hand:
         *
         * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
         * that call matches one of the admin functions exposed by the proxy itself.
         * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
         * implementation. If the admin tries to call a function on the implementation it will fail with an error that says
         * "admin cannot fallback to proxy target".
         *
         * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
         * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
         * to sudden errors when trying to call a function from the proxy implementation.
         *
         * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
         * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
         *
         * NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not
         * inherit from that interface, and instead the admin functions are implicitly implemented using a custom dispatch
         * mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to
         * fully implement transparency without decoding reverts caused by selector clashes between the proxy and the
         * implementation.
         *
         * WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the compiler
         * will not check that there are no selector conflicts, due to the note above. A selector clash between any new function
         * and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This could
         * render the admin operations inaccessible, which could prevent upgradeability. Transparency may also be compromised.
         */
        contract TransparentUpgradeableProxy is ERC1967Proxy {
            /**
             * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
             * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.
             */
            constructor(
                address _logic,
                address admin_,
                bytes memory _data
            ) payable ERC1967Proxy(_logic, _data) {
                _changeAdmin(admin_);
            }
            /**
             * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
             *
             * CAUTION: This modifier is deprecated, as it could cause issues if the modified function has arguments, and the
             * implementation provides a function with the same selector.
             */
            modifier ifAdmin() {
                if (msg.sender == _getAdmin()) {
                    _;
                } else {
                    _fallback();
                }
            }
            /**
             * @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior
             */
            function _fallback() internal virtual override {
                if (msg.sender == _getAdmin()) {
                    bytes memory ret;
                    bytes4 selector = msg.sig;
                    if (selector == ITransparentUpgradeableProxy.upgradeTo.selector) {
                        ret = _dispatchUpgradeTo();
                    } else if (selector == ITransparentUpgradeableProxy.upgradeToAndCall.selector) {
                        ret = _dispatchUpgradeToAndCall();
                    } else if (selector == ITransparentUpgradeableProxy.changeAdmin.selector) {
                        ret = _dispatchChangeAdmin();
                    } else if (selector == ITransparentUpgradeableProxy.admin.selector) {
                        ret = _dispatchAdmin();
                    } else if (selector == ITransparentUpgradeableProxy.implementation.selector) {
                        ret = _dispatchImplementation();
                    } else {
                        revert("TransparentUpgradeableProxy: admin cannot fallback to proxy target");
                    }
                    assembly {
                        return(add(ret, 0x20), mload(ret))
                    }
                } else {
                    super._fallback();
                }
            }
            /**
             * @dev Returns the current admin.
             *
             * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
             * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
             * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
             */
            function _dispatchAdmin() private returns (bytes memory) {
                _requireZeroValue();
                address admin = _getAdmin();
                return abi.encode(admin);
            }
            /**
             * @dev Returns the current implementation.
             *
             * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
             * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
             * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
             */
            function _dispatchImplementation() private returns (bytes memory) {
                _requireZeroValue();
                address implementation = _implementation();
                return abi.encode(implementation);
            }
            /**
             * @dev Changes the admin of the proxy.
             *
             * Emits an {AdminChanged} event.
             */
            function _dispatchChangeAdmin() private returns (bytes memory) {
                _requireZeroValue();
                address newAdmin = abi.decode(msg.data[4:], (address));
                _changeAdmin(newAdmin);
                return "";
            }
            /**
             * @dev Upgrade the implementation of the proxy.
             */
            function _dispatchUpgradeTo() private returns (bytes memory) {
                _requireZeroValue();
                address newImplementation = abi.decode(msg.data[4:], (address));
                _upgradeToAndCall(newImplementation, bytes(""), false);
                return "";
            }
            /**
             * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
             * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
             * proxied contract.
             */
            function _dispatchUpgradeToAndCall() private returns (bytes memory) {
                (address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));
                _upgradeToAndCall(newImplementation, data, true);
                return "";
            }
            /**
             * @dev Returns the current admin.
             */
            function _admin() internal view virtual returns (address) {
                return _getAdmin();
            }
            /**
             * @dev To keep this contract fully transparent, all `ifAdmin` functions must be payable. This helper is here to
             * emulate some proxy functions being non-payable while still allowing value to pass through.
             */
            function _requireZeroValue() private {
                require(msg.value == 0);
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
        pragma solidity ^0.8.1;
        /**
         * @dev Collection of functions related to the address type
         */
        library Address {
            /**
             * @dev Returns true if `account` is a contract.
             *
             * [IMPORTANT]
             * ====
             * It is unsafe to assume that an address for which this function returns
             * false is an externally-owned account (EOA) and not a contract.
             *
             * Among others, `isContract` will return false for the following
             * types of addresses:
             *
             *  - an externally-owned account
             *  - a contract in construction
             *  - an address where a contract will be created
             *  - an address where a contract lived, but was destroyed
             * ====
             *
             * [IMPORTANT]
             * ====
             * You shouldn't rely on `isContract` to protect against flash loan attacks!
             *
             * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
             * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
             * constructor.
             * ====
             */
            function isContract(address account) internal view returns (bool) {
                // This method relies on extcodesize/address.code.length, which returns 0
                // for contracts in construction, since the code is only stored at the end
                // of the constructor execution.
                return account.code.length > 0;
            }
            /**
             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
             * `recipient`, forwarding all available gas and reverting on errors.
             *
             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
             * of certain opcodes, possibly making contracts go over the 2300 gas limit
             * imposed by `transfer`, making them unable to receive funds via
             * `transfer`. {sendValue} removes this limitation.
             *
             * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
             *
             * IMPORTANT: because control is transferred to `recipient`, care must be
             * taken to not create reentrancy vulnerabilities. Consider using
             * {ReentrancyGuard} or the
             * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
             */
            function sendValue(address payable recipient, uint256 amount) internal {
                require(address(this).balance >= amount, "Address: insufficient balance");
                (bool success, ) = recipient.call{value: amount}("");
                require(success, "Address: unable to send value, recipient may have reverted");
            }
            /**
             * @dev Performs a Solidity function call using a low level `call`. A
             * plain `call` is an unsafe replacement for a function call: use this
             * function instead.
             *
             * If `target` reverts with a revert reason, it is bubbled up by this
             * function (like regular Solidity function calls).
             *
             * Returns the raw returned data. To convert to the expected return value,
             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
             *
             * Requirements:
             *
             * - `target` must be a contract.
             * - calling `target` with `data` must not revert.
             *
             * _Available since v3.1._
             */
            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                return functionCallWithValue(target, data, 0, "Address: low-level call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
             * `errorMessage` as a fallback revert reason when `target` reverts.
             *
             * _Available since v3.1._
             */
            function functionCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal returns (bytes memory) {
                return functionCallWithValue(target, data, 0, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but also transferring `value` wei to `target`.
             *
             * Requirements:
             *
             * - the calling contract must have an ETH balance of at least `value`.
             * - the called Solidity function must be `payable`.
             *
             * _Available since v3.1._
             */
            function functionCallWithValue(
                address target,
                bytes memory data,
                uint256 value
            ) internal returns (bytes memory) {
                return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
            }
            /**
             * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
             * with `errorMessage` as a fallback revert reason when `target` reverts.
             *
             * _Available since v3.1._
             */
            function functionCallWithValue(
                address target,
                bytes memory data,
                uint256 value,
                string memory errorMessage
            ) internal returns (bytes memory) {
                require(address(this).balance >= value, "Address: insufficient balance for call");
                (bool success, bytes memory returndata) = target.call{value: value}(data);
                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but performing a static call.
             *
             * _Available since v3.3._
             */
            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                return functionStaticCall(target, data, "Address: low-level static call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
             * but performing a static call.
             *
             * _Available since v3.3._
             */
            function functionStaticCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal view returns (bytes memory) {
                (bool success, bytes memory returndata) = target.staticcall(data);
                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but performing a delegate call.
             *
             * _Available since v3.4._
             */
            function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                return functionDelegateCall(target, data, "Address: low-level delegate call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
             * but performing a delegate call.
             *
             * _Available since v3.4._
             */
            function functionDelegateCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal returns (bytes memory) {
                (bool success, bytes memory returndata) = target.delegatecall(data);
                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
            }
            /**
             * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
             * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
             *
             * _Available since v4.8._
             */
            function verifyCallResultFromTarget(
                address target,
                bool success,
                bytes memory returndata,
                string memory errorMessage
            ) internal view returns (bytes memory) {
                if (success) {
                    if (returndata.length == 0) {
                        // only check isContract if the call was successful and the return data is empty
                        // otherwise we already know that it was a contract
                        require(isContract(target), "Address: call to non-contract");
                    }
                    return returndata;
                } else {
                    _revert(returndata, errorMessage);
                }
            }
            /**
             * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
             * revert reason or using the provided one.
             *
             * _Available since v4.3._
             */
            function verifyCallResult(
                bool success,
                bytes memory returndata,
                string memory errorMessage
            ) internal pure returns (bytes memory) {
                if (success) {
                    return returndata;
                } else {
                    _revert(returndata, errorMessage);
                }
            }
            function _revert(bytes memory returndata, string memory errorMessage) private pure {
                // Look for revert reason and bubble it up if present
                if (returndata.length > 0) {
                    // The easiest way to bubble the revert reason is using memory via assembly
                    /// @solidity memory-safe-assembly
                    assembly {
                        let returndata_size := mload(returndata)
                        revert(add(32, returndata), returndata_size)
                    }
                } else {
                    revert(errorMessage);
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev Provides information about the current execution context, including the
         * sender of the transaction and its data. While these are generally available
         * via msg.sender and msg.data, they should not be accessed in such a direct
         * manner, since when dealing with meta-transactions the account sending and
         * paying for execution may not be the actual sender (as far as an application
         * is concerned).
         *
         * This contract is only required for intermediate, library-like contracts.
         */
        abstract contract Context {
            function _msgSender() internal view virtual returns (address) {
                return msg.sender;
            }
            function _msgData() internal view virtual returns (bytes calldata) {
                return msg.data;
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev Library for reading and writing primitive types to specific storage slots.
         *
         * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
         * This library helps with reading and writing to such slots without the need for inline assembly.
         *
         * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
         *
         * Example usage to set ERC1967 implementation slot:
         * ```
         * contract ERC1967 {
         *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
         *
         *     function _getImplementation() internal view returns (address) {
         *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
         *     }
         *
         *     function _setImplementation(address newImplementation) internal {
         *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
         *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
         *     }
         * }
         * ```
         *
         * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
         */
        library StorageSlot {
            struct AddressSlot {
                address value;
            }
            struct BooleanSlot {
                bool value;
            }
            struct Bytes32Slot {
                bytes32 value;
            }
            struct Uint256Slot {
                uint256 value;
            }
            /**
             * @dev Returns an `AddressSlot` with member `value` located at `slot`.
             */
            function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
                /// @solidity memory-safe-assembly
                assembly {
                    r.slot := slot
                }
            }
            /**
             * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
             */
            function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
                /// @solidity memory-safe-assembly
                assembly {
                    r.slot := slot
                }
            }
            /**
             * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
             */
            function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
                /// @solidity memory-safe-assembly
                assembly {
                    r.slot := slot
                }
            }
            /**
             * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
             */
            function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
                /// @solidity memory-safe-assembly
                assembly {
                    r.slot := slot
                }
            }
        }
        

        File 2 of 4: MergedAdapterWithoutRoundsPufStakingV1
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
        pragma solidity ^0.8.2;
        import "../../utils/AddressUpgradeable.sol";
        /**
         * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
         * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
         * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
         * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
         *
         * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
         * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
         * case an upgrade adds a module that needs to be initialized.
         *
         * For example:
         *
         * [.hljs-theme-light.nopadding]
         * ```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 Indicates that the contract has been initialized.
             * @custom:oz-retyped-from bool
             */
            uint8 private _initialized;
            /**
             * @dev Indicates that the contract is in the process of being initialized.
             */
            bool private _initializing;
            /**
             * @dev Triggered when the contract has been initialized or reinitialized.
             */
            event Initialized(uint8 version);
            /**
             * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
             * `onlyInitializing` functions can be used to initialize parent contracts.
             *
             * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
             * constructor.
             *
             * Emits an {Initialized} event.
             */
            modifier initializer() {
                bool isTopLevelCall = !_initializing;
                require(
                    (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
                    "Initializable: contract is already initialized"
                );
                _initialized = 1;
                if (isTopLevelCall) {
                    _initializing = true;
                }
                _;
                if (isTopLevelCall) {
                    _initializing = false;
                    emit Initialized(1);
                }
            }
            /**
             * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
             * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
             * used to initialize parent contracts.
             *
             * A reinitializer may be used after the original initialization step. This is essential to configure modules that
             * are added through upgrades and that require initialization.
             *
             * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
             * cannot be nested. If one is invoked in the context of another, execution will revert.
             *
             * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
             * a contract, executing them in the right order is up to the developer or operator.
             *
             * WARNING: setting the version to 255 will prevent any future reinitialization.
             *
             * Emits an {Initialized} event.
             */
            modifier reinitializer(uint8 version) {
                require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
                _initialized = version;
                _initializing = true;
                _;
                _initializing = false;
                emit Initialized(version);
            }
            /**
             * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
             * {initializer} and {reinitializer} modifiers, directly or indirectly.
             */
            modifier onlyInitializing() {
                require(_initializing, "Initializable: contract is not initializing");
                _;
            }
            /**
             * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
             * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
             * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
             * through proxies.
             *
             * Emits an {Initialized} event the first time it is successfully executed.
             */
            function _disableInitializers() internal virtual {
                require(!_initializing, "Initializable: contract is initializing");
                if (_initialized != type(uint8).max) {
                    _initialized = type(uint8).max;
                    emit Initialized(type(uint8).max);
                }
            }
            /**
             * @dev Returns the highest version that has been initialized. See {reinitializer}.
             */
            function _getInitializedVersion() internal view returns (uint8) {
                return _initialized;
            }
            /**
             * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
             */
            function _isInitializing() internal view returns (bool) {
                return _initializing;
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
        pragma solidity ^0.8.1;
        /**
         * @dev Collection of functions related to the address type
         */
        library AddressUpgradeable {
            /**
             * @dev Returns true if `account` is a contract.
             *
             * [IMPORTANT]
             * ====
             * It is unsafe to assume that an address for which this function returns
             * false is an externally-owned account (EOA) and not a contract.
             *
             * Among others, `isContract` will return false for the following
             * types of addresses:
             *
             *  - an externally-owned account
             *  - a contract in construction
             *  - an address where a contract will be created
             *  - an address where a contract lived, but was destroyed
             *
             * Furthermore, `isContract` will also return true if the target contract within
             * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
             * which only has an effect at the end of a transaction.
             * ====
             *
             * [IMPORTANT]
             * ====
             * You shouldn't rely on `isContract` to protect against flash loan attacks!
             *
             * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
             * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
             * constructor.
             * ====
             */
            function isContract(address account) internal view returns (bool) {
                // This method relies on extcodesize/address.code.length, which returns 0
                // for contracts in construction, since the code is only stored at the end
                // of the constructor execution.
                return account.code.length > 0;
            }
            /**
             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
             * `recipient`, forwarding all available gas and reverting on errors.
             *
             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
             * of certain opcodes, possibly making contracts go over the 2300 gas limit
             * imposed by `transfer`, making them unable to receive funds via
             * `transfer`. {sendValue} removes this limitation.
             *
             * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
             *
             * IMPORTANT: because control is transferred to `recipient`, care must be
             * taken to not create reentrancy vulnerabilities. Consider using
             * {ReentrancyGuard} or the
             * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
             */
            function sendValue(address payable recipient, uint256 amount) internal {
                require(address(this).balance >= amount, "Address: insufficient balance");
                (bool success, ) = recipient.call{value: amount}("");
                require(success, "Address: unable to send value, recipient may have reverted");
            }
            /**
             * @dev Performs a Solidity function call using a low level `call`. A
             * plain `call` is an unsafe replacement for a function call: use this
             * function instead.
             *
             * If `target` reverts with a revert reason, it is bubbled up by this
             * function (like regular Solidity function calls).
             *
             * Returns the raw returned data. To convert to the expected return value,
             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
             *
             * Requirements:
             *
             * - `target` must be a contract.
             * - calling `target` with `data` must not revert.
             *
             * _Available since v3.1._
             */
            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                return functionCallWithValue(target, data, 0, "Address: low-level call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
             * `errorMessage` as a fallback revert reason when `target` reverts.
             *
             * _Available since v3.1._
             */
            function functionCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal returns (bytes memory) {
                return functionCallWithValue(target, data, 0, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but also transferring `value` wei to `target`.
             *
             * Requirements:
             *
             * - the calling contract must have an ETH balance of at least `value`.
             * - the called Solidity function must be `payable`.
             *
             * _Available since v3.1._
             */
            function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
            }
            /**
             * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
             * with `errorMessage` as a fallback revert reason when `target` reverts.
             *
             * _Available since v3.1._
             */
            function functionCallWithValue(
                address target,
                bytes memory data,
                uint256 value,
                string memory errorMessage
            ) internal returns (bytes memory) {
                require(address(this).balance >= value, "Address: insufficient balance for call");
                (bool success, bytes memory returndata) = target.call{value: value}(data);
                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but performing a static call.
             *
             * _Available since v3.3._
             */
            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                return functionStaticCall(target, data, "Address: low-level static call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
             * but performing a static call.
             *
             * _Available since v3.3._
             */
            function functionStaticCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal view returns (bytes memory) {
                (bool success, bytes memory returndata) = target.staticcall(data);
                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but performing a delegate call.
             *
             * _Available since v3.4._
             */
            function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                return functionDelegateCall(target, data, "Address: low-level delegate call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
             * but performing a delegate call.
             *
             * _Available since v3.4._
             */
            function functionDelegateCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal returns (bytes memory) {
                (bool success, bytes memory returndata) = target.delegatecall(data);
                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
            }
            /**
             * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
             * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
             *
             * _Available since v4.8._
             */
            function verifyCallResultFromTarget(
                address target,
                bool success,
                bytes memory returndata,
                string memory errorMessage
            ) internal view returns (bytes memory) {
                if (success) {
                    if (returndata.length == 0) {
                        // only check isContract if the call was successful and the return data is empty
                        // otherwise we already know that it was a contract
                        require(isContract(target), "Address: call to non-contract");
                    }
                    return returndata;
                } else {
                    _revert(returndata, errorMessage);
                }
            }
            /**
             * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
             * revert reason or using the provided one.
             *
             * _Available since v4.3._
             */
            function verifyCallResult(
                bool success,
                bytes memory returndata,
                string memory errorMessage
            ) internal pure returns (bytes memory) {
                if (success) {
                    return returndata;
                } else {
                    _revert(returndata, errorMessage);
                }
            }
            function _revert(bytes memory returndata, string memory errorMessage) private pure {
                // Look for revert reason and bubble it up if present
                if (returndata.length > 0) {
                    // The easiest way to bubble the revert reason is using memory via assembly
                    /// @solidity memory-safe-assembly
                    assembly {
                        let returndata_size := mload(returndata)
                        revert(add(32, returndata), returndata_size)
                    }
                } else {
                    revert(errorMessage);
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
        // This file was procedurally generated from scripts/generate/templates/SafeCast.js.
        pragma solidity ^0.8.0;
        /**
         * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
         * checks.
         *
         * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
         * easily result in undesired exploitation or bugs, since developers usually
         * assume that overflows raise errors. `SafeCast` restores this intuition by
         * reverting the transaction when such an operation overflows.
         *
         * Using this library instead of the unchecked operations eliminates an entire
         * class of bugs, so it's recommended to use it always.
         *
         * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
         * all math on `uint256` and `int256` and then downcasting.
         */
        library SafeCast {
            /**
             * @dev Returns the downcasted 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
             *
             * _Available since v4.7._
             */
            function toUint248(uint256 value) internal pure returns (uint248) {
                require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
                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
             *
             * _Available since v4.7._
             */
            function toUint240(uint256 value) internal pure returns (uint240) {
                require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
                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
             *
             * _Available since v4.7._
             */
            function toUint232(uint256 value) internal pure returns (uint232) {
                require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
                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
             *
             * _Available since v4.2._
             */
            function toUint224(uint256 value) internal pure returns (uint224) {
                require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
                return uint224(value);
            }
            /**
             * @dev Returns the downcasted 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
             *
             * _Available since v4.7._
             */
            function toUint216(uint256 value) internal pure returns (uint216) {
                require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
                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
             *
             * _Available since v4.7._
             */
            function toUint208(uint256 value) internal pure returns (uint208) {
                require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
                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
             *
             * _Available since v4.7._
             */
            function toUint200(uint256 value) internal pure returns (uint200) {
                require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
                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
             *
             * _Available since v4.7._
             */
            function toUint192(uint256 value) internal pure returns (uint192) {
                require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
                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
             *
             * _Available since v4.7._
             */
            function toUint184(uint256 value) internal pure returns (uint184) {
                require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
                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
             *
             * _Available since v4.7._
             */
            function toUint176(uint256 value) internal pure returns (uint176) {
                require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
                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
             *
             * _Available since v4.7._
             */
            function toUint168(uint256 value) internal pure returns (uint168) {
                require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
                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
             *
             * _Available since v4.7._
             */
            function toUint160(uint256 value) internal pure returns (uint160) {
                require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
                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
             *
             * _Available since v4.7._
             */
            function toUint152(uint256 value) internal pure returns (uint152) {
                require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
                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
             *
             * _Available since v4.7._
             */
            function toUint144(uint256 value) internal pure returns (uint144) {
                require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
                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
             *
             * _Available since v4.7._
             */
            function toUint136(uint256 value) internal pure returns (uint136) {
                require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
                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
             *
             * _Available since v2.5._
             */
            function toUint128(uint256 value) internal pure returns (uint128) {
                require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
                return uint128(value);
            }
            /**
             * @dev Returns the downcasted 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
             *
             * _Available since v4.7._
             */
            function toUint120(uint256 value) internal pure returns (uint120) {
                require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
                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
             *
             * _Available since v4.7._
             */
            function toUint112(uint256 value) internal pure returns (uint112) {
                require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
                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
             *
             * _Available since v4.7._
             */
            function toUint104(uint256 value) internal pure returns (uint104) {
                require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
                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
             *
             * _Available since v4.2._
             */
            function toUint96(uint256 value) internal pure returns (uint96) {
                require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
                return uint96(value);
            }
            /**
             * @dev Returns the downcasted 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
             *
             * _Available since v4.7._
             */
            function toUint88(uint256 value) internal pure returns (uint88) {
                require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
                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
             *
             * _Available since v4.7._
             */
            function toUint80(uint256 value) internal pure returns (uint80) {
                require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
                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
             *
             * _Available since v4.7._
             */
            function toUint72(uint256 value) internal pure returns (uint72) {
                require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
                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
             *
             * _Available since v2.5._
             */
            function toUint64(uint256 value) internal pure returns (uint64) {
                require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
                return uint64(value);
            }
            /**
             * @dev Returns the downcasted 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
             *
             * _Available since v4.7._
             */
            function toUint56(uint256 value) internal pure returns (uint56) {
                require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
                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
             *
             * _Available since v4.7._
             */
            function toUint48(uint256 value) internal pure returns (uint48) {
                require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
                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
             *
             * _Available since v4.7._
             */
            function toUint40(uint256 value) internal pure returns (uint40) {
                require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
                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
             *
             * _Available since v2.5._
             */
            function toUint32(uint256 value) internal pure returns (uint32) {
                require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
                return uint32(value);
            }
            /**
             * @dev Returns the downcasted 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
             *
             * _Available since v4.7._
             */
            function toUint24(uint256 value) internal pure returns (uint24) {
                require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
                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
             *
             * _Available since v2.5._
             */
            function toUint16(uint256 value) internal pure returns (uint16) {
                require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
                return uint16(value);
            }
            /**
             * @dev Returns the downcasted uint8 from uint256, reverting on
             * overflow (when the input is greater than largest uint8).
             *
             * Counterpart to Solidity's `uint8` operator.
             *
             * Requirements:
             *
             * - input must fit into 8 bits
             *
             * _Available since v2.5._
             */
            function toUint8(uint256 value) internal pure returns (uint8) {
                require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
                return uint8(value);
            }
            /**
             * @dev Converts a signed int256 into an unsigned uint256.
             *
             * Requirements:
             *
             * - input must be greater than or equal to 0.
             *
             * _Available since v3.0._
             */
            function toUint256(int256 value) internal pure returns (uint256) {
                require(value >= 0, "SafeCast: value must be positive");
                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
             *
             * _Available since v4.7._
             */
            function toInt248(int256 value) internal pure returns (int248 downcasted) {
                downcasted = int248(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt240(int256 value) internal pure returns (int240 downcasted) {
                downcasted = int240(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt232(int256 value) internal pure returns (int232 downcasted) {
                downcasted = int232(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt224(int256 value) internal pure returns (int224 downcasted) {
                downcasted = int224(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt216(int256 value) internal pure returns (int216 downcasted) {
                downcasted = int216(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt208(int256 value) internal pure returns (int208 downcasted) {
                downcasted = int208(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt200(int256 value) internal pure returns (int200 downcasted) {
                downcasted = int200(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt192(int256 value) internal pure returns (int192 downcasted) {
                downcasted = int192(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt184(int256 value) internal pure returns (int184 downcasted) {
                downcasted = int184(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt176(int256 value) internal pure returns (int176 downcasted) {
                downcasted = int176(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt168(int256 value) internal pure returns (int168 downcasted) {
                downcasted = int168(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt160(int256 value) internal pure returns (int160 downcasted) {
                downcasted = int160(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt152(int256 value) internal pure returns (int152 downcasted) {
                downcasted = int152(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt144(int256 value) internal pure returns (int144 downcasted) {
                downcasted = int144(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt136(int256 value) internal pure returns (int136 downcasted) {
                downcasted = int136(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
            }
            /**
             * @dev Returns the downcasted int128 from int256, reverting on
             * overflow (when the input is less than smallest int128 or
             * greater than largest int128).
             *
             * Counterpart to Solidity's `int128` operator.
             *
             * Requirements:
             *
             * - input must fit into 128 bits
             *
             * _Available since v3.1._
             */
            function toInt128(int256 value) internal pure returns (int128 downcasted) {
                downcasted = int128(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt120(int256 value) internal pure returns (int120 downcasted) {
                downcasted = int120(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt112(int256 value) internal pure returns (int112 downcasted) {
                downcasted = int112(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt104(int256 value) internal pure returns (int104 downcasted) {
                downcasted = int104(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt96(int256 value) internal pure returns (int96 downcasted) {
                downcasted = int96(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt88(int256 value) internal pure returns (int88 downcasted) {
                downcasted = int88(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt80(int256 value) internal pure returns (int80 downcasted) {
                downcasted = int80(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt72(int256 value) internal pure returns (int72 downcasted) {
                downcasted = int72(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
            }
            /**
             * @dev Returns the downcasted int64 from int256, reverting on
             * overflow (when the input is less than smallest int64 or
             * greater than largest int64).
             *
             * Counterpart to Solidity's `int64` operator.
             *
             * Requirements:
             *
             * - input must fit into 64 bits
             *
             * _Available since v3.1._
             */
            function toInt64(int256 value) internal pure returns (int64 downcasted) {
                downcasted = int64(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt56(int256 value) internal pure returns (int56 downcasted) {
                downcasted = int56(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt48(int256 value) internal pure returns (int48 downcasted) {
                downcasted = int48(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt40(int256 value) internal pure returns (int40 downcasted) {
                downcasted = int40(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
            }
            /**
             * @dev Returns the downcasted int32 from int256, reverting on
             * overflow (when the input is less than smallest int32 or
             * greater than largest int32).
             *
             * Counterpart to Solidity's `int32` operator.
             *
             * Requirements:
             *
             * - input must fit into 32 bits
             *
             * _Available since v3.1._
             */
            function toInt32(int256 value) internal pure returns (int32 downcasted) {
                downcasted = int32(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
            }
            /**
             * @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
             *
             * _Available since v4.7._
             */
            function toInt24(int256 value) internal pure returns (int24 downcasted) {
                downcasted = int24(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
            }
            /**
             * @dev Returns the downcasted int16 from int256, reverting on
             * overflow (when the input is less than smallest int16 or
             * greater than largest int16).
             *
             * Counterpart to Solidity's `int16` operator.
             *
             * Requirements:
             *
             * - input must fit into 16 bits
             *
             * _Available since v3.1._
             */
            function toInt16(int256 value) internal pure returns (int16 downcasted) {
                downcasted = int16(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
            }
            /**
             * @dev Returns the downcasted int8 from int256, reverting on
             * overflow (when the input is less than smallest int8 or
             * greater than largest int8).
             *
             * Counterpart to Solidity's `int8` operator.
             *
             * Requirements:
             *
             * - input must fit into 8 bits
             *
             * _Available since v3.1._
             */
            function toInt8(int256 value) internal pure returns (int8 downcasted) {
                downcasted = int8(value);
                require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
            }
            /**
             * @dev Converts an unsigned uint256 into a signed int256.
             *
             * Requirements:
             *
             * - input must be less than or equal to maxInt256.
             *
             * _Available since v3.0._
             */
            function toInt256(uint256 value) internal pure returns (int256) {
                // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
                require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
                return int256(value);
            }
        }
        // SPDX-License-Identifier: BUSL-1.1
        pragma solidity ^0.8.4;
        import "./RedstoneConstants.sol";
        /**
         * @title The base contract with the main logic of data extraction from calldata
         * @author The Redstone Oracles team
         * @dev This contract was created to reuse the same logic in the RedstoneConsumerBase
         * and the ProxyConnector contracts
         */
        contract CalldataExtractor is RedstoneConstants {
          error DataPackageTimestampMustNotBeZero();
          error DataPackageTimestampsMustBeEqual();
          error RedstonePayloadMustHaveAtLeastOneDataPackage();
          error TooLargeValueByteSize(uint256 valueByteSize);
          function extractTimestampsAndAssertAllAreEqual() public pure returns (uint256 extractedTimestamp) {
            uint256 calldataNegativeOffset = _extractByteSizeOfUnsignedMetadata();
            uint256 dataPackagesCount;
            (dataPackagesCount, calldataNegativeOffset) = _extractDataPackagesCountFromCalldata(calldataNegativeOffset);
            if (dataPackagesCount == 0) {
              revert RedstonePayloadMustHaveAtLeastOneDataPackage();
            }
            for (uint256 dataPackageIndex = 0; dataPackageIndex < dataPackagesCount; dataPackageIndex++) {
              uint256 dataPackageByteSize = _getDataPackageByteSize(calldataNegativeOffset);
              // Extracting timestamp for the current data package
              uint48 dataPackageTimestamp; // uint48, because timestamp uses 6 bytes
              uint256 timestampNegativeOffset = (calldataNegativeOffset + TIMESTAMP_NEGATIVE_OFFSET_IN_DATA_PACKAGE_WITH_STANDARD_SLOT_BS);
              uint256 timestampOffset = msg.data.length - timestampNegativeOffset;
              assembly {
                dataPackageTimestamp := calldataload(timestampOffset)
              }
              if (dataPackageTimestamp == 0) {
                revert DataPackageTimestampMustNotBeZero();
              }
              if (extractedTimestamp == 0) {
                extractedTimestamp = dataPackageTimestamp;
              } else if (dataPackageTimestamp != extractedTimestamp) {
                revert DataPackageTimestampsMustBeEqual();
              }
              calldataNegativeOffset += dataPackageByteSize;
            }
          }
          function _getDataPackageByteSize(uint256 calldataNegativeOffset) internal pure returns (uint256) {
            (
              uint256 dataPointsCount,
              uint256 eachDataPointValueByteSize
            ) = _extractDataPointsDetailsForDataPackage(calldataNegativeOffset);
            return
              dataPointsCount *
              (DATA_POINT_SYMBOL_BS + eachDataPointValueByteSize) +
              DATA_PACKAGE_WITHOUT_DATA_POINTS_BS;
          }
          function _extractByteSizeOfUnsignedMetadata() internal pure returns (uint256) {
            // Checking if the calldata ends with the RedStone marker
            bool hasValidRedstoneMarker;
            assembly {
              let calldataLast32Bytes := calldataload(sub(calldatasize(), STANDARD_SLOT_BS))
              hasValidRedstoneMarker := eq(
                REDSTONE_MARKER_MASK,
                and(calldataLast32Bytes, REDSTONE_MARKER_MASK)
              )
            }
            if (!hasValidRedstoneMarker) {
              revert CalldataMustHaveValidPayload();
            }
            // Using uint24, because unsigned metadata byte size number has 3 bytes
            uint24 unsignedMetadataByteSize;
            if (REDSTONE_MARKER_BS_PLUS_STANDARD_SLOT_BS > msg.data.length) {
              revert CalldataOverOrUnderFlow();
            }
            assembly {
              unsignedMetadataByteSize := calldataload(
                sub(calldatasize(), REDSTONE_MARKER_BS_PLUS_STANDARD_SLOT_BS)
              )
            }
            uint256 calldataNegativeOffset = unsignedMetadataByteSize
              + UNSIGNED_METADATA_BYTE_SIZE_BS
              + REDSTONE_MARKER_BS;
            if (calldataNegativeOffset + DATA_PACKAGES_COUNT_BS > msg.data.length) {
              revert IncorrectUnsignedMetadataSize();
            }
            return calldataNegativeOffset;
          }
          // We return uint16, because unsigned metadata byte size number has 2 bytes
          function _extractDataPackagesCountFromCalldata(uint256 calldataNegativeOffset)
            internal
            pure
            returns (uint16 dataPackagesCount, uint256 nextCalldataNegativeOffset)
          {
            uint256 calldataNegativeOffsetWithStandardSlot = calldataNegativeOffset + STANDARD_SLOT_BS;
            if (calldataNegativeOffsetWithStandardSlot > msg.data.length) {
              revert CalldataOverOrUnderFlow();
            }
            assembly {
              dataPackagesCount := calldataload(
                sub(calldatasize(), calldataNegativeOffsetWithStandardSlot)
              )
            }
            return (dataPackagesCount, calldataNegativeOffset + DATA_PACKAGES_COUNT_BS);
          }
          function _extractDataPointValueAndDataFeedId(
            uint256 dataPointNegativeOffset,
            uint256 dataPointValueByteSize
          ) internal pure virtual returns (bytes32 dataPointDataFeedId, uint256 dataPointValue) {
            uint256 dataPointCalldataOffset = msg.data.length - dataPointNegativeOffset;
            assembly {
              dataPointDataFeedId := calldataload(dataPointCalldataOffset)
              dataPointValue := calldataload(add(dataPointCalldataOffset, DATA_POINT_SYMBOL_BS))
            }
            if (dataPointValueByteSize >= 33) {
              revert TooLargeValueByteSize(dataPointValueByteSize);
            }
            unchecked {
              dataPointValue = dataPointValue >> (32 - dataPointValueByteSize) * 8; 
            }
          }
          function _extractDataPointsDetailsForDataPackage(uint256 calldataNegativeOffsetForDataPackage)
            internal
            pure
            returns (uint256 dataPointsCount, uint256 eachDataPointValueByteSize)
          {
            // Using uint24, because data points count byte size number has 3 bytes
            uint24 dataPointsCount_;
            // Using uint32, because data point value byte size has 4 bytes
            uint32 eachDataPointValueByteSize_;
            // Extract data points count
            uint256 calldataOffset = msg.data.length - (calldataNegativeOffsetForDataPackage + SIG_BS + STANDARD_SLOT_BS);
            assembly {
              dataPointsCount_ := calldataload(calldataOffset)
            }
            // Extract each data point value size
            calldataOffset = calldataOffset - DATA_POINTS_COUNT_BS;
            assembly {
              eachDataPointValueByteSize_ := calldataload(calldataOffset)
            }
            // Prepare returned values
            dataPointsCount = dataPointsCount_;
            eachDataPointValueByteSize = eachDataPointValueByteSize_;
          }
        }
        // SPDX-License-Identifier: BUSL-1.1
        pragma solidity ^0.8.4;
        /**
         * @title The base contract with helpful constants
         * @author The Redstone Oracles team
         * @dev It mainly contains redstone-related values, which improve readability
         * of other contracts (e.g. CalldataExtractor and RedstoneConsumerBase)
         */
        contract RedstoneConstants {
          // === Abbreviations ===
          // BS - Bytes size
          // PTR - Pointer (memory location)
          // SIG - Signature
          // Solidity and YUL constants
          uint256 internal constant STANDARD_SLOT_BS = 32;
          uint256 internal constant FREE_MEMORY_PTR = 0x40;
          uint256 internal constant BYTES_ARR_LEN_VAR_BS = 32;
          uint256 internal constant FUNCTION_SIGNATURE_BS = 4;
          uint256 internal constant REVERT_MSG_OFFSET = 68; // Revert message structure described here: https://ethereum.stackexchange.com/a/66173/106364
          uint256 internal constant STRING_ERR_MESSAGE_MASK = 0x08c379a000000000000000000000000000000000000000000000000000000000;
          // RedStone protocol consts
          uint256 internal constant SIG_BS = 65;
          uint256 internal constant TIMESTAMP_BS = 6;
          uint256 internal constant DATA_PACKAGES_COUNT_BS = 2;
          uint256 internal constant DATA_POINTS_COUNT_BS = 3;
          uint256 internal constant DATA_POINT_VALUE_BYTE_SIZE_BS = 4;
          uint256 internal constant DATA_POINT_SYMBOL_BS = 32;
          uint256 internal constant DEFAULT_DATA_POINT_VALUE_BS = 32;
          uint256 internal constant UNSIGNED_METADATA_BYTE_SIZE_BS = 3;
          uint256 internal constant REDSTONE_MARKER_BS = 9; // byte size of 0x000002ed57011e0000
          uint256 internal constant REDSTONE_MARKER_MASK = 0x0000000000000000000000000000000000000000000000000002ed57011e0000;
          // Derived values (based on consts)
          uint256 internal constant TIMESTAMP_NEGATIVE_OFFSET_IN_DATA_PACKAGE_WITH_STANDARD_SLOT_BS = 104; // SIG_BS + DATA_POINTS_COUNT_BS + DATA_POINT_VALUE_BYTE_SIZE_BS + STANDARD_SLOT_BS
          uint256 internal constant DATA_PACKAGE_WITHOUT_DATA_POINTS_BS = 78; // DATA_POINT_VALUE_BYTE_SIZE_BS + TIMESTAMP_BS + DATA_POINTS_COUNT_BS + SIG_BS
          uint256 internal constant DATA_PACKAGE_WITHOUT_DATA_POINTS_AND_SIG_BS = 13; // DATA_POINT_VALUE_BYTE_SIZE_BS + TIMESTAMP_BS + DATA_POINTS_COUNT_BS
          uint256 internal constant REDSTONE_MARKER_BS_PLUS_STANDARD_SLOT_BS = 41; // REDSTONE_MARKER_BS + STANDARD_SLOT_BS
          // Error messages
          error CalldataOverOrUnderFlow();
          error IncorrectUnsignedMetadataSize();
          error InsufficientNumberOfUniqueSigners(uint256 receivedSignersCount, uint256 requiredSignersCount);
          error EachSignerMustProvideTheSameValue();
          error EmptyCalldataPointersArr();
          error InvalidCalldataPointer();
          error CalldataMustHaveValidPayload();
          error SignerNotAuthorised(address receivedSigner);
          error DataTimestampCannotBeZero();
          error TimestampsMustBeEqual();
        }
        // SPDX-License-Identifier: BUSL-1.1
        pragma solidity ^0.8.4;
        import "./RedstoneConstants.sol";
        import "./RedstoneDefaultsLib.sol";
        import "./CalldataExtractor.sol";
        import "../libs/BitmapLib.sol";
        import "../libs/SignatureLib.sol";
        /**
         * @title The base contract with the main Redstone logic
         * @author The Redstone Oracles team
         * @dev Do not use this contract directly in consumer contracts, take a
         * look at `RedstoneConsumerNumericBase` and `RedstoneConsumerBytesBase` instead
         */
        abstract contract RedstoneConsumerBase is CalldataExtractor {
          error GetDataServiceIdNotImplemented();
          /* ========== VIRTUAL FUNCTIONS (MAY BE OVERRIDDEN IN CHILD CONTRACTS) ========== */
          /**
           * @dev This function must be implemented by the child consumer contract.
           * It should return dataServiceId which DataServiceWrapper will use if not provided explicitly .
           * If not overridden, value will always have to be provided explicitly in DataServiceWrapper.
           * @return dataServiceId being consumed by contract
           */
          function getDataServiceId() public view virtual returns (string memory) {
            revert GetDataServiceIdNotImplemented();
          }
          /**
           * @dev This function must be implemented by the child consumer contract.
           * It should return a unique index for a given signer address if the signer
           * is authorised, otherwise it should revert
           * @param receivedSigner The address of a signer, recovered from ECDSA signature
           * @return Unique index for a signer in the range [0..255]
           */
          function getAuthorisedSignerIndex(address receivedSigner) public view virtual returns (uint8);
          /**
           * @dev This function may be overridden by the child consumer contract.
           * It should validate the timestamp against the current time (block.timestamp)
           * It should revert with a helpful message if the timestamp is not valid
           * @param receivedTimestampMilliseconds Timestamp extracted from calldata
           */
          function validateTimestamp(uint256 receivedTimestampMilliseconds) public view virtual {
            RedstoneDefaultsLib.validateTimestamp(receivedTimestampMilliseconds);
          }
          /**
           * @dev This function should be overridden by the child consumer contract.
           * @return The minimum required value of unique authorised signers
           */
          function getUniqueSignersThreshold() public view virtual returns (uint8) {
            return 1;
          }
          /**
           * @dev This function may be overridden by the child consumer contract.
           * It should aggregate values from different signers to a single uint value.
           * By default, it calculates the median value
           * @param values An array of uint256 values from different signers
           * @return Result of the aggregation in the form of a single number
           */
          function aggregateValues(uint256[] memory values) public view virtual returns (uint256) {
            return RedstoneDefaultsLib.aggregateValues(values);
          }
          /* ========== FUNCTIONS WITH IMPLEMENTATION (CAN NOT BE OVERRIDDEN) ========== */
          /**
           * @dev This is an internal helpful function for secure extraction oracle values
           * from the tx calldata. Security is achieved by signatures verification, timestamp
           * validation, and aggregating values from different authorised signers into a
           * single numeric value. If any of the required conditions (e.g. packages with different 
           * timestamps or insufficient number of authorised signers) do not match, the function 
           * will revert.
           *
           * Note! You should not call this function in a consumer contract. You can use
           * `getOracleNumericValuesFromTxMsg` or `getOracleNumericValueFromTxMsg` instead.
           *
           * @param dataFeedIds An array of unique data feed identifiers
           * @return An array of the extracted and verified oracle values in the same order
           * as they are requested in dataFeedIds array
           * @return dataPackagesTimestamp timestamp equal for all data packages
           */
          function _securelyExtractOracleValuesAndTimestampFromTxMsg(bytes32[] memory dataFeedIds)
            internal
            view
            returns (uint256[] memory, uint256 dataPackagesTimestamp)
          {
            // Initializing helpful variables and allocating memory
            uint256[] memory uniqueSignerCountForDataFeedIds = new uint256[](dataFeedIds.length);
            uint256[] memory signersBitmapForDataFeedIds = new uint256[](dataFeedIds.length);
            uint256[][] memory valuesForDataFeeds = new uint256[][](dataFeedIds.length);
            for (uint256 i = 0; i < dataFeedIds.length;) {
              // The line below is commented because newly allocated arrays are filled with zeros
              // But we left it for better readability
              // signersBitmapForDataFeedIds[i] = 0; // <- setting to an empty bitmap
              valuesForDataFeeds[i] = new uint256[](getUniqueSignersThreshold());
              unchecked {
                i++;
              }
            }
            // Extracting the number of data packages from calldata
            uint256 calldataNegativeOffset = _extractByteSizeOfUnsignedMetadata();
            uint256 dataPackagesCount;
            (dataPackagesCount, calldataNegativeOffset) = _extractDataPackagesCountFromCalldata(calldataNegativeOffset);
            // Saving current free memory pointer
            uint256 freeMemPtr;
            assembly {
              freeMemPtr := mload(FREE_MEMORY_PTR)
            }
            // Data packages extraction in a loop
            for (uint256 dataPackageIndex = 0; dataPackageIndex < dataPackagesCount;) {
              // Extract data package details and update calldata offset
              uint256 dataPackageTimestamp;
              (calldataNegativeOffset, dataPackageTimestamp) = _extractDataPackage(
                dataFeedIds,
                uniqueSignerCountForDataFeedIds,
                signersBitmapForDataFeedIds,
                valuesForDataFeeds,
                calldataNegativeOffset
              );
              if (dataPackageTimestamp == 0) {
                revert DataTimestampCannotBeZero();
              }
              if (dataPackageTimestamp != dataPackagesTimestamp && dataPackagesTimestamp != 0) {
                revert TimestampsMustBeEqual();
              }
              dataPackagesTimestamp = dataPackageTimestamp;
              // Shifting memory pointer back to the "safe" value
              assembly {
                mstore(FREE_MEMORY_PTR, freeMemPtr)
              }
              unchecked {
                dataPackageIndex++;
              }
            }
            // Validating numbers of unique signers and calculating aggregated values for each dataFeedId
            return (_getAggregatedValues(valuesForDataFeeds, uniqueSignerCountForDataFeedIds), dataPackagesTimestamp);
          }
          /**
           * @dev This is a private helpful function, which extracts data for a data package based
           * on the given negative calldata offset, verifies them, and in the case of successful
           * verification updates the corresponding data package values in memory
           *
           * @param dataFeedIds an array of unique data feed identifiers
           * @param uniqueSignerCountForDataFeedIds an array with the numbers of unique signers
           * for each data feed
           * @param signersBitmapForDataFeedIds an array of signer bitmaps for data feeds
           * @param valuesForDataFeeds 2-dimensional array, valuesForDataFeeds[i][j] contains
           * j-th value for the i-th data feed
           * @param calldataNegativeOffset negative calldata offset for the given data package
           *
           * @return nextCalldataNegativeOffset negative calldata offset for the next data package
           * @return dataPackageTimestamp data package timestamp
           */
          function _extractDataPackage(
            bytes32[] memory dataFeedIds,
            uint256[] memory uniqueSignerCountForDataFeedIds,
            uint256[] memory signersBitmapForDataFeedIds,
            uint256[][] memory valuesForDataFeeds,
            uint256 calldataNegativeOffset
          ) private view returns (uint256 nextCalldataNegativeOffset, uint256 dataPackageTimestamp) {
            uint256 signerIndex;
            (
              uint256 dataPointsCount,
              uint256 eachDataPointValueByteSize
            ) = _extractDataPointsDetailsForDataPackage(calldataNegativeOffset);
            // We use scopes to resolve problem with too deep stack
            {
              address signerAddress;
              bytes32 signedHash;
              bytes memory signedMessage;
              uint256 signedMessageBytesCount;
              uint48 extractedTimestamp;
              signedMessageBytesCount = dataPointsCount * (eachDataPointValueByteSize + DATA_POINT_SYMBOL_BS)
                + DATA_PACKAGE_WITHOUT_DATA_POINTS_AND_SIG_BS; //DATA_POINT_VALUE_BYTE_SIZE_BS + TIMESTAMP_BS + DATA_POINTS_COUNT_BS
              uint256 timestampCalldataOffset = msg.data.length - 
                (calldataNegativeOffset + TIMESTAMP_NEGATIVE_OFFSET_IN_DATA_PACKAGE_WITH_STANDARD_SLOT_BS);
              uint256 signedMessageCalldataOffset = msg.data.length - 
                (calldataNegativeOffset + SIG_BS + signedMessageBytesCount);
              assembly {
                // Extracting the signed message
                signedMessage := extractBytesFromCalldata(
                  signedMessageCalldataOffset,
                  signedMessageBytesCount
                )
                // Hashing the signed message
                signedHash := keccak256(add(signedMessage, BYTES_ARR_LEN_VAR_BS), signedMessageBytesCount)
                // Extracting timestamp
                extractedTimestamp := calldataload(timestampCalldataOffset)
                function initByteArray(bytesCount) -> ptr {
                  ptr := mload(FREE_MEMORY_PTR)
                  mstore(ptr, bytesCount)
                  ptr := add(ptr, BYTES_ARR_LEN_VAR_BS)
                  mstore(FREE_MEMORY_PTR, add(ptr, bytesCount))
                }
                function extractBytesFromCalldata(offset, bytesCount) -> extractedBytes {
                  let extractedBytesStartPtr := initByteArray(bytesCount)
                  calldatacopy(
                    extractedBytesStartPtr,
                    offset,
                    bytesCount
                  )
                  extractedBytes := sub(extractedBytesStartPtr, BYTES_ARR_LEN_VAR_BS)
                }
              }
              dataPackageTimestamp = extractedTimestamp;
              // Verifying the off-chain signature against on-chain hashed data
              signerAddress = SignatureLib.recoverSignerAddress(
                signedHash,
                calldataNegativeOffset + SIG_BS
              );
              signerIndex = getAuthorisedSignerIndex(signerAddress);
            }
            // Updating helpful arrays
            {
              calldataNegativeOffset = calldataNegativeOffset + DATA_PACKAGE_WITHOUT_DATA_POINTS_BS;
              bytes32 dataPointDataFeedId;
              uint256 dataPointValue;
              for (uint256 dataPointIndex = 0; dataPointIndex < dataPointsCount;) {
                calldataNegativeOffset = calldataNegativeOffset + eachDataPointValueByteSize + DATA_POINT_SYMBOL_BS;
                // Extracting data feed id and value for the current data point
                (dataPointDataFeedId, dataPointValue) = _extractDataPointValueAndDataFeedId(
                  calldataNegativeOffset,
                  eachDataPointValueByteSize
                );
                for (
                  uint256 dataFeedIdIndex = 0;
                  dataFeedIdIndex < dataFeedIds.length;
                ) {
                  if (dataPointDataFeedId == dataFeedIds[dataFeedIdIndex]) {
                    uint256 bitmapSignersForDataFeedId = signersBitmapForDataFeedIds[dataFeedIdIndex];
                    if (
                      !BitmapLib.getBitFromBitmap(bitmapSignersForDataFeedId, signerIndex) && /* current signer was not counted for current dataFeedId */
                      uniqueSignerCountForDataFeedIds[dataFeedIdIndex] < getUniqueSignersThreshold()
                    ) {
                      // Add new value
                      valuesForDataFeeds[dataFeedIdIndex][uniqueSignerCountForDataFeedIds[dataFeedIdIndex]] = dataPointValue;
                      // Increase unique signer counter
                      uniqueSignerCountForDataFeedIds[dataFeedIdIndex]++;
                      // Update signers bitmap
                      signersBitmapForDataFeedIds[dataFeedIdIndex] = BitmapLib.setBitInBitmap(
                        bitmapSignersForDataFeedId,
                        signerIndex
                      );
                    }
                    // Breaking, as there couldn't be several indexes for the same feed ID
                    break;
                  }
                  unchecked {
                    dataFeedIdIndex++;
                  }
                }
                unchecked {
                   dataPointIndex++;
                }
              }
            }
            return (calldataNegativeOffset, dataPackageTimestamp);
          }
          /**
           * @dev This is a private helpful function, which aggregates values from different
           * authorised signers for the given arrays of values for each data feed
           *
           * @param valuesForDataFeeds 2-dimensional array, valuesForDataFeeds[i][j] contains
           * j-th value for the i-th data feed
           * @param uniqueSignerCountForDataFeedIds an array with the numbers of unique signers
           * for each data feed
           *
           * @return An array of the aggregated values
           */
          function _getAggregatedValues(
            uint256[][] memory valuesForDataFeeds,
            uint256[] memory uniqueSignerCountForDataFeedIds
          ) private view returns (uint256[] memory) {
            uint256[] memory aggregatedValues = new uint256[](valuesForDataFeeds.length);
            uint256 uniqueSignersThreshold = getUniqueSignersThreshold();
            for (uint256 dataFeedIndex = 0; dataFeedIndex < valuesForDataFeeds.length; dataFeedIndex++) {
              if (uniqueSignerCountForDataFeedIds[dataFeedIndex] < uniqueSignersThreshold) {
                revert InsufficientNumberOfUniqueSigners(
                  uniqueSignerCountForDataFeedIds[dataFeedIndex],
                  uniqueSignersThreshold);
              }
              uint256 aggregatedValueForDataFeedId = aggregateValues(valuesForDataFeeds[dataFeedIndex]);
              aggregatedValues[dataFeedIndex] = aggregatedValueForDataFeedId;
            }
            return aggregatedValues;
          }
        }
        // SPDX-License-Identifier: BUSL-1.1
        pragma solidity ^0.8.4;
        import "./RedstoneConsumerBase.sol";
        /**
         * @title The base contract for Redstone consumers' contracts that allows to
         * securely calculate numeric redstone oracle values
         * @author The Redstone Oracles team
         * @dev This contract can extend other contracts to allow them
         * securely fetch Redstone oracle data from transactions calldata
         */
        abstract contract RedstoneConsumerNumericBase is RedstoneConsumerBase {
          /**
           * @dev This function can be used in a consumer contract to securely extract an
           * oracle value for a given data feed id. Security is achieved by
           * signatures verification, timestamp validation, and aggregating values
           * from different authorised signers into a single numeric value. If any of the
           * required conditions do not match, the function will revert.
           * Note! This function expects that tx calldata contains redstone payload in the end
           * Learn more about redstone payload here: https://github.com/redstone-finance/redstone-oracles-monorepo/tree/main/packages/evm-connector#readme
           * @param dataFeedId bytes32 value that uniquely identifies the data feed
           * @return Extracted and verified numeric oracle value for the given data feed id
           */
          function getOracleNumericValueFromTxMsg(bytes32 dataFeedId)
            internal
            view
            virtual
            returns (uint256)
          {
            bytes32[] memory dataFeedIds = new bytes32[](1);
            dataFeedIds[0] = dataFeedId;
            return getOracleNumericValuesFromTxMsg(dataFeedIds)[0];
          }
          /**
           * @dev This function can be used in a consumer contract to securely extract several
           * numeric oracle values for a given array of data feed ids. Security is achieved by
           * signatures verification, timestamp validation, and aggregating values
           * from different authorised signers into a single numeric value. If any of the
           * required conditions do not match, the function will revert.
           * Note! This function expects that tx calldata contains redstone payload in the end
           * Learn more about redstone payload here: https://github.com/redstone-finance/redstone-oracles-monorepo/tree/main/packages/evm-connector#readme
           * @param dataFeedIds An array of unique data feed identifiers
           * @return An array of the extracted and verified oracle values in the same order
           * as they are requested in the dataFeedIds array
           */
          function getOracleNumericValuesFromTxMsg(bytes32[] memory dataFeedIds)
            internal
            view
            virtual
            returns (uint256[] memory)
          {
            (uint256[] memory values, uint256 timestamp) = _securelyExtractOracleValuesAndTimestampFromTxMsg(dataFeedIds);
            validateTimestamp(timestamp);
            return values;
          }
          /**
           * @dev This function can be used in a consumer contract to securely extract several
           * numeric oracle values for a given array of data feed ids. Security is achieved by
           * signatures verification and aggregating values from different authorised signers 
           * into a single numeric value. If any of the required conditions do not match, 
           * the function will revert.
           * Note! This function returns the timestamp of the packages (it requires it to be 
           * the same for all), but does not validate this timestamp.
           * Note! This function expects that tx calldata contains redstone payload in the end
           * Learn more about redstone payload here: https://github.com/redstone-finance/redstone-oracles-monorepo/tree/main/packages/evm-connector#readme
           * @param dataFeedIds An array of unique data feed identifiers
           * @return An array of the extracted and verified oracle values in the same order
           * as they are requested in the dataFeedIds array and data packages timestamp
           */
           function getOracleNumericValuesAndTimestampFromTxMsg(bytes32[] memory dataFeedIds)
            internal
            view
            virtual
            returns (uint256[] memory, uint256)
          {
            return _securelyExtractOracleValuesAndTimestampFromTxMsg(dataFeedIds);
          }
          /**
           * @dev This function works similarly to the `getOracleNumericValuesFromTxMsg` with the
           * only difference that it allows to request oracle data for an array of data feeds
           * that may contain duplicates
           * 
           * @param dataFeedIdsWithDuplicates An array of data feed identifiers (duplicates are allowed)
           * @return An array of the extracted and verified oracle values in the same order
           * as they are requested in the dataFeedIdsWithDuplicates array
           */
          function getOracleNumericValuesWithDuplicatesFromTxMsg(bytes32[] memory dataFeedIdsWithDuplicates) internal view returns (uint256[] memory) {
            // Building an array without duplicates
            bytes32[] memory dataFeedIdsWithoutDuplicates = new bytes32[](dataFeedIdsWithDuplicates.length);
            bool alreadyIncluded;
            uint256 uniqueDataFeedIdsCount = 0;
            for (uint256 indexWithDup = 0; indexWithDup < dataFeedIdsWithDuplicates.length; indexWithDup++) {
              // Checking if current element is already included in `dataFeedIdsWithoutDuplicates`
              alreadyIncluded = false;
              for (uint256 indexWithoutDup = 0; indexWithoutDup < uniqueDataFeedIdsCount; indexWithoutDup++) {
                if (dataFeedIdsWithoutDuplicates[indexWithoutDup] == dataFeedIdsWithDuplicates[indexWithDup]) {
                  alreadyIncluded = true;
                  break;
                }
              }
              // Adding if not included
              if (!alreadyIncluded) {
                dataFeedIdsWithoutDuplicates[uniqueDataFeedIdsCount] = dataFeedIdsWithDuplicates[indexWithDup];
                uniqueDataFeedIdsCount++;
              }
            }
            // Overriding dataFeedIdsWithoutDuplicates.length
            // Equivalent to: dataFeedIdsWithoutDuplicates.length = uniqueDataFeedIdsCount;
            assembly {
              mstore(dataFeedIdsWithoutDuplicates, uniqueDataFeedIdsCount)
            }
            // Requesting oracle values (without duplicates)
            (uint256[] memory valuesWithoutDuplicates, uint256 timestamp) = _securelyExtractOracleValuesAndTimestampFromTxMsg(dataFeedIdsWithoutDuplicates);
            validateTimestamp(timestamp);
            // Preparing result values array
            uint256[] memory valuesWithDuplicates = new uint256[](dataFeedIdsWithDuplicates.length);
            for (uint256 indexWithDup = 0; indexWithDup < dataFeedIdsWithDuplicates.length; indexWithDup++) {
              for (uint256 indexWithoutDup = 0; indexWithoutDup < dataFeedIdsWithoutDuplicates.length; indexWithoutDup++) {
                if (dataFeedIdsWithDuplicates[indexWithDup] == dataFeedIdsWithoutDuplicates[indexWithoutDup]) {
                  valuesWithDuplicates[indexWithDup] = valuesWithoutDuplicates[indexWithoutDup];
                  break;
                }
              }
            }
            return valuesWithDuplicates;
          }
        }
        // SPDX-License-Identifier: BUSL-1.1
        pragma solidity ^0.8.4;
        import "../libs/NumericArrayLib.sol";
        /**
         * @title Default implementations of virtual redstone consumer base functions
         * @author The Redstone Oracles team
         */
        library RedstoneDefaultsLib {
          uint256 constant DEFAULT_MAX_DATA_TIMESTAMP_DELAY_SECONDS = 3 minutes;
          uint256 constant DEFAULT_MAX_DATA_TIMESTAMP_AHEAD_SECONDS = 1 minutes;
          error TimestampFromTooLongFuture(uint256 receivedTimestampSeconds, uint256 blockTimestamp);
          error TimestampIsTooOld(uint256 receivedTimestampSeconds, uint256 blockTimestamp);
          function validateTimestamp(uint256 receivedTimestampMilliseconds) internal view {
            // Getting data timestamp from future seems quite unlikely
            // But we've already spent too much time with different cases
            // Where block.timestamp was less than dataPackage.timestamp.
            // Some blockchains may case this problem as well.
            // That's why we add MAX_BLOCK_TIMESTAMP_DELAY
            // and allow data "from future" but with a small delay
            uint256 receivedTimestampSeconds = receivedTimestampMilliseconds / 1000;
            if (block.timestamp < receivedTimestampSeconds) {
              if ((receivedTimestampSeconds - block.timestamp) > DEFAULT_MAX_DATA_TIMESTAMP_AHEAD_SECONDS) {
                revert TimestampFromTooLongFuture(receivedTimestampSeconds, block.timestamp);
              }
            } else if ((block.timestamp - receivedTimestampSeconds) > DEFAULT_MAX_DATA_TIMESTAMP_DELAY_SECONDS) {
              revert TimestampIsTooOld(receivedTimestampSeconds, block.timestamp);
            }
          }
          function aggregateValues(uint256[] memory values) internal pure returns (uint256) {
            return NumericArrayLib.pickMedian(values);
          }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.4;
        library BitmapLib {
          function setBitInBitmap(uint256 bitmap, uint256 bitIndex) internal pure returns (uint256) {
            return bitmap | (1 << bitIndex);
          }
          function getBitFromBitmap(uint256 bitmap, uint256 bitIndex) internal pure returns (bool) {
            uint256 bitAtIndex = bitmap & (1 << bitIndex);
            return bitAtIndex > 0;
          }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.4;
        library NumericArrayLib {
          // This function sort array in memory using bubble sort algorithm,
          // which performs even better than quick sort for small arrays
          uint256 constant BYTES_ARR_LEN_VAR_BS = 32;
          uint256 constant UINT256_VALUE_BS = 32;
          error CanNotPickMedianOfEmptyArray();
          // This function modifies the array
          function pickMedian(uint256[] memory arr) internal pure returns (uint256) {
            if (arr.length == 0) {
              revert CanNotPickMedianOfEmptyArray();
            }
            sort(arr);
            uint256 middleIndex = arr.length / 2;
            if (arr.length % 2 == 0) {
              uint256 sum = arr[middleIndex - 1] + arr[middleIndex];
              return sum / 2;
            } else {
              return arr[middleIndex];
            }
          }
          function sort(uint256[] memory arr) internal pure {
            assembly {
              let arrLength := mload(arr)
              let valuesPtr := add(arr, BYTES_ARR_LEN_VAR_BS)
              let endPtr := add(valuesPtr, mul(arrLength, UINT256_VALUE_BS))
              for {
                let arrIPtr := valuesPtr
              } lt(arrIPtr, endPtr) {
                arrIPtr := add(arrIPtr, UINT256_VALUE_BS) // arrIPtr += 32
              } {
                for {
                  let arrJPtr := valuesPtr
                } lt(arrJPtr, arrIPtr) {
                  arrJPtr := add(arrJPtr, UINT256_VALUE_BS) // arrJPtr += 32
                } {
                  let arrI := mload(arrIPtr)
                  let arrJ := mload(arrJPtr)
                  if lt(arrI, arrJ) {
                    mstore(arrIPtr, arrJ)
                    mstore(arrJPtr, arrI)
                  }
                }
              }
            }
          }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.4;
        library SignatureLib {
          uint256 constant ECDSA_SIG_R_BS = 32;
          uint256 constant ECDSA_SIG_S_BS = 32;
          function recoverSignerAddress(bytes32 signedHash, uint256 signatureCalldataNegativeOffset)
            internal
            pure
            returns (address)
          {
            bytes32 r;
            bytes32 s;
            uint8 v;
            assembly {
              let signatureCalldataStartPos := sub(calldatasize(), signatureCalldataNegativeOffset)
              r := calldataload(signatureCalldataStartPos)
              signatureCalldataStartPos := add(signatureCalldataStartPos, ECDSA_SIG_R_BS)
              s := calldataload(signatureCalldataStartPos)
              signatureCalldataStartPos := add(signatureCalldataStartPos, ECDSA_SIG_S_BS)
              v := byte(0, calldataload(signatureCalldataStartPos)) // last byte of the signature memory array
            }
            return ecrecover(signedHash, v, r, s);
          }
        }
        // SPDX-License-Identifier: BUSL-1.1
        pragma solidity ^0.8.14;
        /**
         * @title Interface of RedStone adapter
         * @author The Redstone Oracles team
         */
        interface IRedstoneAdapter {
          /**
           * @notice Updates values of all data feeds supported by the Adapter contract
           * @dev This function requires an attached redstone payload to the transaction calldata.
           * It also requires each data package to have exactly the same timestamp
           * @param dataPackagesTimestamp Timestamp of each signed data package in the redstone payload
           */
          function updateDataFeedsValues(uint256 dataPackagesTimestamp) external;
          /**
           * @notice Returns the latest properly reported value of the data feed
           * @param dataFeedId The identifier of the requested data feed
           * @return value The latest value of the given data feed
           */
          function getValueForDataFeed(bytes32 dataFeedId) external view returns (uint256);
          /**
           * @notice Returns the latest properly reported values for several data feeds
           * @param requestedDataFeedIds The array of identifiers for the requested feeds
           * @return values Values of the requested data feeds in the corresponding order
           */
          function getValuesForDataFeeds(bytes32[] memory requestedDataFeedIds) external view returns (uint256[] memory);
          /**
           * @notice Returns data timestamp from the latest update
           * @dev It's virtual, because its implementation can sometimes be different
           * (e.g. SinglePriceFeedAdapterWithClearing)
           * @return lastDataTimestamp Timestamp of the latest reported data packages
           */
          function getDataTimestampFromLatestUpdate() external view returns (uint256 lastDataTimestamp);
          /**
           * @notice Returns block timestamp of the latest successful update
           * @return blockTimestamp The block timestamp of the latest successful update
           */
          function getBlockTimestampFromLatestUpdate() external view returns (uint256 blockTimestamp);
          /**
           * @notice Returns timestamps of the latest successful update
           * @return dataTimestamp timestamp (usually in milliseconds) from the signed data packages
           * @return blockTimestamp timestamp of the block when the update has happened
           */
          function getTimestampsFromLatestUpdate() external view returns (uint128 dataTimestamp, uint128 blockTimestamp);
          /**
           * @notice Returns identifiers of all data feeds supported by the Adapter contract
           * @return An array of data feed identifiers
           */
          function getDataFeedIds() external view returns (bytes32[] memory);
          /**
           * @notice Returns the unique index of the given data feed
           * @param dataFeedId The data feed identifier
           * @return index The index of the data feed
           */
          function getDataFeedIndex(bytes32 dataFeedId) external view returns (uint256);
          /**
           * @notice Returns minimal required interval (usually in seconds) between subsequent updates
           * @return interval The required interval between updates
           */
          function getMinIntervalBetweenUpdates() external view returns (uint256);
          /**
           * @notice Reverts if the proposed timestamp of data packages it too old or too new
           * comparing to the block.timestamp. It also ensures that the proposed timestamp is newer
           * Then the one from the previous update
           * @param dataPackagesTimestamp The proposed timestamp (usually in milliseconds)
           */
          function validateProposedDataPackagesTimestamp(uint256 dataPackagesTimestamp) external view;
          /**
           * @notice Reverts if the updater is not authorised
           * @dev This function should revert if msg.sender is not allowed to update data feed values
           * @param updater The address of the proposed updater
           */
          function requireAuthorisedUpdater(address updater) external view;
        }
        // SPDX-License-Identifier: BUSL-1.1
        pragma solidity ^0.8.14;
        import {RedstoneConsumerNumericBase, RedstoneDefaultsLib} from "@redstone-finance/evm-connector/contracts/core/RedstoneConsumerNumericBase.sol";
        import {IRedstoneAdapter} from "./IRedstoneAdapter.sol";
        /**
         * @title Core logic of Redstone Adapter Contract
         * @author The Redstone Oracles team
         * @dev This contract is used to repeatedly push Redstone data to blockchain storage
         * More details here: https://docs.redstone.finance/docs/smart-contract-devs/get-started/redstone-classic
         *
         * Key details about the contract:
         * - Values for data feeds can be updated using the `updateDataFeedsValues` function
         * - All data feeds must be updated within a single call, partial updates are not allowed
         * - There is a configurable minimum interval between updates
         * - Updaters can be restricted by overriding `requireAuthorisedUpdater` function
         * - The contract is designed to force values validation, by default it prevents returning zero values
         * - All data packages in redstone payload must have the same timestamp,
         *    equal to `dataPackagesTimestamp` argument of the `updateDataFeedsValues` function
         * - Block timestamp abstraction - even though we call it blockTimestamp in many places,
         *    it's possible to have a custom logic here, e.g. use block number instead of a timestamp
         */
        abstract contract RedstoneAdapterBase is RedstoneConsumerNumericBase, IRedstoneAdapter {
          // We don't use storage variables to avoid potential problems with upgradable contracts
          bytes32 internal constant LATEST_UPDATE_TIMESTAMPS_STORAGE_LOCATION = 0x3d01e4d77237ea0f771f1786da4d4ff757fcba6a92933aa53b1dcef2d6bd6fe2; // keccak256("RedStone.lastUpdateTimestamp");
          uint256 internal constant MIN_INTERVAL_BETWEEN_UPDATES = 3 seconds;
          uint256 internal constant BITS_COUNT_IN_16_BYTES = 128;
          uint256 internal constant MAX_NUMBER_FOR_128_BITS = 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff;
          error DataTimestampShouldBeNewerThanBefore(
            uint256 receivedDataTimestampMilliseconds,
            uint256 lastDataTimestampMilliseconds
          );
          error MinIntervalBetweenUpdatesHasNotPassedYet(
            uint256 currentBlockTimestamp,
            uint256 lastUpdateTimestamp,
            uint256 minIntervalBetweenUpdates
          );
          error DataPackageTimestampMismatch(uint256 expectedDataTimestamp, uint256 dataPackageTimestamp);
          error DataFeedValueCannotBeZero(bytes32 dataFeedId);
          error DataFeedIdNotFound(bytes32 dataFeedId);
          error DataTimestampIsTooBig(uint256 dataTimestamp);
          error BlockTimestampIsTooBig(uint256 blockTimestamp);
          /**
           * @notice Reverts if the updater is not authorised
           * @dev This function should revert if msg.sender is not allowed to update data feed values
           * @param updater The address of the proposed updater
           */
          function requireAuthorisedUpdater(address updater) public view virtual {
            // By default, anyone can update data feed values, but it can be overridden
          }
          /**
           * @notice Returns identifiers of all data feeds supported by the Adapter contract
           * @dev this function must be implemented in derived contracts
           * @return An array of data feed identifiers
           */
          function getDataFeedIds() public view virtual returns (bytes32[] memory);
          /**
           * @notice Returns the unique index of the given data feed
           * @dev This function can (and should) be overriden to reduce gas
           * costs of other functions
           * @param dataFeedId The data feed identifier
           * @return index The index of the data feed
           */
          function getDataFeedIndex(bytes32 dataFeedId) public view virtual returns (uint256) {
            bytes32[] memory dataFeedIds = getDataFeedIds();
            for (uint256 i = 0; i < dataFeedIds.length;) {
              if (dataFeedIds[i] == dataFeedId) {
                return i;
              }
              unchecked { i++; } // reduces gas costs
            }
            revert DataFeedIdNotFound(dataFeedId);
          }
          /**
           * @notice Updates values of all data feeds supported by the Adapter contract
           * @dev This function requires an attached redstone payload to the transaction calldata.
           * It also requires each data package to have exactly the same timestamp
           * @param dataPackagesTimestamp Timestamp of each signed data package in the redstone payload
           */
          function updateDataFeedsValues(uint256 dataPackagesTimestamp) public virtual {
            requireAuthorisedUpdater(msg.sender);
            _assertMinIntervalBetweenUpdatesPassed();
            validateProposedDataPackagesTimestamp(dataPackagesTimestamp);
            _saveTimestampsOfCurrentUpdate(dataPackagesTimestamp);
            bytes32[] memory dataFeedsIdsArray = getDataFeedIds();
            // It will trigger timestamp validation for each data package
            uint256[] memory oracleValues = getOracleNumericValuesFromTxMsg(dataFeedsIdsArray);
            _validateAndUpdateDataFeedsValues(dataFeedsIdsArray, oracleValues);
          }
          /**
           * @dev Note! This function is not called directly, it's called for each data package    .
           * in redstone payload and just verifies if each data package has the same timestamp
           * as the one that was saved in the storage
           * @param receivedTimestampMilliseconds Timestamp from a data package
           */
          function validateTimestamp(uint256 receivedTimestampMilliseconds) public view virtual override {
            // It means that we are in the special view context and we can skip validation of the
            // timestamp. It can be useful for calling view functions, as they can not modify the contract
            // state to pass the timestamp validation below
            if (msg.sender == address(0)) {
              return;
            }
            uint256 expectedDataPackageTimestamp = getDataTimestampFromLatestUpdate();
            if (receivedTimestampMilliseconds != expectedDataPackageTimestamp) {
              revert DataPackageTimestampMismatch(
                expectedDataPackageTimestamp,
                receivedTimestampMilliseconds
              );
            }
          }
          /**
           * @dev This function should be implemented by the actual contract
           * and should contain the logic of values validation and reporting.
           * Usually, values reporting is based on saving them to the contract storage,
           * e.g. in PriceFeedsAdapter, but some custom implementations (e.g. GMX keeper adapter
           * or Mento Sorted Oracles adapter) may handle values updating in a different way
           * @param dataFeedIdsArray Array of the data feeds identifiers (it will always be all data feed ids)
           * @param values The reported values that should be validated and reported
           */
          function _validateAndUpdateDataFeedsValues(bytes32[] memory dataFeedIdsArray, uint256[] memory values) internal virtual;
          /**
           * @dev This function reverts if not enough time passed since the latest update
           */
          function _assertMinIntervalBetweenUpdatesPassed() private view {
            uint256 currentBlockTimestamp = getBlockTimestamp();
            uint256 blockTimestampFromLatestUpdate = getBlockTimestampFromLatestUpdate();
            uint256 minIntervalBetweenUpdates = getMinIntervalBetweenUpdates();
            if (currentBlockTimestamp < blockTimestampFromLatestUpdate + minIntervalBetweenUpdates) {
              revert MinIntervalBetweenUpdatesHasNotPassedYet(
                currentBlockTimestamp,
                blockTimestampFromLatestUpdate,
                minIntervalBetweenUpdates
              );
            }
          }
          /**
           * @notice Returns minimal required interval (usually in seconds) between subsequent updates
           * @dev You can override this function to change the required interval between udpates.
           * Please do not set it to 0, as it may open many attack vectors
           * @return interval The required interval between updates
           */
          function getMinIntervalBetweenUpdates() public view virtual returns (uint256) {
            return MIN_INTERVAL_BETWEEN_UPDATES;
          }
          /**
           * @notice Reverts if the proposed timestamp of data packages it too old or too new
           * comparing to the block.timestamp. It also ensures that the proposed timestamp is newer
           * Then the one from the previous update
           * @param dataPackagesTimestamp The proposed timestamp (usually in milliseconds)
           */
          function validateProposedDataPackagesTimestamp(uint256 dataPackagesTimestamp) public view {
            _preventUpdateWithOlderDataPackages(dataPackagesTimestamp);
            validateDataPackagesTimestampOnce(dataPackagesTimestamp);
          }
          /**
           * @notice Reverts if the proposed timestamp of data packages it too old or too new
           * comparing to the current block timestamp
           * @param dataPackagesTimestamp The proposed timestamp (usually in milliseconds)
           */
          function validateDataPackagesTimestampOnce(uint256 dataPackagesTimestamp) public view virtual {
            uint256 receivedTimestampSeconds = dataPackagesTimestamp / 1000;
            (uint256 maxDataAheadSeconds, uint256 maxDataDelaySeconds) = getAllowedTimestampDiffsInSeconds();
            uint256 blockTimestamp = getBlockTimestamp();
            if (blockTimestamp < receivedTimestampSeconds) {
              if ((receivedTimestampSeconds - blockTimestamp) > maxDataAheadSeconds) {
                revert RedstoneDefaultsLib.TimestampFromTooLongFuture(receivedTimestampSeconds, blockTimestamp);
              }
            } else if ((blockTimestamp - receivedTimestampSeconds) > maxDataDelaySeconds) {
              revert RedstoneDefaultsLib.TimestampIsTooOld(receivedTimestampSeconds, blockTimestamp);
            }
          }
          /**
           * @dev This function can be overriden, e.g. to use block.number instead of block.timestamp
           * It can be useful in some L2 chains, as sometimes their different blocks can have the same timestamp
           * @return timestamp Timestamp or Block number or any other number that can identify time in the context
           * of the given blockchain
           */
          function getBlockTimestamp() public view virtual returns (uint256) {
            return block.timestamp;
          }
          /**
           * @dev Helpful function for getting values for timestamp validation
           * @return  maxDataAheadSeconds Max allowed number of seconds ahead of block.timrstamp
           * @return  maxDataDelaySeconds Max allowed number of seconds for data delay
           */
          function getAllowedTimestampDiffsInSeconds() public view virtual returns (uint256 maxDataAheadSeconds, uint256 maxDataDelaySeconds) {
            maxDataAheadSeconds = RedstoneDefaultsLib.DEFAULT_MAX_DATA_TIMESTAMP_AHEAD_SECONDS;
            maxDataDelaySeconds = RedstoneDefaultsLib.DEFAULT_MAX_DATA_TIMESTAMP_DELAY_SECONDS;
          }
          /**
           * @dev Reverts if proposed data packages are not newer than the ones used previously
           * @param dataPackagesTimestamp Timestamp od the data packages (usually in milliseconds)
           */
          function _preventUpdateWithOlderDataPackages(uint256 dataPackagesTimestamp) internal view {
            uint256 dataTimestampFromLatestUpdate = getDataTimestampFromLatestUpdate();
            if (dataPackagesTimestamp <= dataTimestampFromLatestUpdate) {
              revert DataTimestampShouldBeNewerThanBefore(
                dataPackagesTimestamp,
                dataTimestampFromLatestUpdate
              );
            }
          }
          /**
           * @notice Returns data timestamp from the latest update
           * @dev It's virtual, because its implementation can sometimes be different
           * (e.g. SinglePriceFeedAdapterWithClearing)
           * @return lastDataTimestamp Timestamp of the latest reported data packages
           */
          function getDataTimestampFromLatestUpdate() public view virtual returns (uint256 lastDataTimestamp) {
            (lastDataTimestamp, ) = getTimestampsFromLatestUpdate();
          }
          /**
           * @notice Returns block timestamp of the latest successful update
           * @return blockTimestamp The block timestamp of the latest successful update
           */
          function getBlockTimestampFromLatestUpdate() public view returns (uint256 blockTimestamp) {
            (, blockTimestamp) = getTimestampsFromLatestUpdate();
          }
          /**
           * @dev Returns 2 timestamps packed into a single uint256 number
           * @return packedTimestamps a single uin256 number with 2 timestamps
           */
          function getPackedTimestampsFromLatestUpdate() public view returns (uint256 packedTimestamps) {
            assembly {
              packedTimestamps := sload(LATEST_UPDATE_TIMESTAMPS_STORAGE_LOCATION)
            }
          }
          /**
           * @notice Returns timestamps of the latest successful update
           * @return dataTimestamp timestamp (usually in milliseconds) from the signed data packages
           * @return blockTimestamp timestamp of the block when the update has happened
           */
          function getTimestampsFromLatestUpdate() public view virtual returns (uint128 dataTimestamp, uint128 blockTimestamp) {
            return _unpackTimestamps(getPackedTimestampsFromLatestUpdate());
          }
          /**
           * @dev A helpful function to unpack 2 timestamps from one uin256 number
           * @param packedTimestamps a single uin256 number
           * @return dataTimestamp fetched from left 128 bits
           * @return blockTimestamp fetched from right 128 bits
           */
          function _unpackTimestamps(uint256 packedTimestamps) internal pure returns (uint128 dataTimestamp, uint128 blockTimestamp) {
            dataTimestamp = uint128(packedTimestamps >> 128); // left 128 bits
            blockTimestamp = uint128(packedTimestamps); // right 128 bits
          }
          /**
           * @dev Logic of saving timestamps of the current update
           * By default, it stores packed timestamps in one storage slot (32 bytes)
           * to minimise gas costs
           * But it can be overriden (e.g. in SinglePriceFeedAdapter)
           * @param   dataPackagesTimestamp  .
           */
          function _saveTimestampsOfCurrentUpdate(uint256 dataPackagesTimestamp) internal virtual {
            uint256 blockTimestamp = getBlockTimestamp();
            if (blockTimestamp > MAX_NUMBER_FOR_128_BITS) {
              revert BlockTimestampIsTooBig(blockTimestamp);
            }
            if (dataPackagesTimestamp > MAX_NUMBER_FOR_128_BITS) {
              revert DataTimestampIsTooBig(dataPackagesTimestamp);
            }
            assembly {
              let timestamps := or(shl(BITS_COUNT_IN_16_BYTES, dataPackagesTimestamp), blockTimestamp)
              sstore(LATEST_UPDATE_TIMESTAMPS_STORAGE_LOCATION, timestamps)
            }
          }
          /**
           * @notice Returns the latest properly reported value of the data feed
           * @param dataFeedId The identifier of the requested data feed
           * @return value The latest value of the given data feed
           */
          function getValueForDataFeed(bytes32 dataFeedId) public view returns (uint256) {
            getDataFeedIndex(dataFeedId); // will revert if data feed id is not supported
            // "unsafe" here means "without validation"
            uint256 valueForDataFeed = getValueForDataFeedUnsafe(dataFeedId);
            validateDataFeedValueOnRead(dataFeedId, valueForDataFeed);
            return valueForDataFeed;
          }
          /**
           * @notice Returns the latest properly reported values for several data feeds
           * @param dataFeedIds The array of identifiers for the requested feeds
           * @return values Values of the requested data feeds in the corresponding order
           */
          function getValuesForDataFeeds(bytes32[] memory dataFeedIds) public view returns (uint256[] memory) {
            uint256[] memory values = getValuesForDataFeedsUnsafe(dataFeedIds);
            for (uint256 i = 0; i < dataFeedIds.length;) {
              bytes32 dataFeedId = dataFeedIds[i];
              getDataFeedIndex(dataFeedId); // will revert if data feed id is not supported
              validateDataFeedValueOnRead(dataFeedId, values[i]);
              unchecked { i++; } // reduces gas costs
            }
            return values;
          }
          /**
           * @dev Reverts if proposed value for the proposed data feed id is invalid
           * Is called on every NOT *unsafe method which reads dataFeed
           * By default, it just checks if the value is not equal to 0, but it can be extended
           * @param dataFeedId The data feed identifier
           * @param valueForDataFeed Proposed value for the data feed
           */
          function validateDataFeedValueOnRead(bytes32 dataFeedId, uint256 valueForDataFeed) public view virtual {
            if (valueForDataFeed == 0) {
              revert DataFeedValueCannotBeZero(dataFeedId);
            }
          }
          /**
           * @dev Reverts if proposed value for the proposed data feed id is invalid
           * Is called on every NOT *unsafe method which writes dataFeed
           * By default, it does nothing
           * @param dataFeedId The data feed identifier
           * @param valueForDataFeed Proposed value for the data feed
           */
          function validateDataFeedValueOnWrite(bytes32 dataFeedId, uint256 valueForDataFeed) public view virtual {
            if (valueForDataFeed == 0) {
              revert DataFeedValueCannotBeZero(dataFeedId);
            }
          }
          /**
           * @dev [HIGH RISK] Returns the latest value for a given data feed without validation
           * Important! Using this function instead of `getValueForDataFeed` may cause
           * significant risk for your smart contracts
           * @param dataFeedId The data feed identifier
           * @return dataFeedValue Unvalidated value of the latest successful update
           */
          function getValueForDataFeedUnsafe(bytes32 dataFeedId) public view virtual returns (uint256);
          /**
           * @notice [HIGH RISK] Returns the latest properly reported values for several data feeds without validation
           * Important! Using this function instead of `getValuesForDataFeeds` may cause
           * significant risk for your smart contracts
           * @param requestedDataFeedIds The array of identifiers for the requested feeds
           * @return values Unvalidated values of the requested data feeds in the corresponding order
           */
          function getValuesForDataFeedsUnsafe(bytes32[] memory requestedDataFeedIds) public view virtual returns (uint256[] memory values) {
            values = new uint256[](requestedDataFeedIds.length);
            for (uint256 i = 0; i < requestedDataFeedIds.length;) {
              values[i] = getValueForDataFeedUnsafe(requestedDataFeedIds[i]);
              unchecked { i++; } // reduces gas costs
            }
            return values;
          }
        }
        // SPDX-License-Identifier: BUSL-1.1
        pragma solidity ^0.8.14;
        import {PriceFeedsAdapterWithoutRounds} from "../without-rounds/PriceFeedsAdapterWithoutRounds.sol";
        abstract contract PriceFeedsAdapterWithoutRoundsPrimaryProd is PriceFeedsAdapterWithoutRounds {
          function getUniqueSignersThreshold() public view virtual override returns (uint8) {
            return 2;
          }
          function getAuthorisedSignerIndex(
            address signerAddress
          ) public view virtual override returns (uint8) {
            if (signerAddress == 0x8BB8F32Df04c8b654987DAaeD53D6B6091e3B774) { return 0; }
            else if (signerAddress == 0xdEB22f54738d54976C4c0fe5ce6d408E40d88499) { return 1; }
            else if (signerAddress == 0x51Ce04Be4b3E32572C4Ec9135221d0691Ba7d202) { return 2; }
            else if (signerAddress == 0xDD682daEC5A90dD295d14DA4b0bec9281017b5bE) { return 3; }
            else if (signerAddress == 0x9c5AE89C4Af6aA32cE58588DBaF90d18a855B6de) { return 4; }
            else {
              revert SignerNotAuthorised(signerAddress);
            }
          }
        }
        // SPDX-License-Identifier: BUSL-1.1
        pragma solidity ^0.8.14;
        import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
        import {RedstoneAdapterBase} from "../core/RedstoneAdapterBase.sol";
        /**
         * @title Common logic of the price feeds adapter contracts
         * @author The Redstone Oracles team
         */
        abstract contract PriceFeedsAdapterBase is RedstoneAdapterBase, Initializable {
          /**
           * @dev Helpful function for upgradable contracts
           */
          function initialize() public virtual initializer {
            // We don't have storage variables, but we keep this function
            // Because it is used for contract setup in upgradable contracts
          }
          /**
           * @dev This function is virtual and may contain additional logic in the derived contract
           * E.g. it can check if the updating conditions are met (e.g. if at least one
           * value is deviated enough)
           * @param dataFeedIdsArray Array of all data feeds identifiers
           * @param values The reported values that are validated and reported
           */
          function _validateAndUpdateDataFeedsValues(
            bytes32[] memory dataFeedIdsArray,
            uint256[] memory values
          ) internal virtual override {
            for (uint256 i = 0; i < dataFeedIdsArray.length;) {
              _validateAndUpdateDataFeedValue(dataFeedIdsArray[i], values[i]);
              unchecked { i++; } // reduces gas costs
            }
          }
          /**
           * @dev Helpful virtual function for handling value validation and saving in derived
           * Price Feed Adapters contracts 
           * @param dataFeedId The data feed identifier
           * @param dataFeedValue Proposed value for the data feed
           */
          function _validateAndUpdateDataFeedValue(bytes32 dataFeedId, uint256 dataFeedValue) internal virtual;
        }
        // SPDX-License-Identifier: BUSL-1.1
        pragma solidity ^0.8.14;
        import {PriceFeedsAdapterBase} from "../PriceFeedsAdapterBase.sol";
        /**
         * @title Implementation of a price feeds adapter without rounds support
         * @author The Redstone Oracles team
         * @dev This contract is abstract, the following functions should be
         * implemented in the actual contract before deployment:
         * - getDataFeedIds
         * - getUniqueSignersThreshold
         * - getAuthorisedSignerIndex
         * 
         * We also recommend to override `getDataFeedIndex` function with hardcoded
         * values, as it can significantly reduce gas usage
         */
        abstract contract PriceFeedsAdapterWithoutRounds is PriceFeedsAdapterBase {
          bytes32 constant VALUES_MAPPING_STORAGE_LOCATION = 0x4dd0c77efa6f6d590c97573d8c70b714546e7311202ff7c11c484cc841d91bfc; // keccak256("RedStone.oracleValuesMapping");
          /**
           * @dev Helpful virtual function for handling value validation and saving
           * @param dataFeedId The data feed identifier
           * @param dataFeedValue Proposed value for the data feed
           */
          function _validateAndUpdateDataFeedValue(bytes32 dataFeedId, uint256 dataFeedValue) internal override virtual {
            validateDataFeedValueOnWrite(dataFeedId, dataFeedValue);
            bytes32 locationInStorage = _getValueLocationInStorage(dataFeedId);
            assembly {
              sstore(locationInStorage, dataFeedValue)
            }
          }
          /**
           * @dev [HIGH RISK] Returns the latest value for a given data feed without validation
           * Important! Using this function instead of `getValueForDataFeed` may cause
           * significant risk for your smart contracts
           * @param dataFeedId The data feed identifier
           * @return dataFeedValue Unvalidated value of the latest successful update
           */
          function getValueForDataFeedUnsafe(bytes32 dataFeedId) public view  virtual override returns (uint256 dataFeedValue) {
            bytes32 locationInStorage = _getValueLocationInStorage(dataFeedId);
            assembly {
              dataFeedValue := sload(locationInStorage)
            }
          }
          /**
           * @dev Helpful function for getting storage location for the requested data feed
           * @param dataFeedId Requested data feed identifier
           * @return locationInStorage
           */
          function _getValueLocationInStorage(bytes32 dataFeedId) private pure returns (bytes32) {
            return keccak256(abi.encode(dataFeedId, VALUES_MAPPING_STORAGE_LOCATION));
          }
        }
        // SPDX-License-Identifier: BUSL-1.1
        pragma solidity ^0.8.4;
        library OldGelatoAddress {
          address constant public ADDR = 0xc4D1AE5E796E6d7561cdc8335F85e6B57a36e097;
        }
        library GelatoAddress {
          address constant public ADDR = 0xCD6BfDA4D95d5C0f3f2882dC221D792392c99714;
        }
        // SPDX-License-Identifier: BUSL-1.1
        pragma solidity ^0.8.4;
        import {PriceFeedsAdapterWithoutRoundsPrimaryProd} from "@redstone-finance/on-chain-relayer/contracts/price-feeds/data-services/PriceFeedsAdapterWithoutRoundsPrimaryProd.sol";
        import {OldGelatoAddress, GelatoAddress} from "../__addresses/Addresses.sol";
        import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
        interface IValidatorTicketPricer {
            function setDailyRewardsAndPostMintPrice(uint104 dailyMevPayouts, uint104 dailyConsensusRewards) external;
            function setAuthority(address) external;
            function setDailyMevPayoutsChangeToleranceBps(uint16 newValue) external;
            function authority() external view returns (address);
            function getDailyMevPayouts() external view returns (uint104);
            function getDailyConsensusRewards() external view returns (uint104);
        }
        contract MergedAdapterWithoutRoundsPufStakingV1 is
            PriceFeedsAdapterWithoutRoundsPrimaryProd
        {
            IValidatorTicketPricer constant validatorTickerPricer = IValidatorTicketPricer(0x9830aD1bD5Cf73640e253EdF97DeE3791C4a53C3);
            bytes32 constant ETH_CLE = bytes32("ETH_CLE");
            bytes32 constant ETH_ELE = bytes32("ETH_ELE");
            address internal constant MAIN_UPDATER_ADDRESS =
                0x604dba5DBA0Dd58997DCF9B5Ae5D066C8E14a3C0;
            address internal constant FALLBACK_UPDATER_ADDRESS =
                0x835f501Ebf7c8187872ebdE16ACE572c4DdF6a5A;
            address internal constant MANUAL_UPDATER_ADDRESS =
                0x6b2b4B3AD68f30873446F3779f8fe64d4A1318F3;
            error UpdaterNotAuthorised(address signer);
            function getDataFeedIds() public pure virtual override returns (bytes32[] memory) {
                bytes32[] memory dataFeedIds = new bytes32[](2);
                dataFeedIds[0] = ETH_CLE;
                dataFeedIds[1] = ETH_ELE;
                return dataFeedIds;
            }
            function requireAuthorisedUpdater(
                address updater
            ) public view virtual override {
                if (
                    updater != MAIN_UPDATER_ADDRESS &&
                    updater != FALLBACK_UPDATER_ADDRESS &&
                    updater != MANUAL_UPDATER_ADDRESS &&
                    updater != GelatoAddress.ADDR &&
                    updater != OldGelatoAddress.ADDR
                ) {
                    // We allow anyone to publish the new price if 40 seconds have passed since the latest update
                    uint256 lastUpdateBlockTimestamp = getBlockTimestampFromLatestUpdate();
                    if (getBlockTimestamp() - lastUpdateBlockTimestamp < 40 seconds) {
                        revert UpdaterNotAuthorised(updater);
                    }
                }
            }
            function _validateAndUpdateDataFeedsValues(bytes32[] memory dataFeedIdsArray, uint256[] memory values) override internal virtual {
                uint104 ele;
                uint104 cle;
                
                for (uint256 i = 0; i < dataFeedIdsArray.length;) {
                    _validateAndUpdateDataFeedValue(dataFeedIdsArray[i], values[i]);
                    if (dataFeedIdsArray[i] == ETH_CLE) {
                        cle = SafeCast.toUint104(values[i] * 1e10);
                    }
                    if (dataFeedIdsArray[i] == ETH_ELE) {
                        ele = SafeCast.toUint104(values[i] * 1e10);
                    }
                    unchecked { i++; } // reduces gas costs
                }      
                validatorTickerPricer.setDailyRewardsAndPostMintPrice(ele,cle);
            }
        }
        

        File 3 of 4: ValidatorTicketPricer
        // SPDX-License-Identifier: GPL-3.0
        pragma solidity <0.9.0 >=0.8.0 ^0.8.20;
        
        // node_modules/@openzeppelin/contracts/access/manager/IAccessManaged.sol
        
        // OpenZeppelin Contracts (last updated v5.0.0) (access/manager/IAccessManaged.sol)
        
        interface IAccessManaged {
            /**
             * @dev Authority that manages this contract was updated.
             */
            event AuthorityUpdated(address authority);
        
            error AccessManagedUnauthorized(address caller);
            error AccessManagedRequiredDelay(address caller, uint32 delay);
            error AccessManagedInvalidAuthority(address authority);
        
            /**
             * @dev Returns the current authority.
             */
            function authority() external view returns (address);
        
            /**
             * @dev Transfers control to a new authority. The caller must be the current authority.
             */
            function setAuthority(address) external;
        
            /**
             * @dev Returns true only in the context of a delayed restricted call, at the moment that the scheduled operation is
             * being consumed. Prevents denial of service for delayed restricted calls in the case that the contract performs
             * attacker controlled calls.
             */
            function isConsumingScheduledOp() external view returns (bytes4);
        }
        
        // node_modules/@openzeppelin/contracts/access/manager/IAuthority.sol
        
        // OpenZeppelin Contracts (last updated v5.0.0) (access/manager/IAuthority.sol)
        
        /**
         * @dev Standard interface for permissioning originally defined in Dappsys.
         */
        interface IAuthority {
            /**
             * @dev Returns true if the caller can invoke on a target the function identified by a function selector.
             */
            function canCall(address caller, address target, bytes4 selector) external view returns (bool allowed);
        }
        
        // node_modules/@openzeppelin/contracts/utils/Base64.sol
        
        // OpenZeppelin Contracts (last updated v5.0.0) (utils/Base64.sol)
        
        pragma solidity ^0.8.20;
        
        /**
         * @dev Provides a set of functions to operate with Base64 strings.
         */
        library Base64 {
            /**
             * @dev Base64 Encoding/Decoding Table
             */
            string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        
            /**
             * @dev Converts a `bytes` to its Bytes64 `string` representation.
             */
            function encode(bytes memory data) internal pure returns (string memory) {
                /**
                 * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence
                 * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol
                 */
                if (data.length == 0) return "";
        
                // Loads the table into memory
                string memory table = _TABLE;
        
                // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter
                // and split into 4 numbers of 6 bits.
                // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up
                // - `data.length + 2`  -> Round up
                // - `/ 3`              -> Number of 3-bytes chunks
                // - `4 *`              -> 4 characters for each chunk
                string memory result = new string(4 * ((data.length + 2) / 3));
        
                /// @solidity memory-safe-assembly
                assembly {
                    // Prepare the lookup table (skip the first "length" byte)
                    let tablePtr := add(table, 1)
        
                    // Prepare result pointer, jump over length
                    let resultPtr := add(result, 32)
        
                    // Run over the input, 3 bytes at a time
                    for {
                        let dataPtr := data
                        let endPtr := add(data, mload(data))
                    } lt(dataPtr, endPtr) {
        
                    } {
                        // Advance 3 bytes
                        dataPtr := add(dataPtr, 3)
                        let input := mload(dataPtr)
        
                        // To write each character, shift the 3 bytes (18 bits) chunk
                        // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)
                        // and apply logical AND with 0x3F which is the number of
                        // the previous character in the ASCII table prior to the Base64 Table
                        // The result is then added to the table to get the character to write,
                        // and finally write it in the result pointer but with a left shift
                        // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits
        
                        mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
                        resultPtr := add(resultPtr, 1) // Advance
        
                        mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
                        resultPtr := add(resultPtr, 1) // Advance
        
                        mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
                        resultPtr := add(resultPtr, 1) // Advance
        
                        mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
                        resultPtr := add(resultPtr, 1) // Advance
                    }
        
                    // When data `bytes` is not exactly 3 bytes long
                    // it is padded with `=` characters at the end
                    switch mod(mload(data), 3)
                    case 1 {
                        mstore8(sub(resultPtr, 1), 0x3d)
                        mstore8(sub(resultPtr, 2), 0x3d)
                    }
                    case 2 {
                        mstore8(sub(resultPtr, 1), 0x3d)
                    }
                }
        
                return result;
            }
        }
        
        // node_modules/@openzeppelin/contracts/utils/Context.sol
        
        // OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.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 Context {
            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;
            }
        }
        
        // node_modules/@openzeppelin/contracts/utils/math/Math.sol
        
        // OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
        
        /**
         * @dev Standard math utilities missing in the Solidity language.
         */
        library Math {
            /**
             * @dev Muldiv operation overflow.
             */
            error MathOverflowedMulDiv();
        
            enum Rounding {
                Floor, // Toward negative infinity
                Ceil, // Toward positive infinity
                Trunc, // Toward zero
                Expand // Away from zero
            }
        
            /**
             * @dev Returns the addition of two unsigned integers, with an overflow flag.
             */
            function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                unchecked {
                    uint256 c = a + b;
                    if (c < a) return (false, 0);
                    return (true, c);
                }
            }
        
            /**
             * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
             */
            function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                unchecked {
                    if (b > a) return (false, 0);
                    return (true, a - b);
                }
            }
        
            /**
             * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
             */
            function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                unchecked {
                    // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                    // benefit is lost if 'b' is also tested.
                    // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                    if (a == 0) return (true, 0);
                    uint256 c = a * b;
                    if (c / a != b) return (false, 0);
                    return (true, c);
                }
            }
        
            /**
             * @dev Returns the division of two unsigned integers, with a division by zero flag.
             */
            function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                unchecked {
                    if (b == 0) return (false, 0);
                    return (true, a / b);
                }
            }
        
            /**
             * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
             */
            function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                unchecked {
                    if (b == 0) return (false, 0);
                    return (true, a % b);
                }
            }
        
            /**
             * @dev Returns the largest of two numbers.
             */
            function max(uint256 a, uint256 b) internal pure returns (uint256) {
                return a > b ? a : b;
            }
        
            /**
             * @dev Returns the smallest of two numbers.
             */
            function min(uint256 a, uint256 b) internal pure returns (uint256) {
                return a < b ? a : b;
            }
        
            /**
             * @dev Returns the average of two numbers. The result is rounded towards
             * zero.
             */
            function average(uint256 a, uint256 b) internal pure returns (uint256) {
                // (a + b) / 2 can overflow.
                return (a & b) + (a ^ b) / 2;
            }
        
            /**
             * @dev Returns the ceiling of the division of two numbers.
             *
             * This differs from standard division with `/` in that it rounds towards infinity instead
             * of rounding towards zero.
             */
            function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
                if (b == 0) {
                    // Guarantee the same behavior as in a regular Solidity division.
                    return a / b;
                }
        
                // (a + b - 1) / b can overflow on addition, so we distribute.
                return a == 0 ? 0 : (a - 1) / b + 1;
            }
        
            /**
             * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
             * denominator == 0.
             * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
             * Uniswap Labs also under MIT license.
             */
            function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
                unchecked {
                    // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                    // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                    // variables such that product = prod1 * 2^256 + prod0.
                    uint256 prod0 = x * y; // Least significant 256 bits of the product
                    uint256 prod1; // Most significant 256 bits of the product
                    assembly {
                        let mm := mulmod(x, y, not(0))
                        prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                    }
        
                    // Handle non-overflow cases, 256 by 256 division.
                    if (prod1 == 0) {
                        // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                        // The surrounding unchecked block does not change this fact.
                        // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                        return prod0 / denominator;
                    }
        
                    // Make sure the result is less than 2^256. Also prevents denominator == 0.
                    if (denominator <= prod1) {
                        revert MathOverflowedMulDiv();
                    }
        
                    ///////////////////////////////////////////////
                    // 512 by 256 division.
                    ///////////////////////////////////////////////
        
                    // Make division exact by subtracting the remainder from [prod1 prod0].
                    uint256 remainder;
                    assembly {
                        // Compute remainder using mulmod.
                        remainder := mulmod(x, y, denominator)
        
                        // Subtract 256 bit number from 512 bit number.
                        prod1 := sub(prod1, gt(remainder, prod0))
                        prod0 := sub(prod0, remainder)
                    }
        
                    // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
                    // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
        
                    uint256 twos = denominator & (0 - denominator);
                    assembly {
                        // Divide denominator by twos.
                        denominator := div(denominator, twos)
        
                        // Divide [prod1 prod0] by twos.
                        prod0 := div(prod0, twos)
        
                        // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                        twos := add(div(sub(0, twos), twos), 1)
                    }
        
                    // Shift in bits from prod1 into prod0.
                    prod0 |= prod1 * twos;
        
                    // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                    // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                    // four bits. That is, denominator * inv = 1 mod 2^4.
                    uint256 inverse = (3 * denominator) ^ 2;
        
                    // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
                    // works in modular arithmetic, doubling the correct bits in each step.
                    inverse *= 2 - denominator * inverse; // inverse mod 2^8
                    inverse *= 2 - denominator * inverse; // inverse mod 2^16
                    inverse *= 2 - denominator * inverse; // inverse mod 2^32
                    inverse *= 2 - denominator * inverse; // inverse mod 2^64
                    inverse *= 2 - denominator * inverse; // inverse mod 2^128
                    inverse *= 2 - denominator * inverse; // inverse mod 2^256
        
                    // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                    // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                    // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                    // is no longer required.
                    result = prod0 * inverse;
                    return result;
                }
            }
        
            /**
             * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
             */
            function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
                uint256 result = mulDiv(x, y, denominator);
                if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
                    result += 1;
                }
                return result;
            }
        
            /**
             * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
             * towards zero.
             *
             * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
             */
            function sqrt(uint256 a) internal pure returns (uint256) {
                if (a == 0) {
                    return 0;
                }
        
                // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
                //
                // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
                // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
                //
                // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
                // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
                // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
                //
                // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
                uint256 result = 1 << (log2(a) >> 1);
        
                // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
                // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
                // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
                // into the expected uint128 result.
                unchecked {
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    return min(result, a / result);
                }
            }
        
            /**
             * @notice Calculates sqrt(a), following the selected rounding direction.
             */
            function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
                unchecked {
                    uint256 result = sqrt(a);
                    return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
                }
            }
        
            /**
             * @dev Return the log in base 2 of a positive value rounded towards zero.
             * Returns 0 if given 0.
             */
            function log2(uint256 value) internal pure returns (uint256) {
                uint256 result = 0;
                unchecked {
                    if (value >> 128 > 0) {
                        value >>= 128;
                        result += 128;
                    }
                    if (value >> 64 > 0) {
                        value >>= 64;
                        result += 64;
                    }
                    if (value >> 32 > 0) {
                        value >>= 32;
                        result += 32;
                    }
                    if (value >> 16 > 0) {
                        value >>= 16;
                        result += 16;
                    }
                    if (value >> 8 > 0) {
                        value >>= 8;
                        result += 8;
                    }
                    if (value >> 4 > 0) {
                        value >>= 4;
                        result += 4;
                    }
                    if (value >> 2 > 0) {
                        value >>= 2;
                        result += 2;
                    }
                    if (value >> 1 > 0) {
                        result += 1;
                    }
                }
                return result;
            }
        
            /**
             * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
             * Returns 0 if given 0.
             */
            function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
                unchecked {
                    uint256 result = log2(value);
                    return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
                }
            }
        
            /**
             * @dev Return the log in base 10 of a positive value rounded towards zero.
             * Returns 0 if given 0.
             */
            function log10(uint256 value) internal pure returns (uint256) {
                uint256 result = 0;
                unchecked {
                    if (value >= 10 ** 64) {
                        value /= 10 ** 64;
                        result += 64;
                    }
                    if (value >= 10 ** 32) {
                        value /= 10 ** 32;
                        result += 32;
                    }
                    if (value >= 10 ** 16) {
                        value /= 10 ** 16;
                        result += 16;
                    }
                    if (value >= 10 ** 8) {
                        value /= 10 ** 8;
                        result += 8;
                    }
                    if (value >= 10 ** 4) {
                        value /= 10 ** 4;
                        result += 4;
                    }
                    if (value >= 10 ** 2) {
                        value /= 10 ** 2;
                        result += 2;
                    }
                    if (value >= 10 ** 1) {
                        result += 1;
                    }
                }
                return result;
            }
        
            /**
             * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
             * Returns 0 if given 0.
             */
            function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
                unchecked {
                    uint256 result = log10(value);
                    return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
                }
            }
        
            /**
             * @dev Return the log in base 256 of a positive value rounded towards zero.
             * Returns 0 if given 0.
             *
             * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
             */
            function log256(uint256 value) internal pure returns (uint256) {
                uint256 result = 0;
                unchecked {
                    if (value >> 128 > 0) {
                        value >>= 128;
                        result += 16;
                    }
                    if (value >> 64 > 0) {
                        value >>= 64;
                        result += 8;
                    }
                    if (value >> 32 > 0) {
                        value >>= 32;
                        result += 4;
                    }
                    if (value >> 16 > 0) {
                        value >>= 16;
                        result += 2;
                    }
                    if (value >> 8 > 0) {
                        result += 1;
                    }
                }
                return result;
            }
        
            /**
             * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
             * Returns 0 if given 0.
             */
            function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
                unchecked {
                    uint256 result = log256(value);
                    return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
                }
            }
        
            /**
             * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
             */
            function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
                return uint8(rounding) % 2 == 1;
            }
        }
        
        // node_modules/@openzeppelin/contracts/utils/math/SafeCast.sol
        
        // OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SafeCast.sol)
        // This file was procedurally generated from scripts/generate/templates/SafeCast.js.
        
        /**
         * @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);
            }
        }
        
        // node_modules/rave/src/BytesUtils.sol
        
        // Copied from https://github.com/ensdomains/ens-contracts/blob/f5f2ededccbb7e52be44925c0050620d71762e32/contracts/dnssec-oracle/BytesUtils.sol
        library BytesUtils {
            error OffsetOutOfBoundsError(uint256 offset, uint256 length);
        
            /*
             * @dev Returns the keccak-256 hash of a byte range.
             * @param self The byte string to hash.
             * @param offset The position to start hashing at.
             * @param len The number of bytes to hash.
             * @return The hash of the byte range.
             */
            function keccak(bytes memory self, uint256 offset, uint256 len) internal pure returns (bytes32 ret) {
                require(offset + len <= self.length);
                assembly {
                    ret := keccak256(add(add(self, 32), offset), len)
                }
            }
        
            /*
             * @dev Returns a positive number if `other` comes lexicographically after
             *      `self`, a negative number if it comes before, or zero if the
             *      contents of the two bytes are equal.
             * @param self The first bytes to compare.
             * @param other The second bytes to compare.
             * @return The result of the comparison.
             */
            function compare(bytes memory self, bytes memory other) internal pure returns (int256) {
                return compare(self, 0, self.length, other, 0, other.length);
            }
        
            /*
             * @dev Returns a positive number if `other` comes lexicographically after
             *      `self`, a negative number if it comes before, or zero if the
             *      contents of the two bytes are equal. Comparison is done per-rune,
             *      on unicode codepoints.
             * @param self The first bytes to compare.
             * @param offset The offset of self.
             * @param len    The length of self.
             * @param other The second bytes to compare.
             * @param otheroffset The offset of the other string.
             * @param otherlen    The length of the other string.
             * @return The result of the comparison.
             */
            function compare(
                bytes memory self,
                uint256 offset,
                uint256 len,
                bytes memory other,
                uint256 otheroffset,
                uint256 otherlen
            ) internal pure returns (int256) {
                if (offset + len > self.length) {
                    revert OffsetOutOfBoundsError(offset + len, self.length);
                }
                if (otheroffset + otherlen > other.length) {
                    revert OffsetOutOfBoundsError(otheroffset + otherlen, other.length);
                }
        
                uint256 shortest = len;
                if (otherlen < len) shortest = otherlen;
        
                uint256 selfptr;
                uint256 otherptr;
        
                assembly {
                    selfptr := add(self, add(offset, 32))
                    otherptr := add(other, add(otheroffset, 32))
                }
                for (uint256 idx = 0; idx < shortest; idx += 32) {
                    uint256 a;
                    uint256 b;
                    assembly {
                        a := mload(selfptr)
                        b := mload(otherptr)
                    }
                    if (a != b) {
                        // Mask out irrelevant bytes and check again
                        uint256 mask;
                        if (shortest - idx >= 32) {
                            mask = type(uint256).max;
                        } else {
                            mask = ~(2 ** (8 * (idx + 32 - shortest)) - 1);
                        }
                        int256 diff = int256(a & mask) - int256(b & mask);
                        if (diff != 0) return diff;
                    }
                    selfptr += 32;
                    otherptr += 32;
                }
        
                return int256(len) - int256(otherlen);
            }
        
            /*
             * @dev Returns true if the two byte ranges are equal.
             * @param self The first byte range to compare.
             * @param offset The offset into the first byte range.
             * @param other The second byte range to compare.
             * @param otherOffset The offset into the second byte range.
             * @param len The number of bytes to compare
             * @return True if the byte ranges are equal, false otherwise.
             */
            function equals(bytes memory self, uint256 offset, bytes memory other, uint256 otherOffset, uint256 len)
                internal
                pure
                returns (bool)
            {
                return keccak(self, offset, len) == keccak(other, otherOffset, len);
            }
        
            /*
             * @dev Returns true if the two byte ranges are equal with offsets.
             * @param self The first byte range to compare.
             * @param offset The offset into the first byte range.
             * @param other The second byte range to compare.
             * @param otherOffset The offset into the second byte range.
             * @return True if the byte ranges are equal, false otherwise.
             */
            function equals(bytes memory self, uint256 offset, bytes memory other, uint256 otherOffset)
                internal
                pure
                returns (bool)
            {
                return keccak(self, offset, self.length - offset) == keccak(other, otherOffset, other.length - otherOffset);
            }
        
            /*
             * @dev Compares a range of 'self' to all of 'other' and returns True iff
             *      they are equal.
             * @param self The first byte range to compare.
             * @param offset The offset into the first byte range.
             * @param other The second byte range to compare.
             * @return True if the byte ranges are equal, false otherwise.
             */
            function equals(bytes memory self, uint256 offset, bytes memory other) internal pure returns (bool) {
                return self.length == offset + other.length && equals(self, offset, other, 0, other.length);
            }
        
            /*
             * @dev Returns true if the two byte ranges are equal.
             * @param self The first byte range to compare.
             * @param other The second byte range to compare.
             * @return True if the byte ranges are equal, false otherwise.
             */
            function equals(bytes memory self, bytes memory other) internal pure returns (bool) {
                return self.length == other.length && equals(self, 0, other, 0, self.length);
            }
        
            /*
             * @dev Returns the 8-bit number at the specified index of self.
             * @param self The byte string.
             * @param idx The index into the bytes
             * @return The specified 8 bits of the string, interpreted as an integer.
             */
            function readUint8(bytes memory self, uint256 idx) internal pure returns (uint8 ret) {
                return uint8(self[idx]);
            }
        
            /*
             * @dev Returns the 16-bit number at the specified index of self.
             * @param self The byte string.
             * @param idx The index into the bytes
             * @return The specified 16 bits of the string, interpreted as an integer.
             */
            function readUint16(bytes memory self, uint256 idx) internal pure returns (uint16 ret) {
                require(idx + 2 <= self.length);
                assembly {
                    ret := and(mload(add(add(self, 2), idx)), 0xFFFF)
                }
            }
        
            /*
             * @dev Returns the 32-bit number at the specified index of self.
             * @param self The byte string.
             * @param idx The index into the bytes
             * @return The specified 32 bits of the string, interpreted as an integer.
             */
            function readUint32(bytes memory self, uint256 idx) internal pure returns (uint32 ret) {
                require(idx + 4 <= self.length);
                assembly {
                    ret := and(mload(add(add(self, 4), idx)), 0xFFFFFFFF)
                }
            }
        
            /*
             * @dev Returns the 32 byte value at the specified index of self.
             * @param self The byte string.
             * @param idx The index into the bytes
             * @return The specified 32 bytes of the string.
             */
            function readBytes32(bytes memory self, uint256 idx) internal pure returns (bytes32 ret) {
                require(idx + 32 <= self.length);
                assembly {
                    ret := mload(add(add(self, 32), idx))
                }
            }
        
            /*
             * @dev Returns the 32 byte value at the specified index of self.
             * @param self The byte string.
             * @param idx The index into the bytes
             * @return The specified 32 bytes of the string.
             */
            function readBytes20(bytes memory self, uint256 idx) internal pure returns (bytes20 ret) {
                require(idx + 20 <= self.length);
                assembly {
                    ret :=
                        and(mload(add(add(self, 32), idx)), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000)
                }
            }
        
            /*
             * @dev Returns the n byte value at the specified index of self.
             * @param self The byte string.
             * @param idx The index into the bytes.
             * @param len The number of bytes.
             * @return The specified 32 bytes of the string.
             */
            function readBytesN(bytes memory self, uint256 idx, uint256 len) internal pure returns (bytes32 ret) {
                require(len <= 32);
                require(idx + len <= self.length);
                assembly {
                    let mask := not(sub(exp(256, sub(32, len)), 1))
                    ret := and(mload(add(add(self, 32), idx)), mask)
                }
            }
        
            function memcpy(uint256 dest, uint256 src, uint256 len) private pure {
                // Copy word-length chunks while possible
                for (; len >= 32; len -= 32) {
                    assembly {
                        mstore(dest, mload(src))
                    }
                    dest += 32;
                    src += 32;
                }
        
                // Copy remaining bytes
                unchecked {
                    uint256 mask = (256 ** (32 - len)) - 1;
                    assembly {
                        let srcpart := and(mload(src), not(mask))
                        let destpart := and(mload(dest), mask)
                        mstore(dest, or(destpart, srcpart))
                    }
                }
            }
        
            /*
             * @dev Copies a substring into a new byte string.
             * @param self The byte string to copy from.
             * @param offset The offset to start copying at.
             * @param len The number of bytes to copy.
             */
            function substring(bytes memory self, uint256 offset, uint256 len) internal pure returns (bytes memory) {
                require(offset + len <= self.length);
        
                bytes memory ret = new bytes(len);
                uint256 dest;
                uint256 src;
        
                assembly {
                    dest := add(ret, 32)
                    src := add(add(self, 32), offset)
                }
                memcpy(dest, src, len);
        
                return ret;
            }
        
            // Maps characters from 0x30 to 0x7A to their base32 values.
            // 0xFF represents invalid characters in that range.
            bytes constant base32HexTable =
                hex"00010203040506070809FFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1FFFFFFFFFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1F";
        
            /**
             * @dev Decodes unpadded base32 data of up to one word in length.
             * @param self The data to decode.
             * @param off Offset into the string to start at.
             * @param len Number of characters to decode.
             * @return The decoded data, left aligned.
             */
            function base32HexDecodeWord(bytes memory self, uint256 off, uint256 len) internal pure returns (bytes32) {
                require(len <= 52);
        
                uint256 ret = 0;
                uint8 decoded;
                for (uint256 i = 0; i < len; i++) {
                    bytes1 char = self[off + i];
                    require(char >= 0x30 && char <= 0x7A);
                    decoded = uint8(base32HexTable[uint256(uint8(char)) - 0x30]);
                    require(decoded <= 0x20);
                    if (i == len - 1) {
                        break;
                    }
                    ret = (ret << 5) | decoded;
                }
        
                uint256 bitlen = len * 5;
                if (len % 8 == 0) {
                    // Multiple of 8 characters, no padding
                    ret = (ret << 5) | decoded;
                } else if (len % 8 == 2) {
                    // Two extra characters - 1 byte
                    ret = (ret << 3) | (decoded >> 2);
                    bitlen -= 2;
                } else if (len % 8 == 4) {
                    // Four extra characters - 2 bytes
                    ret = (ret << 1) | (decoded >> 4);
                    bitlen -= 4;
                } else if (len % 8 == 5) {
                    // Five extra characters - 3 bytes
                    ret = (ret << 4) | (decoded >> 1);
                    bitlen -= 1;
                } else if (len % 8 == 7) {
                    // Seven extra characters - 4 bytes
                    ret = (ret << 2) | (decoded >> 3);
                    bitlen -= 3;
                } else {
                    revert();
                }
        
                return bytes32(ret << (256 - bitlen));
            }
        
            /**
             * @dev Finds the first occurrence of the byte `needle` in `self`.
             * @param self The string to search
             * @param off The offset to start searching at
             * @param len The number of bytes to search
             * @param needle The byte to search for
             * @return The offset of `needle` in `self`, or 2**256-1 if it was not found.
             */
            function find(bytes memory self, uint256 off, uint256 len, bytes1 needle) internal pure returns (uint256) {
                for (uint256 idx = off; idx < off + len; idx++) {
                    if (self[idx] == needle) {
                        return idx;
                    }
                }
                return type(uint256).max;
            }
        
            /**
             * @dev Attempts to parse an address from a hex string
             * @param str The string to parse
             * @param idx The offset to start parsing at
             * @param lastIdx The (exclusive) last index in `str` to consider. Use `str.length` to scan the whole string.
             */
            function hexToAddress(bytes memory str, uint256 idx, uint256 lastIdx) internal pure returns (address, bool) {
                if (lastIdx - idx < 40) return (address(0x0), false);
                uint256 ret = 0;
                for (uint256 i = idx; i < idx + 40; i++) {
                    ret <<= 4;
                    uint256 x = readUint8(str, i);
                    if (x >= 48 && x < 58) {
                        ret |= x - 48;
                    } else if (x >= 65 && x < 71) {
                        ret |= x - 55;
                    } else if (x >= 97 && x < 103) {
                        ret |= x - 87;
                    } else {
                        return (address(0x0), false);
                    }
                }
                return (address(uint160(ret)), true);
            }
        }
        
        // node_modules/rave/src/IRave.sol
        
        /**
         * @title IRave interface
         * @author Puffer finance
         * @custom:security-contact security@puffer.fi
         * @notice IRave interface
         */
        interface IRave {
            /**
             * Bad report signature
             */
            error BadReportSignature();
        
            /*
            * @dev Verifies the RSA-SHA256 signature of the attestation report.
            * @param report The attestation evidence report from IAS.
            * @param sig The RSA-SHA256 signature over the report.
            * @param signingMod The expected signer's RSA modulus
            * @param signingExp The expected signer's RSA exponent
            * @return True if the signature is valid
            */
            function verifyReportSignature(
                bytes memory report,
                bytes calldata sig,
                bytes memory signingMod,
                bytes memory signingExp
            ) external view returns (bool);
        
            /*
            * @dev Verifies that the leafX509Cert was signed by the expected signer (signingMod, signingExp). 
                Then uses leafX509Cert RSA public key to verify the signature over the report, sig. 
                The trusted report is verified for correct fields and then the enclave' 64 byte commitment is extracted. 
            * @param report The attestation evidence report from IAS.
            * @param sig The RSA-SHA256 signature over the report.
            * @param leafX509Cert The signed leaf x509 certificate.
            * @param signingMod The expected signer's RSA modulus
            * @param signingExp The expected signer's RSA exponent
            * @param mrenclave The expected enclave measurement.
            * @param mrsigner The expected enclave signer.
            * @return The 64 byte payload from the report.
            */
            function rave(
                bytes calldata report,
                bytes memory sig,
                bytes memory leafX509Cert,
                bytes memory signingMod,
                bytes memory signingExp,
                bytes32 mrenclave,
                bytes32 mrsigner
            ) external view returns (bytes memory payload);
        
            /*
            * @dev Verifies that this report was signed by the expected signer, then extracts out the report's 64 byte payload.
            * @param report The attestation evidence report from IAS.
            * @param sig The RSA-SHA256 signature over the report.
            * @param signingMod The expected signer's RSA modulus
            * @param signingExp The expected signer's RSA exponent
            * @param mrenclave The expected enclave measurement.
            * @param mrsigner The expected enclave signer.
            * @return The 64 byte payload from the report.
            */
            function verifyRemoteAttestation(
                bytes calldata report,
                bytes memory sig,
                bytes memory signingMod,
                bytes memory signingExp,
                bytes32 mrenclave,
                bytes32 mrsigner
            ) external view returns (bytes memory payload);
        }
        
        // node_modules/rave/src/JSONBuilder.sol
        
        contract JSONBuilder {
            struct Values {
                bytes id;
                bytes timestamp;
                bytes version;
                bytes epidPseudonym;
                bytes advisoryURL;
                bytes advisoryIDs;
                bytes isvEnclaveQuoteStatus;
                bytes isvEnclaveQuoteBody;
            }
        
            function buildJSON(Values memory values) public pure returns (string memory json) {
                json = string(
                    abi.encodePacked(
                        '{"id":"',
                        values.id,
                        '","timestamp":"',
                        values.timestamp,
                        '","version":',
                        values.version,
                        ',"epidPseudonym":"',
                        values.epidPseudonym
                    )
                );
                json = string(
                    abi.encodePacked(
                        json,
                        '","advisoryURL":"',
                        values.advisoryURL,
                        '","advisoryIDs":',
                        values.advisoryIDs,
                        ',"isvEnclaveQuoteStatus":"',
                        values.isvEnclaveQuoteStatus,
                        '","isvEnclaveQuoteBody":"',
                        values.isvEnclaveQuoteBody,
                        '"}'
                    )
                );
            }
        }
        
        contract CustomJSONBuilder {
            string[] public keys;
        
            constructor(string[] memory _keys) {
                keys = _keys;
            }
        
            function buildJSON(string[] memory values) public view returns (string memory) {
                require(values.length == keys.length);
                string memory json = "";
                for (uint256 i = 0; i < keys.length; i++) {
                    json = string(abi.encodePacked(json, keys[i], values[i]));
                }
                return string(abi.encodePacked("{", json, '"}'));
            }
        }
        
        // node_modules/rave/src/RSAVerify.sol
        
        // Copied from https://github.com/ensdomains/ens-contracts/blob/80aa5108f11d11cd7956135ef21ac45da8eb934d/contracts/dnssec-oracle/algorithms/RSAVerify.sol
        
        library ModexpPrecompile {
            /**
             * @dev Computes (base ^ exponent) % modulus over big numbers.
             */
            function modexp(bytes memory base, bytes memory exponent, bytes memory modulus)
                internal
                view
                returns (bool success, bytes memory output)
            {
                bytes memory input = abi.encodePacked(
                    uint256(base.length), uint256(exponent.length), uint256(modulus.length), base, exponent, modulus
                );
        
                output = new bytes(modulus.length);
        
                assembly {
                    success := staticcall(gas(), 5, add(input, 32), mload(input), add(output, 32), mload(modulus))
                }
            }
        }
        
        library RSAVerify {
            /**
             * @dev Recovers the input data from an RSA signature, returning the result in S.
             * @param N The RSA public modulus.
             * @param E The RSA public exponent.
             * @param S The signature to recover.
             * @return True if the recovery succeeded.
             */
            function rsarecover(bytes memory N, bytes memory E, bytes memory S) internal view returns (bool, bytes memory) {
                return ModexpPrecompile.modexp(S, E, N);
            }
        }
        
        // src/Errors.sol
        
        /**
         * @notice Thrown when the operation is not authorized
         * @dev Signature "0x82b42900"
         */
        error Unauthorized();
        
        /**
         * @notice Thrown if the address supplied is not valid
         * @dev Signature "0xe6c4247b"
         */
        error InvalidAddress();
        
        // src/interface/IPufferOracle.sol
        
        /**
         * @title IPufferOracle
         * @author Puffer Finance
         * @custom:security-contact security@puffer.fi
         */
        interface IPufferOracle {
            /**
             * @notice Thrown if the new ValidatorTicket mint price is invalid
             */
            error InvalidValidatorTicketPrice();
        
            /**
             * @notice Emitted when the price to mint ValidatorTicket is updated
             * @dev Signature "0xf76811fec27423d0853e6bf49d7ea78c666629c2f67e29647d689954021ae0ea"
             */
            event ValidatorTicketMintPriceUpdated(uint256 oldPrice, uint256 newPrice);
        
            /**
             * @notice Retrieves the current mint price for minting one ValidatorTicket
             * @return pricePerVT The current ValidatorTicket mint price
             */
            function getValidatorTicketPrice() external view returns (uint256 pricePerVT);
        
            /**
             * @notice Returns true if the number of active Puffer Validators is over the burst threshold
             */
            function isOverBurstThreshold() external view returns (bool);
        
            /**
             * @notice Returns the locked ETH amount
             * @return lockedEthAmount The amount of ETH locked in Beacon chain
             */
            function getLockedEthAmount() external view returns (uint256 lockedEthAmount);
        }
        
        // src/interface/IValidatorTicketPricer.sol
        
        /**
         * @title IValidatorTicketPricer
         * @notice Interface for the ValidatorTicketPricer contract
         */
        interface IValidatorTicketPricer {
            /**
             * @notice Thrown if the new value is invalid
             */
            error InvalidValue();
        
            /**
             * @notice Emitted when daily MEV payouts are updated
             * @param oldValue The old value of daily MEV payouts
             * @param newValue The new value of daily MEV payouts
             */
            event DailyMevPayoutsUpdated(uint104 oldValue, uint104 newValue);
        
            /**
             * @notice Emitted when daily consensus rewards are updated
             * @param oldValue The old value of daily consensus rewards
             * @param newValue The new value of daily consensus rewards
             */
            event DailyConsensusRewardsUpdated(uint104 oldValue, uint104 newValue);
        
            /**
             * @notice Emitted when daily MEV payouts change tolerance is updated
             * @param oldValue The old tolerance value
             * @param newValue The new tolerance value
             */
            event DailyMevPayoutsChangeToleranceBPSUpdated(uint16 oldValue, uint16 newValue);
        
            /**
             * @notice Emitted when daily consensus rewards change tolerance is updated
             * @param oldValue The old tolerance value
             * @param newValue The new tolerance value
             */
            event DailyConsensusRewardsChangeToleranceBPSUpdated(uint16 oldValue, uint16 newValue);
        
            /**
             * @notice Emitted when the discount rate is updated
             * @param oldValue The old discount rate
             * @param newValue The new discount rate
             */
            event DiscountRateUpdated(uint16 oldValue, uint16 newValue);
        
            /**
             * @notice Sets the daily MEV payouts change tolerance in basis points
             * @param newValue The new tolerance value to set
             */
            function setDailyMevPayoutsChangeToleranceBps(uint16 newValue) external;
        
            /**
             * @notice Sets the daily consensus rewards change tolerance in basis points
             * @param newValue The new tolerance value to set
             */
            function setDailyConsensusRewardsChangeToleranceBps(uint16 newValue) external;
        
            /**
             * @notice Updates the allowed price change tolerance percentage
             * @param newValue The new discount rate to set
             */
            function setDiscountRate(uint16 newValue) external;
        
            /**
             * @notice Updates the daily MEV payouts
             * @param newValue The new daily MEV payouts value to set
             */
            function setDailyMevPayouts(uint104 newValue) external;
        
            /**
             * @notice Updates the daily consensus rewards
             * @param newValue The new daily consensus rewards value to set
             */
            function setDailyConsensusRewards(uint104 newValue) external;
        
            /**
             * @notice Posts the mint price based on current MEV payouts and consensus rewards
             */
            function postMintPrice() external;
        
            /**
             * @notice Updates daily rewards and posts the mint price
             * @param dailyMevPayouts The new daily MEV payouts value to set
             * @param dailyConsensusRewards The new daily consensus rewards value to set
             */
            function setDailyRewardsAndPostMintPrice(uint104 dailyMevPayouts, uint104 dailyConsensusRewards) external;
        
            /**
             * @notice Gets the daily MEV payouts change tolerance in basis points
             * @return The current daily MEV payouts change tolerance in basis points
             */
            function getDailyMevPayoutsChangeToleranceBps() external view returns (uint16);
        
            /**
             * @notice Gets the daily consensus rewards change tolerance in basis points
             * @return The current daily consensus rewards change tolerance in basis points
             */
            function getDailyConsensusRewardsChangeToleranceBps() external view returns (uint16);
        
            /**
             * @notice Gets the discount rate in basis points
             * @return The current discount rate in basis points
             */
            function getDiscountRateBps() external view returns (uint16);
        
            /**
             * @notice Gets the daily MEV payouts
             * @return The current daily MEV payouts
             */
            function getDailyMevPayouts() external view returns (uint104);
        
            /**
             * @notice Gets the daily consensus rewards
             * @return The current daily consensus rewards
             */
            function getDailyConsensusRewards() external view returns (uint104);
        }
        
        // src/struct/RaveEvidence.sol
        
        struct RaveEvidence {
            // Preprocessed remote attestation report
            bytes report;
            // Preprocessed RSA signature over the report
            bytes signature;
            // The hash of a whitelisted Intel-signed leaf x509 certificate
            bytes32 leafX509CertDigest;
        }
        
        // src/struct/StoppedValidatorInfo.sol
        
        /**
         * @dev Stopped validator info
         */
        struct StoppedValidatorInfo {
            ///@dev Module address.
            address module;
            ///@dev Validator start epoch.
            uint256 startEpoch;
            ///@dev Validator stop epoch.
            uint256 endEpoch;
            /// @dev Indicates whether the validator was slashed before stopping.
            bool wasSlashed;
            /// @dev Name of the module where the validator was participating.
            bytes32 moduleName;
            /// @dev Index of the validator in the module's validator list.
            uint256 pufferModuleIndex;
            /// @dev Amount of funds withdrawn upon validator stoppage.
            uint256 withdrawalAmount;
        }
        
        // node_modules/@openzeppelin/contracts/access/manager/AuthorityUtils.sol
        
        // OpenZeppelin Contracts (last updated v5.0.0) (access/manager/AuthorityUtils.sol)
        
        library AuthorityUtils {
            /**
             * @dev Since `AccessManager` implements an extended IAuthority interface, invoking `canCall` with backwards compatibility
             * for the preexisting `IAuthority` interface requires special care to avoid reverting on insufficient return data.
             * This helper function takes care of invoking `canCall` in a backwards compatible way without reverting.
             */
            function canCallWithDelay(
                address authority,
                address caller,
                address target,
                bytes4 selector
            ) internal view returns (bool immediate, uint32 delay) {
                (bool success, bytes memory data) = authority.staticcall(
                    abi.encodeCall(IAuthority.canCall, (caller, target, selector))
                );
                if (success) {
                    if (data.length >= 0x40) {
                        (immediate, delay) = abi.decode(data, (bool, uint32));
                    } else if (data.length >= 0x20) {
                        immediate = abi.decode(data, (bool));
                    }
                }
                return (immediate, delay);
            }
        }
        
        // node_modules/rave/src/ASN1Decode.sol
        
        // Original source: https://github.com/JonahGroendal/asn1-decode
        
        library NodePtr {
            // Unpack first byte index
            function ixs(uint256 self) internal pure returns (uint256) {
                return uint80(self);
            }
            // Unpack first content byte index
        
            function ixf(uint256 self) internal pure returns (uint256) {
                return uint80(self >> 80);
            }
            // Unpack last content byte index
        
            function ixl(uint256 self) internal pure returns (uint256) {
                return uint80(self >> 160);
            }
            // Pack 3 uint80s into a uint256
        
            function getPtr(uint256 _ixs, uint256 _ixf, uint256 _ixl) internal pure returns (uint256) {
                _ixs |= _ixf << 80;
                _ixs |= _ixl << 160;
                return _ixs;
            }
        }
        
        library Asn1Decode {
            using NodePtr for uint256;
            using BytesUtils for bytes;
        
            /*
            * @dev Get the root node. First step in traversing an ASN1 structure
            * @param der The DER-encoded ASN1 structure
            * @return A pointer to the outermost node
            */
            function root(bytes memory der) internal pure returns (uint256) {
                return readNodeLength(der, 0);
            }
        
            /*
            * @dev Get the root node of an ASN1 structure that's within a bit string value
            * @param der The DER-encoded ASN1 structure
            * @return A pointer to the outermost node
            */
            function rootOfBitStringAt(bytes memory der, uint256 ptr) internal pure returns (uint256) {
                require(der[ptr.ixs()] == 0x03, "Not type BIT STRING");
                return readNodeLength(der, ptr.ixf() + 1);
            }
        
            /*
            * @dev Get the root node of an ASN1 structure that's within an octet string value
            * @param der The DER-encoded ASN1 structure
            * @return A pointer to the outermost node
            */
            function rootOfOctetStringAt(bytes memory der, uint256 ptr) internal pure returns (uint256) {
                require(der[ptr.ixs()] == 0x04, "Not type OCTET STRING");
                return readNodeLength(der, ptr.ixf());
            }
        
            /*
            * @dev Get the next sibling node
            * @param der The DER-encoded ASN1 structure
            * @param ptr Points to the indices of the current node
            * @return A pointer to the next sibling node
            */
            function nextSiblingOf(bytes memory der, uint256 ptr) internal pure returns (uint256) {
                return readNodeLength(der, ptr.ixl() + 1);
            }
        
            /*
            * @dev Get the first child node of the current node
            * @param der The DER-encoded ASN1 structure
            * @param ptr Points to the indices of the current node
            * @return A pointer to the first child node
            */
            function firstChildOf(bytes memory der, uint256 ptr) internal pure returns (uint256) {
                require(der[ptr.ixs()] & 0x20 == 0x20, "Not a constructed type");
                return readNodeLength(der, ptr.ixf());
            }
        
            /*
            * @dev Use for looping through children of a node (either i or j).
            * @param i Pointer to an ASN1 node
            * @param j Pointer to another ASN1 node of the same ASN1 structure
            * @return True iff j is child of i or i is child of j.
            */
            function isChildOf(uint256 i, uint256 j) internal pure returns (bool) {
                return (((i.ixf() <= j.ixs()) && (j.ixl() <= i.ixl())) || ((j.ixf() <= i.ixs()) && (i.ixl() <= j.ixl())));
            }
        
            /*
            * @dev Extract value of node from DER-encoded structure
            * @param der The der-encoded ASN1 structure
            * @param ptr Points to the indices of the current node
            * @return Value bytes of node
            */
            function bytesAt(bytes memory der, uint256 ptr) internal pure returns (bytes memory) {
                return der.substring(ptr.ixf(), ptr.ixl() + 1 - ptr.ixf());
            }
        
            /*
            * @dev Extract entire node from DER-encoded structure
            * @param der The DER-encoded ASN1 structure
            * @param ptr Points to the indices of the current node
            * @return All bytes of node
            */
            function allBytesAt(bytes memory der, uint256 ptr) internal pure returns (bytes memory) {
                return der.substring(ptr.ixs(), ptr.ixl() + 1 - ptr.ixs());
            }
        
            /*
            * @dev Extract value of node from DER-encoded structure
            * @param der The DER-encoded ASN1 structure
            * @param ptr Points to the indices of the current node
            * @return Value bytes of node as bytes32
            */
            function bytes32At(bytes memory der, uint256 ptr) internal pure returns (bytes32) {
                return der.readBytesN(ptr.ixf(), ptr.ixl() + 1 - ptr.ixf());
            }
        
            /*
            * @dev Extract value of node from DER-encoded structure
            * @param der The der-encoded ASN1 structure
            * @param ptr Points to the indices of the current node
            * @return Uint value of node
            */
            function uintAt(bytes memory der, uint256 ptr) internal pure returns (uint256) {
                require(der[ptr.ixs()] == 0x02, "Not type INTEGER");
                require(der[ptr.ixf()] & 0x80 == 0, "Not positive");
                uint256 len = ptr.ixl() + 1 - ptr.ixf();
                return uint256(der.readBytesN(ptr.ixf(), len) >> (32 - len) * 8);
            }
        
            /*
            * @dev Extract value of a positive integer node from DER-encoded structure
            * @param der The DER-encoded ASN1 structure
            * @param ptr Points to the indices of the current node
            * @return Value bytes of a positive integer node
            */
            function uintBytesAt(bytes memory der, uint256 ptr) internal pure returns (bytes memory) {
                require(der[ptr.ixs()] == 0x02, "Not type INTEGER");
                require(der[ptr.ixf()] & 0x80 == 0, "Not positive");
                uint256 valueLength = ptr.ixl() + 1 - ptr.ixf();
                if (der[ptr.ixf()] == 0) {
                    return der.substring(ptr.ixf() + 1, valueLength - 1);
                } else {
                    return der.substring(ptr.ixf(), valueLength);
                }
            }
        
            function keccakOfBytesAt(bytes memory der, uint256 ptr) internal pure returns (bytes32) {
                return der.keccak(ptr.ixf(), ptr.ixl() + 1 - ptr.ixf());
            }
        
            function keccakOfAllBytesAt(bytes memory der, uint256 ptr) internal pure returns (bytes32) {
                return der.keccak(ptr.ixs(), ptr.ixl() + 1 - ptr.ixs());
            }
        
            /*
            * @dev Extract value of bitstring node from DER-encoded structure
            * @param der The DER-encoded ASN1 structure
            * @param ptr Points to the indices of the current node
            * @return Value of bitstring converted to bytes
            */
            function bitstringAt(bytes memory der, uint256 ptr) internal pure returns (bytes memory) {
                require(der[ptr.ixs()] == 0x03, "Not type BIT STRING");
                // Only 00 padded bitstr can be converted to bytestr!
                require(der[ptr.ixf()] == 0x00);
                uint256 valueLength = ptr.ixl() + 1 - ptr.ixf();
                return der.substring(ptr.ixf() + 1, valueLength - 1);
            }
        
            function readNodeLength(bytes memory der, uint256 ix) private pure returns (uint256) {
                uint256 length;
                uint80 ixFirstContentByte;
                uint80 ixLastContentByte;
                if ((der[ix + 1] & 0x80) == 0) {
                    length = uint8(der[ix + 1]);
                    ixFirstContentByte = uint80(ix + 2);
                    ixLastContentByte = uint80(ixFirstContentByte + length - 1);
                } else {
                    uint8 lengthbytesLength = uint8(der[ix + 1] & 0x7F);
                    if (lengthbytesLength == 1) {
                        length = der.readUint8(ix + 2);
                    } else if (lengthbytesLength == 2) {
                        length = der.readUint16(ix + 2);
                    } else {
                        length = uint256(der.readBytesN(ix + 2, lengthbytesLength) >> (32 - lengthbytesLength) * 8);
                    }
                    ixFirstContentByte = uint80(ix + 2 + lengthbytesLength);
                    ixLastContentByte = uint80(ixFirstContentByte + length - 1);
                }
                return NodePtr.getPtr(ix, ixFirstContentByte, ixLastContentByte);
            }
        }
        
        // src/interface/IEnclaveVerifier.sol
        
        /**
         * @title IEnclaveVerifier interface
         * @author Puffer Finance
         * @custom:security-contact security@puffer.fi
         */
        interface IEnclaveVerifier {
            struct RSAPubKey {
                bytes modulus;
                bytes exponent;
            }
        
            /**
             * @notice Thrown if the Evidence that we're trying to verify is stale
             * Evidence should be submitted for the recent block < `FRESHNESS_BLOCKS`
             * @dev Signature "0x5d4ad9a9"
             */
            error StaleEvidence();
        
            /**
             * @notice Emitted when the `pubKeyHash` is added to valid pubKeys
             * @dev Signature "0x13b85b042d2bb270091da7111e3b3cc407f6b86c85882cf48ae94123cae22b17"
             */
            event AddedPubKey(bytes32 indexed pubKeyHash);
        
            /**
             * @notice Emitted when the `pubKeyHash` is removed from valid pubKeys
             * @dev Signature "0x0ebd07953ae533bded7d9b0715fa49e0a0ed0a6cef4638a685737ffef8b86254"
             */
            event RemovedPubKey(bytes32 indexed pubKeyHash);
        
            /**
             * @notice Getter for intelRootCAPubKey
             */
            function getIntelRootCAPubKey() external pure returns (RSAPubKey memory);
        
            /**
             * @notice Adds a leaf x509 RSA public key if the x509 was signed by Intel's root CA
             * @param leafX509Cert certificate
             */
            function addLeafX509(bytes calldata leafX509Cert) external;
        
            /**
             * @notice Verifies remote attestation evidence: the report contains the expected MRENCLAVE/MRSIGNER values, a valid TCB status, and was signed by an Intel-issued x509 certificate. The report will contain a 64B payload in the form (32B_Commitment || 32B_BlockHash), where 32B_Blockhash is a recent L1 blockhash and 32B_Commitment is a keccak256 hash that the enclave is committing to. The calling contract is expected to precompute raveCommitment from public inputs. The function returns true if the report is valid and the extracted payload matches the expected.
             * @param blockNumber is the block number to fetch 32B_Blockhash
             * @param raveCommitment is the keccak256 hash commitment 32B_Commitment
             * @param evidence is the remote attestation evidence
             * @param mrenclave is the MRENCLAVE value expected by the calling contract
             * @param mrsigner is the MRSIGNER value expected by the calling contract
             * @return true if evidence verification is a success
             */
            function verifyEvidence(
                uint256 blockNumber,
                bytes32 raveCommitment,
                RaveEvidence calldata evidence,
                bytes32 mrenclave,
                bytes32 mrsigner
            ) external view returns (bool);
        }
        
        // src/interface/IPufferOracleV2.sol
        
        /**
         * @title IPufferOracle
         * @author Puffer Finance
         * @custom:security-contact security@puffer.fi
         */
        interface IPufferOracleV2 is IPufferOracle {
            error InvalidUpdate();
            /**
             * @notice Emitted when the number of active Puffer validators is updated
             * @param numberOfActivePufferValidators is the number of active Puffer validators
             */
        
            event NumberOfActiveValidators(uint256 numberOfActivePufferValidators);
        
            /**
             * @notice Emitted when the total number of validators is updated
             * @param oldNumberOfValidators is the old number of validators
             * @param newNumberOfValidators is the new number of validators
             */
            event TotalNumberOfValidatorsUpdated(
                uint256 oldNumberOfValidators, uint256 newNumberOfValidators, uint256 epochNumber
            );
        
            /**
             * @notice Returns the total number of active validators on Ethereum
             */
            function getTotalNumberOfValidators() external view returns (uint256);
        
            /**
             * @notice Returns the number of active puffer validators on Ethereum
             */
            function getNumberOfActiveValidators() external view returns (uint256);
        
            /**
             * @notice Exits `validatorNumber` validators, decreasing the `lockedETHAmount` by validatorNumber * 32 ETH.
             * It is called when when the validator exits the system in the `batchHandleWithdrawals` on the PufferProtocol.
             * In the same transaction, we are transferring full withdrawal ETH from the PufferModule to the Vault
             * Decrementing the `lockedETHAmount` by 32 ETH and we burn the Node Operator's pufETH (bond) if we need to cover up the loss.
             * @dev Restricted to PufferProtocol contract
             */
            function exitValidators(uint256 validatorNumber) external;
        
            /**
             * @notice Increases the `lockedETHAmount` on the PufferOracle by 32 ETH to account for a new deposit.
             * It is called when the Beacon chain receives a new deposit from the PufferProtocol.
             * The PufferVault's balance will simultaneously decrease by 32 ETH as the deposit is made.
             * @dev Restricted to PufferProtocol contract
             */
            function provisionNode() external;
        }
        
        // node_modules/@openzeppelin/contracts/utils/types/Time.sol
        
        // OpenZeppelin Contracts (last updated v5.0.0) (utils/types/Time.sol)
        
        /**
         * @dev This library provides helpers for manipulating time-related objects.
         *
         * It uses the following types:
         * - `uint48` for timepoints
         * - `uint32` for durations
         *
         * While the library doesn't provide specific types for timepoints and duration, it does provide:
         * - a `Delay` type to represent duration that can be programmed to change value automatically at a given point
         * - additional helper functions
         */
        library Time {
            using Time for *;
        
            /**
             * @dev Get the block timestamp as a Timepoint.
             */
            function timestamp() internal view returns (uint48) {
                return SafeCast.toUint48(block.timestamp);
            }
        
            /**
             * @dev Get the block number as a Timepoint.
             */
            function blockNumber() internal view returns (uint48) {
                return SafeCast.toUint48(block.number);
            }
        
            // ==================================================== Delay =====================================================
            /**
             * @dev A `Delay` is a uint32 duration that can be programmed to change value automatically at a given point in the
             * future. The "effect" timepoint describes when the transitions happens from the "old" value to the "new" value.
             * This allows updating the delay applied to some operation while keeping some guarantees.
             *
             * In particular, the {update} function guarantees that if the delay is reduced, the old delay still applies for
             * some time. For example if the delay is currently 7 days to do an upgrade, the admin should not be able to set
             * the delay to 0 and upgrade immediately. If the admin wants to reduce the delay, the old delay (7 days) should
             * still apply for some time.
             *
             *
             * The `Delay` type is 112 bits long, and packs the following:
             *
             * ```
             *   | [uint48]: effect date (timepoint)
             *   |           | [uint32]: value before (duration)
             *   ↓           ↓       ↓ [uint32]: value after (duration)
             * 0xAAAAAAAAAAAABBBBBBBBCCCCCCCC
             * ```
             *
             * NOTE: The {get} and {withUpdate} functions operate using timestamps. Block number based delays are not currently
             * supported.
             */
            type Delay is uint112;
        
            /**
             * @dev Wrap a duration into a Delay to add the one-step "update in the future" feature
             */
            function toDelay(uint32 duration) internal pure returns (Delay) {
                return Delay.wrap(duration);
            }
        
            /**
             * @dev Get the value at a given timepoint plus the pending value and effect timepoint if there is a scheduled
             * change after this timepoint. If the effect timepoint is 0, then the pending value should not be considered.
             */
            function _getFullAt(Delay self, uint48 timepoint) private pure returns (uint32, uint32, uint48) {
                (uint32 valueBefore, uint32 valueAfter, uint48 effect) = self.unpack();
                return effect <= timepoint ? (valueAfter, 0, 0) : (valueBefore, valueAfter, effect);
            }
        
            /**
             * @dev Get the current value plus the pending value and effect timepoint if there is a scheduled change. If the
             * effect timepoint is 0, then the pending value should not be considered.
             */
            function getFull(Delay self) internal view returns (uint32, uint32, uint48) {
                return _getFullAt(self, timestamp());
            }
        
            /**
             * @dev Get the current value.
             */
            function get(Delay self) internal view returns (uint32) {
                (uint32 delay, , ) = self.getFull();
                return delay;
            }
        
            /**
             * @dev Update a Delay object so that it takes a new duration after a timepoint that is automatically computed to
             * enforce the old delay at the moment of the update. Returns the updated Delay object and the timestamp when the
             * new delay becomes effective.
             */
            function withUpdate(
                Delay self,
                uint32 newValue,
                uint32 minSetback
            ) internal view returns (Delay updatedDelay, uint48 effect) {
                uint32 value = self.get();
                uint32 setback = uint32(Math.max(minSetback, value > newValue ? value - newValue : 0));
                effect = timestamp() + setback;
                return (pack(value, newValue, effect), effect);
            }
        
            /**
             * @dev Split a delay into its components: valueBefore, valueAfter and effect (transition timepoint).
             */
            function unpack(Delay self) internal pure returns (uint32 valueBefore, uint32 valueAfter, uint48 effect) {
                uint112 raw = Delay.unwrap(self);
        
                valueAfter = uint32(raw);
                valueBefore = uint32(raw >> 32);
                effect = uint48(raw >> 64);
        
                return (valueBefore, valueAfter, effect);
            }
        
            /**
             * @dev pack the components into a Delay object.
             */
            function pack(uint32 valueBefore, uint32 valueAfter, uint48 effect) internal pure returns (Delay) {
                return Delay.wrap((uint112(effect) << 64) | (uint112(valueBefore) << 32) | uint112(valueAfter));
            }
        }
        
        // node_modules/rave/src/RAVEBase.sol
        
        abstract contract RAVEBase is IRave {
            using BytesUtils for *;
        
            uint256 constant MAX_JSON_ELEMENTS = 19;
            uint256 constant QUOTE_BODY_LENGTH = 432;
            uint256 constant MRENCLAVE_OFFSET = 112;
            uint256 constant MRSIGNER_OFFSET = 176;
            uint256 constant PAYLOAD_OFFSET = 368;
            uint256 constant PAYLOAD_SIZE = 64;
        
            bytes32 constant OK_STATUS = keccak256("OK");
            bytes32 constant HARDENING_STATUS = keccak256("SW_HARDENING_NEEDED");
        
            constructor() { }
        
            /**
             * @inheritdoc IRave
             */
            function verifyReportSignature(
                bytes memory report,
                bytes calldata sig,
                bytes memory signingMod,
                bytes memory signingExp
            ) public view returns (bool) {
                // Use signingPK to verify sig is the RSA signature over sha256(report)
                (bool success, bytes memory got) = RSAVerify.rsarecover(signingMod, signingExp, sig);
                // Last 32 bytes is recovered signed digest
                bytes32 recovered = got.readBytes32(got.length - 32);
                return success && recovered == sha256(report);
            }
        
            /**
             * @inheritdoc IRave
             */
            function verifyRemoteAttestation(
                bytes calldata report,
                bytes calldata sig,
                bytes memory signingMod,
                bytes memory signingExp,
                bytes32 mrenclave,
                bytes32 mrsigner
            ) public view virtual returns (bytes memory payload) { }
        
            /**
             * @inheritdoc IRave
             */
            function rave(
                bytes calldata report,
                bytes calldata sig,
                bytes memory leafX509Cert,
                bytes memory signingMod,
                bytes memory signingExp,
                bytes32 mrenclave,
                bytes32 mrsigner
            ) external view virtual returns (bytes memory payload) { }
        }
        
        // node_modules/rave/src/X509Verifier.sol
        
        library X509Verifier {
            using Asn1Decode for bytes;
            using BytesUtils for bytes;
        
            /*
             * @dev Verifies an x509 certificate was signed (RSASHA256) by the supplied public key. 
             * @param childCertBody The DER-encoded body (preimage) of the x509   child certificate
             * @param certSig The RSASHA256 signature of the childCertBody
             * @param parentMod The modulus of the parent certificate's public RSA key
             * @param parentExp The exponent of the parent certificate's public RSA key
             * @return Returns true if this childCertBody was signed by the parent's RSA private key
             */
            function verifyChildCert(
                bytes memory childCertBody,
                bytes memory certSig,
                bytes memory parentMod,
                bytes memory parentExp
            ) public view returns (bool) {
                // Recover the digest using parent's public key
                (bool success, bytes memory res) = RSAVerify.rsarecover(parentMod, parentExp, certSig);
                // Digest is last 32 bytes of res
                bytes32 recovered = res.readBytes32(res.length - 32);
                return success && recovered == sha256(childCertBody);
            }
        
            /*
             * @dev specs: https://www.ietf.org/rfc/rfc5280.txt
             * @dev     Certificate  ::=  SEQUENCE  {
             * @dev         tbsCertificate       TBSCertificate,
             * @dev         signatureAlgorithm   AlgorithmIdentifier,
             * @dev         signatureValue       BIT STRING  }
             * @dev
             * @dev     TBSCertificate  ::=  SEQUENCE  {
             * @dev         version         [0]  EXPLICIT Version DEFAULT v1,
             * @dev         serialNumber         CertificateSerialNumber,
             * @dev         signature            AlgorithmIdentifier,
             * @dev         issuer               Name,
             * @dev         validity             Validity,
             * @dev         subject              Name,
             * @dev         subjectPublicKeyInfo SubjectPublicKeyInfo,
             * @dev         issuerUniqueID  [1]  IMPLICIT UniqueIdentifier OPTIONAL,
             * @dev                              -- If present, version MUST be v2 or v3
             * @dev         subjectUniqueID [2]  IMPLICIT UniqueIdentifier OPTIONAL,
             * @dev                              -- If present, version MUST be v2 or v3
             * @dev         extensions      [3]  EXPLICIT Extensions OPTIONAL
             * @dev                              -- If present, version MUST be v3
             * @dev         }
             * @dev Verifies an x509 certificate was signed (RSASHA256) by the parent's
             * @dev supplied modulus and exponent, then returns the child x509's modulus and exponent.
             * @param cert The DER-encoded signed x509 certificate.
             * @param parentMod The parent RSA modulus.
             * @param parentExp The parent RSA exponent.
             * @return Returns the RSA modulus and exponent of the signed x509 certificate iff it was signed by the parent.
             */
            function verifySignedX509(bytes memory cert, bytes memory parentMod, bytes memory parentExp)
                public
                view
                returns (bytes memory, bytes memory)
            {
                // Pointer to top level asn1 object: Sequence{tbsCertificate, signatureAlgorithm, signatureValue}
                uint256 root = cert.root();
        
                // Traverse to first in sequence (the tbsCertificate)
                uint256 tbsPtr = cert.firstChildOf(root);
        
                // Extracts the TBSCerificate (what is used as input to RSA-SHA256)
                bytes memory certBody = cert.allBytesAt(tbsPtr);
        
                // Top level traverse to signatureAlgorithm
                uint256 sigAlgPtr = cert.nextSiblingOf(tbsPtr);
        
                // Top level traverse to signatureValue
                uint256 sigPtr = cert.nextSiblingOf(sigAlgPtr);
        
                // Extracts the signed certificate body
                bytes memory signature = cert.bytesAt(sigPtr);
        
                // Verify the parent signed the certBody
                require(verifyChildCert(certBody, signature, parentMod, parentExp), "verifyChildCert fail");
        
                //  ----------------
                // Begin traversing the tbsCertificate
                //  ----------------
        
                // Traverse to first child of tbsCertificate
                uint256 ptr = cert.firstChildOf(tbsPtr);
        
                // Account for v1 vs v3
                if (cert[NodePtr.ixs(ptr)] == 0xa0) {
                    ptr = cert.nextSiblingOf(ptr);
                }
        
                // Extract serialNumber (CertificateSerialNumber)
                // uint256 serialNumber = uint160(cert.uintAt(ptr));
        
                // Skip the next 3 fields (signature, issuer, validity, subject)
                ptr = cert.nextSiblingOf(ptr); // point to signature
                ptr = cert.nextSiblingOf(ptr); // point to issuer
                ptr = cert.nextSiblingOf(ptr); // point to validity
        
                // Arrive at the validity field
                // todo verifiy validity timestamps
                // uint256 validityPtr = ptr;
                // bytes memory validNotBefore = cert.bytesAt(validityPtr);
                // console.logBytes(validNotBefore);
                // uint40 validNotBefore = uint40(toTimestamp(cert.bytesAt(validityPtr)));
                // console.log("validNotBefore: %s", validNotBefore);
                // validityPtr = cert.nextSiblingOf(validityPtr);
                // bytes memory validNotAfter = cert.bytesAt(validityPtr);
                // console.logBytes(validNotAfter);
                // uint40 validNotAfter = uint40(toTimestamp(cert.bytesAt(validityPtr)));
                // console.log("validNotAfter: %s", validNotAfter);
        
                // Traverse until the subjectPublicKeyInfo field
                ptr = cert.nextSiblingOf(ptr); // point to subject
                ptr = cert.nextSiblingOf(ptr); // point to subjectPublicKeyInfo
        
                // Enter subjectPublicKeyInfo
                ptr = cert.firstChildOf(ptr); // point to subjectPublicKeyInfo.algorithm
                ptr = cert.nextSiblingOf(ptr); // point to subjectPublicKeyInfo.subjectPublicKey
        
                // Extract DER-encoded RSA public key
                bytes memory pubKey = cert.bitstringAt(ptr);
        
                // Extract RSA modulus
                uint256 pkPtr = pubKey.root();
                pkPtr = pubKey.firstChildOf(pkPtr);
                bytes memory modulus = pubKey.bytesAt(pkPtr);
        
                // Extract RSA exponent
                pkPtr = pubKey.nextSiblingOf(pkPtr);
                bytes memory exponent = pubKey.bytesAt(pkPtr);
        
                return (modulus, exponent);
            }
        
            /*
             * @dev Verifies the x509 certificate hasn't expired
             * @param certBody The DER-encoded body (preimage) of the x509 
             * @return Returns ...
             */
            function notExpired(bytes calldata) public pure returns (bool) {
                // TODO
                return true;
            }
        }
        
        // node_modules/@openzeppelin/contracts/access/manager/IAccessManager.sol
        
        // OpenZeppelin Contracts (last updated v5.0.0) (access/manager/IAccessManager.sol)
        
        interface IAccessManager {
            /**
             * @dev A delayed operation was scheduled.
             */
            event OperationScheduled(
                bytes32 indexed operationId,
                uint32 indexed nonce,
                uint48 schedule,
                address caller,
                address target,
                bytes data
            );
        
            /**
             * @dev A scheduled operation was executed.
             */
            event OperationExecuted(bytes32 indexed operationId, uint32 indexed nonce);
        
            /**
             * @dev A scheduled operation was canceled.
             */
            event OperationCanceled(bytes32 indexed operationId, uint32 indexed nonce);
        
            /**
             * @dev Informational labelling for a roleId.
             */
            event RoleLabel(uint64 indexed roleId, string label);
        
            /**
             * @dev Emitted when `account` is granted `roleId`.
             *
             * NOTE: The meaning of the `since` argument depends on the `newMember` argument.
             * If the role is granted to a new member, the `since` argument indicates when the account becomes a member of the role,
             * otherwise it indicates the execution delay for this account and roleId is updated.
             */
            event RoleGranted(uint64 indexed roleId, address indexed account, uint32 delay, uint48 since, bool newMember);
        
            /**
             * @dev Emitted when `account` membership or `roleId` is revoked. Unlike granting, revoking is instantaneous.
             */
            event RoleRevoked(uint64 indexed roleId, address indexed account);
        
            /**
             * @dev Role acting as admin over a given `roleId` is updated.
             */
            event RoleAdminChanged(uint64 indexed roleId, uint64 indexed admin);
        
            /**
             * @dev Role acting as guardian over a given `roleId` is updated.
             */
            event RoleGuardianChanged(uint64 indexed roleId, uint64 indexed guardian);
        
            /**
             * @dev Grant delay for a given `roleId` will be updated to `delay` when `since` is reached.
             */
            event RoleGrantDelayChanged(uint64 indexed roleId, uint32 delay, uint48 since);
        
            /**
             * @dev Target mode is updated (true = closed, false = open).
             */
            event TargetClosed(address indexed target, bool closed);
        
            /**
             * @dev Role required to invoke `selector` on `target` is updated to `roleId`.
             */
            event TargetFunctionRoleUpdated(address indexed target, bytes4 selector, uint64 indexed roleId);
        
            /**
             * @dev Admin delay for a given `target` will be updated to `delay` when `since` is reached.
             */
            event TargetAdminDelayUpdated(address indexed target, uint32 delay, uint48 since);
        
            error AccessManagerAlreadyScheduled(bytes32 operationId);
            error AccessManagerNotScheduled(bytes32 operationId);
            error AccessManagerNotReady(bytes32 operationId);
            error AccessManagerExpired(bytes32 operationId);
            error AccessManagerLockedAccount(address account);
            error AccessManagerLockedRole(uint64 roleId);
            error AccessManagerBadConfirmation();
            error AccessManagerUnauthorizedAccount(address msgsender, uint64 roleId);
            error AccessManagerUnauthorizedCall(address caller, address target, bytes4 selector);
            error AccessManagerUnauthorizedConsume(address target);
            error AccessManagerUnauthorizedCancel(address msgsender, address caller, address target, bytes4 selector);
            error AccessManagerInvalidInitialAdmin(address initialAdmin);
        
            /**
             * @dev Check if an address (`caller`) is authorised to call a given function on a given contract directly (with
             * no restriction). Additionally, it returns the delay needed to perform the call indirectly through the {schedule}
             * & {execute} workflow.
             *
             * This function is usually called by the targeted contract to control immediate execution of restricted functions.
             * Therefore we only return true if the call can be performed without any delay. If the call is subject to a
             * previously set delay (not zero), then the function should return false and the caller should schedule the operation
             * for future execution.
             *
             * If `immediate` is true, the delay can be disregarded and the operation can be immediately executed, otherwise
             * the operation can be executed if and only if delay is greater than 0.
             *
             * NOTE: The IAuthority interface does not include the `uint32` delay. This is an extension of that interface that
             * is backward compatible. Some contracts may thus ignore the second return argument. In that case they will fail
             * to identify the indirect workflow, and will consider calls that require a delay to be forbidden.
             *
             * NOTE: This function does not report the permissions of this manager itself. These are defined by the
             * {_canCallSelf} function instead.
             */
            function canCall(
                address caller,
                address target,
                bytes4 selector
            ) external view returns (bool allowed, uint32 delay);
        
            /**
             * @dev Expiration delay for scheduled proposals. Defaults to 1 week.
             *
             * IMPORTANT: Avoid overriding the expiration with 0. Otherwise every contract proposal will be expired immediately,
             * disabling any scheduling usage.
             */
            function expiration() external view returns (uint32);
        
            /**
             * @dev Minimum setback for all delay updates, with the exception of execution delays. It
             * can be increased without setback (and reset via {revokeRole} in the case event of an
             * accidental increase). Defaults to 5 days.
             */
            function minSetback() external view returns (uint32);
        
            /**
             * @dev Get whether the contract is closed disabling any access. Otherwise role permissions are applied.
             */
            function isTargetClosed(address target) external view returns (bool);
        
            /**
             * @dev Get the role required to call a function.
             */
            function getTargetFunctionRole(address target, bytes4 selector) external view returns (uint64);
        
            /**
             * @dev Get the admin delay for a target contract. Changes to contract configuration are subject to this delay.
             */
            function getTargetAdminDelay(address target) external view returns (uint32);
        
            /**
             * @dev Get the id of the role that acts as an admin for the given role.
             *
             * The admin permission is required to grant the role, revoke the role and update the execution delay to execute
             * an operation that is restricted to this role.
             */
            function getRoleAdmin(uint64 roleId) external view returns (uint64);
        
            /**
             * @dev Get the role that acts as a guardian for a given role.
             *
             * The guardian permission allows canceling operations that have been scheduled under the role.
             */
            function getRoleGuardian(uint64 roleId) external view returns (uint64);
        
            /**
             * @dev Get the role current grant delay.
             *
             * Its value may change at any point without an event emitted following a call to {setGrantDelay}.
             * Changes to this value, including effect timepoint are notified in advance by the {RoleGrantDelayChanged} event.
             */
            function getRoleGrantDelay(uint64 roleId) external view returns (uint32);
        
            /**
             * @dev Get the access details for a given account for a given role. These details include the timepoint at which
             * membership becomes active, and the delay applied to all operation by this user that requires this permission
             * level.
             *
             * Returns:
             * [0] Timestamp at which the account membership becomes valid. 0 means role is not granted.
             * [1] Current execution delay for the account.
             * [2] Pending execution delay for the account.
             * [3] Timestamp at which the pending execution delay will become active. 0 means no delay update is scheduled.
             */
            function getAccess(uint64 roleId, address account) external view returns (uint48, uint32, uint32, uint48);
        
            /**
             * @dev Check if a given account currently has the permission level corresponding to a given role. Note that this
             * permission might be associated with an execution delay. {getAccess} can provide more details.
             */
            function hasRole(uint64 roleId, address account) external view returns (bool, uint32);
        
            /**
             * @dev Give a label to a role, for improved role discoverability by UIs.
             *
             * Requirements:
             *
             * - the caller must be a global admin
             *
             * Emits a {RoleLabel} event.
             */
            function labelRole(uint64 roleId, string calldata label) external;
        
            /**
             * @dev Add `account` to `roleId`, or change its execution delay.
             *
             * This gives the account the authorization to call any function that is restricted to this role. An optional
             * execution delay (in seconds) can be set. If that delay is non 0, the user is required to schedule any operation
             * that is restricted to members of this role. The user will only be able to execute the operation after the delay has
             * passed, before it has expired. During this period, admin and guardians can cancel the operation (see {cancel}).
             *
             * If the account has already been granted this role, the execution delay will be updated. This update is not
             * immediate and follows the delay rules. For example, if a user currently has a delay of 3 hours, and this is
             * called to reduce that delay to 1 hour, the new delay will take some time to take effect, enforcing that any
             * operation executed in the 3 hours that follows this update was indeed scheduled before this update.
             *
             * Requirements:
             *
             * - the caller must be an admin for the role (see {getRoleAdmin})
             * - granted role must not be the `PUBLIC_ROLE`
             *
             * Emits a {RoleGranted} event.
             */
            function grantRole(uint64 roleId, address account, uint32 executionDelay) external;
        
            /**
             * @dev Remove an account from a role, with immediate effect. If the account does not have the role, this call has
             * no effect.
             *
             * Requirements:
             *
             * - the caller must be an admin for the role (see {getRoleAdmin})
             * - revoked role must not be the `PUBLIC_ROLE`
             *
             * Emits a {RoleRevoked} event if the account had the role.
             */
            function revokeRole(uint64 roleId, address account) external;
        
            /**
             * @dev Renounce role permissions for the calling account with immediate effect. If the sender is not in
             * the role this call has no effect.
             *
             * Requirements:
             *
             * - the caller must be `callerConfirmation`.
             *
             * Emits a {RoleRevoked} event if the account had the role.
             */
            function renounceRole(uint64 roleId, address callerConfirmation) external;
        
            /**
             * @dev Change admin role for a given role.
             *
             * Requirements:
             *
             * - the caller must be a global admin
             *
             * Emits a {RoleAdminChanged} event
             */
            function setRoleAdmin(uint64 roleId, uint64 admin) external;
        
            /**
             * @dev Change guardian role for a given role.
             *
             * Requirements:
             *
             * - the caller must be a global admin
             *
             * Emits a {RoleGuardianChanged} event
             */
            function setRoleGuardian(uint64 roleId, uint64 guardian) external;
        
            /**
             * @dev Update the delay for granting a `roleId`.
             *
             * Requirements:
             *
             * - the caller must be a global admin
             *
             * Emits a {RoleGrantDelayChanged} event.
             */
            function setGrantDelay(uint64 roleId, uint32 newDelay) external;
        
            /**
             * @dev Set the role required to call functions identified by the `selectors` in the `target` contract.
             *
             * Requirements:
             *
             * - the caller must be a global admin
             *
             * Emits a {TargetFunctionRoleUpdated} event per selector.
             */
            function setTargetFunctionRole(address target, bytes4[] calldata selectors, uint64 roleId) external;
        
            /**
             * @dev Set the delay for changing the configuration of a given target contract.
             *
             * Requirements:
             *
             * - the caller must be a global admin
             *
             * Emits a {TargetAdminDelayUpdated} event.
             */
            function setTargetAdminDelay(address target, uint32 newDelay) external;
        
            /**
             * @dev Set the closed flag for a contract.
             *
             * Requirements:
             *
             * - the caller must be a global admin
             *
             * Emits a {TargetClosed} event.
             */
            function setTargetClosed(address target, bool closed) external;
        
            /**
             * @dev Return the timepoint at which a scheduled operation will be ready for execution. This returns 0 if the
             * operation is not yet scheduled, has expired, was executed, or was canceled.
             */
            function getSchedule(bytes32 id) external view returns (uint48);
        
            /**
             * @dev Return the nonce for the latest scheduled operation with a given id. Returns 0 if the operation has never
             * been scheduled.
             */
            function getNonce(bytes32 id) external view returns (uint32);
        
            /**
             * @dev Schedule a delayed operation for future execution, and return the operation identifier. It is possible to
             * choose the timestamp at which the operation becomes executable as long as it satisfies the execution delays
             * required for the caller. The special value zero will automatically set the earliest possible time.
             *
             * Returns the `operationId` that was scheduled. Since this value is a hash of the parameters, it can reoccur when
             * the same parameters are used; if this is relevant, the returned `nonce` can be used to uniquely identify this
             * scheduled operation from other occurrences of the same `operationId` in invocations of {execute} and {cancel}.
             *
             * Emits a {OperationScheduled} event.
             *
             * NOTE: It is not possible to concurrently schedule more than one operation with the same `target` and `data`. If
             * this is necessary, a random byte can be appended to `data` to act as a salt that will be ignored by the target
             * contract if it is using standard Solidity ABI encoding.
             */
            function schedule(address target, bytes calldata data, uint48 when) external returns (bytes32, uint32);
        
            /**
             * @dev Execute a function that is delay restricted, provided it was properly scheduled beforehand, or the
             * execution delay is 0.
             *
             * Returns the nonce that identifies the previously scheduled operation that is executed, or 0 if the
             * operation wasn't previously scheduled (if the caller doesn't have an execution delay).
             *
             * Emits an {OperationExecuted} event only if the call was scheduled and delayed.
             */
            function execute(address target, bytes calldata data) external payable returns (uint32);
        
            /**
             * @dev Cancel a scheduled (delayed) operation. Returns the nonce that identifies the previously scheduled
             * operation that is cancelled.
             *
             * Requirements:
             *
             * - the caller must be the proposer, a guardian of the targeted function, or a global admin
             *
             * Emits a {OperationCanceled} event.
             */
            function cancel(address caller, address target, bytes calldata data) external returns (uint32);
        
            /**
             * @dev Consume a scheduled operation targeting the caller. If such an operation exists, mark it as consumed
             * (emit an {OperationExecuted} event and clean the state). Otherwise, throw an error.
             *
             * This is useful for contract that want to enforce that calls targeting them were scheduled on the manager,
             * with all the verifications that it implies.
             *
             * Emit a {OperationExecuted} event.
             */
            function consumeScheduledOp(address caller, bytes calldata data) external;
        
            /**
             * @dev Hashing function for delayed operations.
             */
            function hashOperation(address caller, address target, bytes calldata data) external view returns (bytes32);
        
            /**
             * @dev Changes the authority of a target managed by this manager instance.
             *
             * Requirements:
             *
             * - the caller must be a global admin
             */
            function updateAuthority(address target, address newAuthority) external;
        }
        
        // node_modules/@openzeppelin/contracts/access/manager/AccessManaged.sol
        
        // OpenZeppelin Contracts (last updated v5.0.0) (access/manager/AccessManaged.sol)
        
        /**
         * @dev This contract module makes available a {restricted} modifier. Functions decorated with this modifier will be
         * permissioned according to an "authority": a contract like {AccessManager} that follows the {IAuthority} interface,
         * implementing a policy that allows certain callers to access certain functions.
         *
         * IMPORTANT: The `restricted` modifier should never be used on `internal` functions, judiciously used in `public`
         * functions, and ideally only used in `external` functions. See {restricted}.
         */
        abstract contract AccessManaged is Context, IAccessManaged {
            address private _authority;
        
            bool private _consumingSchedule;
        
            /**
             * @dev Initializes the contract connected to an initial authority.
             */
            constructor(address initialAuthority) {
                _setAuthority(initialAuthority);
            }
        
            /**
             * @dev Restricts access to a function as defined by the connected Authority for this contract and the
             * caller and selector of the function that entered the contract.
             *
             * [IMPORTANT]
             * ====
             * In general, this modifier should only be used on `external` functions. It is okay to use it on `public`
             * functions that are used as external entry points and are not called internally. Unless you know what you're
             * doing, it should never be used on `internal` functions. Failure to follow these rules can have critical security
             * implications! This is because the permissions are determined by the function that entered the contract, i.e. the
             * function at the bottom of the call stack, and not the function where the modifier is visible in the source code.
             * ====
             *
             * [WARNING]
             * ====
             * Avoid adding this modifier to the https://docs.soliditylang.org/en/v0.8.20/contracts.html#receive-ether-function[`receive()`]
             * function or the https://docs.soliditylang.org/en/v0.8.20/contracts.html#fallback-function[`fallback()`]. These
             * functions are the only execution paths where a function selector cannot be unambiguosly determined from the calldata
             * since the selector defaults to `0x00000000` in the `receive()` function and similarly in the `fallback()` function
             * if no calldata is provided. (See {_checkCanCall}).
             *
             * The `receive()` function will always panic whereas the `fallback()` may panic depending on the calldata length.
             * ====
             */
            modifier restricted() {
                _checkCanCall(_msgSender(), _msgData());
                _;
            }
        
            /// @inheritdoc IAccessManaged
            function authority() public view virtual returns (address) {
                return _authority;
            }
        
            /// @inheritdoc IAccessManaged
            function setAuthority(address newAuthority) public virtual {
                address caller = _msgSender();
                if (caller != authority()) {
                    revert AccessManagedUnauthorized(caller);
                }
                if (newAuthority.code.length == 0) {
                    revert AccessManagedInvalidAuthority(newAuthority);
                }
                _setAuthority(newAuthority);
            }
        
            /// @inheritdoc IAccessManaged
            function isConsumingScheduledOp() public view returns (bytes4) {
                return _consumingSchedule ? this.isConsumingScheduledOp.selector : bytes4(0);
            }
        
            /**
             * @dev Transfers control to a new authority. Internal function with no access restriction. Allows bypassing the
             * permissions set by the current authority.
             */
            function _setAuthority(address newAuthority) internal virtual {
                _authority = newAuthority;
                emit AuthorityUpdated(newAuthority);
            }
        
            /**
             * @dev Reverts if the caller is not allowed to call the function identified by a selector. Panics if the calldata
             * is less than 4 bytes long.
             */
            function _checkCanCall(address caller, bytes calldata data) internal virtual {
                (bool immediate, uint32 delay) = AuthorityUtils.canCallWithDelay(
                    authority(),
                    caller,
                    address(this),
                    bytes4(data[0:4])
                );
                if (!immediate) {
                    if (delay > 0) {
                        _consumingSchedule = true;
                        IAccessManager(authority()).consumeScheduledOp(caller, data);
                        _consumingSchedule = false;
                    } else {
                        revert AccessManagedUnauthorized(caller);
                    }
                }
            }
        }
        
        // node_modules/rave/src/RAVE.sol
        
        /**
         * @title RAVE
         * @author PufferFinance
         * @custom:security-contact security@puffer.fi
         * @notice RAVe is a smart contract for verifying Remote Attestation evidence.
         */
        contract RAVE is RAVEBase, JSONBuilder {
            using BytesUtils for *;
        
            constructor() { }
        
            /**
             * @inheritdoc RAVEBase
             */
            function verifyRemoteAttestation(
                bytes calldata report,
                bytes calldata sig,
                bytes memory signingMod,
                bytes memory signingExp,
                bytes32 mrenclave,
                bytes32 mrsigner
            ) public view override returns (bytes memory payload) {
                // Decode the encoded report JSON values to a Values struct and reconstruct the original JSON string
                (Values memory reportValues, bytes memory reportBytes) = _buildReportBytes(report);
        
                // Verify the report was signed by the SigningPK
                if (!verifyReportSignature(reportBytes, sig, signingMod, signingExp)) {
                    revert BadReportSignature();
                }
        
                // Verify the report's contents match the expected
                payload = _verifyReportContents(reportValues, mrenclave, mrsigner);
            }
        
            /**
             * @inheritdoc RAVEBase
             */
            function rave(
                bytes calldata report,
                bytes calldata sig,
                bytes memory leafX509Cert,
                bytes memory signingMod,
                bytes memory signingExp,
                bytes32 mrenclave,
                bytes32 mrsigner
            ) public view override returns (bytes memory payload) {
                // Verify the leafX509Cert was signed with signingMod and signingExp
                (bytes memory leafCertModulus, bytes memory leafCertExponent) =
                    X509Verifier.verifySignedX509(leafX509Cert, signingMod, signingExp);
        
                // Verify report has expected fields then extract its payload
                payload = verifyRemoteAttestation(report, sig, leafCertModulus, leafCertExponent, mrenclave, mrsigner);
            }
        
            /*
            * @dev Builds the JSON report string from the abi-encoded `encodedReportValues`. The assumption is that `isvEnclaveQuoteBody` value was previously base64 decoded off-chain and needs to be base64 encoded to produce the message-to-be-signed.
            * @param encodedReportValues The values from the attestation evidence report JSON from IAS.
            * @return reportValues The JSON values as a Values struct for easier processing downstream
            * @return reportBytes The exact message-to-be-signed
            */
            function _buildReportBytes(bytes memory encodedReportValues)
                internal
                pure
                returns (Values memory reportValues, bytes memory reportBytes)
            {
                // Decode the report JSON values
                (
                    bytes memory id,
                    bytes memory timestamp,
                    bytes memory version,
                    bytes memory epidPseudonym,
                    bytes memory advisoryURL,
                    bytes memory advisoryIDs,
                    bytes memory isvEnclaveQuoteStatus,
                    bytes memory isvEnclaveQuoteBody
                ) = abi.decode(encodedReportValues, (bytes, bytes, bytes, bytes, bytes, bytes, bytes, bytes));
        
                // Assumes the quote body was already decoded off-chain
                bytes memory encBody = bytes(Base64.encode(isvEnclaveQuoteBody));
        
                // Pack values to struct
                reportValues = JSONBuilder.Values(
                    id, timestamp, version, epidPseudonym, advisoryURL, advisoryIDs, isvEnclaveQuoteStatus, encBody
                );
        
                // Reconstruct the JSON report that was signed
                reportBytes = bytes(buildJSON(reportValues));
        
                // Pass on the decoded value for later processing
                reportValues.isvEnclaveQuoteBody = isvEnclaveQuoteBody;
            }
        
            /*
            * @dev Parses a report, verifies the fields are correctly set, and extracts the enclave' 64 byte commitment.
            * @param reportValues The values from the attestation evidence report JSON from IAS.
            * @param mrenclave The expected enclave measurement.
            * @param mrsigner The expected enclave signer.
            * @return The 64 byte payload if the mrenclave and mrsigner values were correctly set.
            */
            function _verifyReportContents(Values memory reportValues, bytes32 mrenclave, bytes32 mrsigner)
                internal
                pure
                returns (bytes memory payload)
            {
                // check enclave status
                bytes32 status = keccak256(reportValues.isvEnclaveQuoteStatus);
                require(status == OK_STATUS || status == HARDENING_STATUS, "bad isvEnclaveQuoteStatus");
        
                // quote body is already base64 decoded
                bytes memory quoteBody = reportValues.isvEnclaveQuoteBody;
                assert(quoteBody.length == QUOTE_BODY_LENGTH);
        
                // Verify report's MRENCLAVE matches the expected
                bytes32 mre = quoteBody.readBytes32(MRENCLAVE_OFFSET);
                require(mre == mrenclave);
        
                // Verify report's MRSIGNER matches the expected
                bytes32 mrs = quoteBody.readBytes32(MRSIGNER_OFFSET);
                require(mrs == mrsigner);
        
                // Verify report's <= 64B payload matches the expected
                payload = quoteBody.substring(PAYLOAD_OFFSET, PAYLOAD_SIZE);
            }
        }
        
        // src/EnclaveVerifier.sol
        
        /**
         * @title EnclaveVerifier
         * @author Puffer Finance
         * @custom:security-contact security@puffer.fi
         */
        contract EnclaveVerifier is IEnclaveVerifier, AccessManaged, RAVE {
            /**
             * @dev RSA Public key for Intel: https://api.portal.trustedservices.intel.com/content/documentation.html
             */
            bytes internal constant _INTEL_RSA_MODULUS =
                hex"9F3C647EB5773CBB512D2732C0D7415EBB55A0FA9EDE2E649199E6821DB910D53177370977466A6A5E4786CCD2DDEBD4149D6A2F6325529DD10CC98737B0779C1A07E29C47A1AE004948476C489F45A5A15D7AC8ECC6ACC645ADB43D87679DF59C093BC5A2E9696C5478541B979E754B573914BE55D32FF4C09DDF27219934CD990527B3F92ED78FBF29246ABECB71240EF39C2D7107B447545A7FFB10EB060A68A98580219E36910952683892D6A5E2A80803193E407531404E36B315623799AA825074409754A2DFE8F5AFD5FE631E1FC2AF3808906F28A790D9DD9FE060939B125790C5805D037DF56A99531B96DE69DE33ED226CC1207D1042B5C9AB7F404FC711C0FE4769FB9578B1DC0EC469EA1A25E0FF9914886EF2699B235BB4847DD6FF40B606E6170793C2FB98B314587F9CFD257362DFEAB10B3BD2D97673A1A4BD44C453AAF47FC1F2D3D0F384F74A06F89C089F0DA6CDB7FCEEE8C9821A8E54F25C0416D18C46839A5F8012FBDD3DC74D256279ADC2C0D55AFF6F0622425D1B";
            bytes internal constant _INTEL_EXPONENT = hex"010001";
        
            /**
             * @notice Freshness number of blocks
             */
            uint256 public immutable FRESHNESS_BLOCKS;
        
            /**
             * @dev Mapping from keccak'd leaf x509 to RSA pub key components
             * leafHash -> pubKey
             */
            mapping(bytes32 leafHash => RSAPubKey pubKey) internal _validLeafX509s;
        
            constructor(uint256 freshnessBlocks, address accessManager) AccessManaged(accessManager) {
                if (address(accessManager) == address(0)) {
                    revert InvalidAddress();
                }
                FRESHNESS_BLOCKS = freshnessBlocks;
            }
        
            /**
             * @inheritdoc IEnclaveVerifier
             */
            function getIntelRootCAPubKey() external pure returns (RSAPubKey memory) {
                return RSAPubKey({ modulus: _INTEL_RSA_MODULUS, exponent: _INTEL_EXPONENT });
            }
        
            /**
             * @inheritdoc IEnclaveVerifier
             */
            function addLeafX509(bytes calldata leafX509Cert) external {
                (bytes memory leafCertModulus, bytes memory leafCertExponent) =
                    X509Verifier.verifySignedX509(leafX509Cert, _INTEL_RSA_MODULUS, _INTEL_EXPONENT);
        
                bytes32 hashedCert = keccak256(leafX509Cert);
        
                _validLeafX509s[hashedCert] = RSAPubKey({ modulus: leafCertModulus, exponent: leafCertExponent });
        
                emit AddedPubKey(hashedCert);
            }
        
            /**
             * @notice Removes a whitelisted leaf x509 RSA public key
             */
            function removeLeafX509(bytes32 hashedCert) external restricted {
                delete _validLeafX509s[hashedCert].modulus;
                delete _validLeafX509s[hashedCert].exponent;
                emit RemovedPubKey(hashedCert);
            }
        
            /**
             * @inheritdoc IEnclaveVerifier
             */
            function verifyEvidence(
                uint256 blockNumber,
                bytes32 raveCommitment,
                RaveEvidence calldata evidence,
                bytes32 mrenclave,
                bytes32 mrsigner
            ) external view returns (bool) {
                // Check for freshness
                if ((block.number - blockNumber) > FRESHNESS_BLOCKS) {
                    revert StaleEvidence();
                }
        
                RSAPubKey memory leafX509 = _validLeafX509s[evidence.leafX509CertDigest];
        
                // Recover a remote attestation payload if everything is valid
                bytes memory recoveredPayload = verifyRemoteAttestation({
                    report: evidence.report,
                    sig: evidence.signature,
                    signingMod: leafX509.modulus,
                    signingExp: leafX509.exponent,
                    mrenclave: mrenclave,
                    mrsigner: mrsigner
                });
        
                // Remote attestation payloads are expected to be in the form (32B_Commitment || 32B_BlockHash)
                bytes memory expectedPayload = abi.encode(raveCommitment, blockhash(blockNumber));
        
                // Compare with the expected payload
                return (keccak256(expectedPayload) == keccak256(recoveredPayload));
            }
        }
        
        // src/interface/IGuardianModule.sol
        
        /**
         * @title IGuardianModule interface
         * @author Puffer Finance
         */
        interface IGuardianModule {
            /**
             * @notice Thrown when the ECDSA public key is not valid
             * @dev Signature "0xe3eece5a"
             */
            error InvalidECDSAPubKey();
        
            /**
             * @notice Thrown when the RAVE evidence is not valid
             * @dev Signature "0x2b3c629b"
             */
            error InvalidRAVE();
        
            /**
             * @notice Thrown if the threshold value is not valid
             * @dev Signature "0x651a749b"
             */
            error InvalidThreshold(uint256 threshold);
        
            /**
             * @notice Emitted when the ejection threshold is changed
             * @param oldThreshold is the old threshold value
             * @param newThreshold is the new threshold value
             * @dev Signature "0x4ae5122a691bf14917d273c6a81956e1f521b3e39f2d0c6d963117bf9c820e83"
             */
            event EjectionThresholdChanged(uint256 oldThreshold, uint256 newThreshold);
        
            /**
             * @notice Emitted when the threshold value for guardian signatures is changed
             * @param oldThreshold is the old threshold value
             * @param newThreshold is the new threshold value
             * @dev Signature "0x3164947cf0f49f08dd0cd80e671535b1e11590d347c55dcaa97ba3c24a96b33a"
             */
            event ThresholdChanged(uint256 oldThreshold, uint256 newThreshold);
        
            /**
             * @notice Emitted when a guardian is added to the module
             * @param guardian The address of the guardian added
             * @dev Signature "0x038596bb31e2e7d3d9f184d4c98b310103f6d7f5830e5eec32bffe6f1728f969"
             */
            event GuardianAdded(address guardian);
        
            /**
             * @notice Emitted when a guardian is removed from the module
             * @param guardian The address of the guardian removed
             * @dev Signature "0xb8107d0c6b40be480ce3172ee66ba6d64b71f6b1685a851340036e6e2e3e3c52"
             */
            event GuardianRemoved(address guardian);
        
            /**
             * @notice Emitted when the guardian changes guardian enclave address
             * @param guardian is the address outside of the enclave
             * @param guardianEnclave is the enclave address
             * @param pubKey is the public key
             * @dev Signature "0x14720919b20fceff2a396c4973d37c6087e4619d40c8f4003d8e44ee127461a2"
             */
            event RotatedGuardianKey(address guardian, address guardianEnclave, bytes pubKey);
        
            /**
             * @notice Emitted when the mrenclave value is changed
             * @dev Signature "0x1ff2c57ef9a384cea0c482d61fec8d708967d266f03266e301c6786f7209904a"
             */
            event MrEnclaveChanged(bytes32 oldMrEnclave, bytes32 newMrEnclave);
        
            /**
             * @notice Emitted when the mrsigner value is changed
             * @dev Signature "0x1a1fe271c5533136fccd1c6df515ca1f227d95822bfe78b9dd93debf3d709ae6"
             */
            event MrSignerChanged(bytes32 oldMrSigner, bytes32 newMrSigner);
        
            /**
             * @notice Returns the enclave address registered to `guardian`
             */
            function getGuardiansEnclaveAddress(address guardian) external view returns (address);
        
            /**
             * @notice Returns the ejection threshold ETH value
             * @dev The ejection threshold is the minimum amount of ETH on the beacon chain required do the validation duties
             * If it drops below this value, the validator will be ejected
             * It is more likely that the validator will run out of Validator Tickets before its balance drops below this value
             * @return The ejection threshold value
             */
            function getEjectionThreshold() external view returns (uint256);
        
            /**
             * @notice Sets the values for mrEnclave and mrSigner to `newMrenclave` and `newMrsigner`
             */
            function setGuardianEnclaveMeasurements(bytes32 newMrenclave, bytes32 newMrsigner) external;
        
            /**
             * @notice Validates the update of the number of validators
             */
            function validateTotalNumberOfValidators(
                uint256 newNumberOfValidators,
                uint256 epochNumber,
                bytes[] calldata guardianEOASignatures
            ) external view;
        
            /**
             * @notice Returns the enclave verifier
             */
            function ENCLAVE_VERIFIER() external view returns (IEnclaveVerifier);
        
            /**
             * @notice Validates the batch withdrawals calldata
             * @dev The order of the signatures is important
             * The order of the signatures MUST the same as the order of the validators in the validator module
             * @param validatorInfos The information of the stopped validators
             * @param guardianEOASignatures The guardian EOA signatures
             */
            function validateBatchWithdrawals(
                StoppedValidatorInfo[] calldata validatorInfos,
                bytes[] calldata guardianEOASignatures
            ) external;
        
            /**
             * @notice Validates the node provisioning calldata
             * @dev The order of the signatures is important
             * The order of the signatures MUST the same as the order of the guardians in the guardian module
             * @param pufferModuleIndex is the validator index in Puffer
             * @param pubKey The public key
             * @param signature The signature
             * @param withdrawalCredentials The withdrawal credentials
             * @param depositDataRoot The deposit data root
             * @param guardianEnclaveSignatures The guardian enclave signatures
             */
            function validateProvisionNode(
                uint256 pufferModuleIndex,
                bytes memory pubKey,
                bytes calldata signature,
                bytes calldata withdrawalCredentials,
                bytes32 depositDataRoot,
                bytes[] calldata guardianEnclaveSignatures
            ) external view;
        
            /**
             * @notice Validates the skipping of provisioning for a specific module
             * @param moduleName The name of the module
             * @param skippedIndex The index of the skipped provisioning
             * @param guardianEOASignatures The guardian EOA signatures
             */
            function validateSkipProvisioning(bytes32 moduleName, uint256 skippedIndex, bytes[] calldata guardianEOASignatures)
                external
                view;
        
            /**
             * @notice Returns the threshold value for guardian signatures
             * @dev The threshold value is the minimum number of guardian signatures required for a transaction to be considered valid
             * @return The threshold value
             */
            function getThreshold() external view returns (uint256);
        
            /**
             * @notice Returns the list of guardians
             * @dev This function returns an array of addresses representing the guardians
             * @return An array of addresses representing the guardians
             */
            function getGuardians() external view returns (address[] memory);
        
            /**
             * @notice Adds a new guardian to the module
             * @dev Restricted to the DAO
             * @param newGuardian The address of the new guardian to add
             */
            function addGuardian(address newGuardian) external;
        
            /**
             * @notice Removes a guardian from the module
             * @dev Restricted to the DAO
             * @param guardian The address of the guardian to remove
             */
            function removeGuardian(address guardian) external;
        
            /**
             * @notice Changes the threshold value for the guardian signatures
             * @dev Restricted to the DAO
             * @param newThreshold The new threshold value
             */
            function setThreshold(uint256 newThreshold) external;
        
            /**
             * @notice Changes the ejection threshold value
             * @dev Restricted to the DAO
             * @param newThreshold The new threshold value
             */
            function setEjectionThreshold(uint256 newThreshold) external;
        
            /**
             * @dev Validates the signatures of the guardians' enclave signatures
             * @param enclaveSignatures The array of enclave signatures
             * @param signedMessageHash The hash of the signed message
             * @return A boolean indicating whether the signatures are valid
             */
            function validateGuardiansEnclaveSignatures(bytes[] calldata enclaveSignatures, bytes32 signedMessageHash)
                external
                view
                returns (bool);
        
            /**
             * @dev Validates the signatures of the guardians' EOAs.
             * @param eoaSignatures The array of EOAs' signatures.
             * @param signedMessageHash The hash of the signed message.
             * @return A boolean indicating whether the signatures are valid.
             */
            function validateGuardiansEOASignatures(bytes[] calldata eoaSignatures, bytes32 signedMessageHash)
                external
                view
                returns (bool);
        
            /**
             * @notice Rotates guardian's key
             * @dev If he caller is not a valid guardian or if the RAVE evidence is not valid the tx will revert
             * @param blockNumber is the block number
             * @param pubKey is the public key of the new signature
             * @param evidence is the RAVE evidence
             */
            function rotateGuardianKey(uint256 blockNumber, bytes calldata pubKey, RaveEvidence calldata evidence) external;
        
            /**
             * @notice Returns the guardians enclave addresses
             */
            function getGuardiansEnclaveAddresses() external view returns (address[] memory);
        
            /**
             * @notice Returns the guardians enclave public keys
             */
            function getGuardiansEnclavePubkeys() external view returns (bytes[] memory);
        
            /**
             * @notice Checks if an account is a guardian
             * @param account The address to check
             * @return A boolean indicating whether the account is a guardian
             */
            function isGuardian(address account) external view returns (bool);
        
            /**
             * @notice Returns the mrenclave value
             */
            function getMrenclave() external view returns (bytes32);
        
            /**
             * @notice Returns the mrsigner value
             */
            function getMrsigner() external view returns (bytes32);
        }
        
        // src/PufferOracleV2.sol
        
        /**
         * @title PufferOracle
         * @author Puffer Finance
         * @custom:security-contact security@puffer.fi
         */
        contract PufferOracleV2 is IPufferOracleV2, AccessManaged {
            /**
             * @dev Burst threshold
             */
            uint256 internal constant _BURST_THRESHOLD = 22;
        
            /**
             * @notice Guardian Module
             */
            IGuardianModule public immutable GUARDIAN_MODULE;
        
            /**
             * @notice Puffer Vault
             */
            address payable public immutable PUFFER_VAULT;
        
            /**
             * @dev Number of active Puffer validators
             * Slot 0
             */
            uint256 internal _numberOfActivePufferValidators;
        
            /**
             * @dev Total number of Validators
             * Slot 1
             */
            uint256 internal _totalNumberOfValidators;
            /**
             * @dev Epoch number of the update
             * Slot 2
             */
            uint256 internal _epochNumber;
        
            /**
             * @dev Price in wei to mint one Validator Ticket
             * Slot 3
             */
            uint256 internal _validatorTicketPrice;
        
            constructor(IGuardianModule guardianModule, address payable vault, address accessManager)
                AccessManaged(accessManager)
            {
                GUARDIAN_MODULE = guardianModule;
                PUFFER_VAULT = vault;
                _totalNumberOfValidators = 927122; // Oracle will be updated with the correct value
                _epochNumber = 268828; // Oracle will be updated with the correct value
                _setMintPrice(0.01 ether);
            }
        
            /**
             * @notice Exits the validator from the Beacon chain
             * @dev Restricted to PufferProtocol contract
             */
            function exitValidators(uint256 numberOfExits) public restricted {
                _numberOfActivePufferValidators -= numberOfExits;
                emit NumberOfActiveValidators(_numberOfActivePufferValidators);
            }
        
            /**
             * @notice Increases the locked eth amount amount on the Oracle by 32 ETH
             * It is called when the Beacon chain receives a new deposit from PufferProtocol
             * The PufferVault balance is decreased by the same amount
             * @dev Restricted to PufferProtocol contract
             */
            function provisionNode() external restricted {
                unchecked {
                    ++_numberOfActivePufferValidators;
                }
                emit NumberOfActiveValidators(_numberOfActivePufferValidators);
            }
        
            /**
             * @notice Updates the price to mint VT
             * @param newPrice The new price to set for minting VT
             * @dev Restricted to the DAO
             */
            function setMintPrice(uint256 newPrice) external restricted {
                _setMintPrice(newPrice);
            }
        
            /**
             * @notice Updates the total number of validators
             * @param newTotalNumberOfValidators The new number of validators
             */
            function setTotalNumberOfValidators(
                uint256 newTotalNumberOfValidators,
                uint256 epochNumber,
                bytes[] calldata guardianEOASignatures
            ) external restricted {
                if (epochNumber <= _epochNumber) {
                    revert InvalidUpdate();
                }
                GUARDIAN_MODULE.validateTotalNumberOfValidators(newTotalNumberOfValidators, epochNumber, guardianEOASignatures);
                emit TotalNumberOfValidatorsUpdated(_totalNumberOfValidators, newTotalNumberOfValidators, epochNumber);
                _totalNumberOfValidators = newTotalNumberOfValidators;
                _epochNumber = epochNumber;
            }
        
            /**
             * @inheritdoc IPufferOracle
             */
            function getLockedEthAmount() external view returns (uint256) {
                return _numberOfActivePufferValidators * 32 ether;
            }
        
            /**
             * @inheritdoc IPufferOracleV2
             */
            function getTotalNumberOfValidators() external view returns (uint256) {
                return _totalNumberOfValidators;
            }
        
            /**
             * @inheritdoc IPufferOracle
             */
            function isOverBurstThreshold() external view returns (bool) {
                return ((_numberOfActivePufferValidators * 100 / _totalNumberOfValidators) > _BURST_THRESHOLD);
            }
        
            /**
             * @inheritdoc IPufferOracle
             */
            function getValidatorTicketPrice() external view returns (uint256) {
                return _validatorTicketPrice;
            }
        
            /**
             * @inheritdoc IPufferOracleV2
             */
            function getNumberOfActiveValidators() external view returns (uint256) {
                return _numberOfActivePufferValidators;
            }
        
            function _setMintPrice(uint256 newPrice) internal {
                emit ValidatorTicketMintPriceUpdated(_validatorTicketPrice, newPrice);
                _validatorTicketPrice = newPrice;
            }
        }
        
        // src/ValidatorTicketPricer.sol
        
        /**
         * @title Validator Ticket Pricer
         * @notice This contract manages the pricing of validator tickets based on MEV payouts and consensus rewards.
         * @dev Uses PufferOracleV2 for price updates and inherits access control from AccessManaged.
         */
        contract ValidatorTicketPricer is AccessManaged, IValidatorTicketPricer {
            uint256 internal constant _BPS_DECIMALS = 1e4; // 100%
        
            PufferOracleV2 internal immutable _ORACLE;
        
            // slot 0
            uint16 internal _dailyMevPayoutsChangeToleranceBps; // max value 655%
            uint16 internal _dailyConsensusRewardsChangeToleranceBps; // max value 655%
            uint16 internal _discountRateBps;
        
            uint104 internal _dailyMevPayouts; // max value is 20282409603651 ETH
            uint104 internal _dailyConsensusRewards; // max value is 20282409603651 ETH
        
            /**
             * @notice Constructor sets the oracle and access manager
             * @param oracle The PufferOracleV2 contract address
             * @param accessManager The address of the access manager contract
             */
            constructor(PufferOracleV2 oracle, address accessManager) AccessManaged(accessManager) {
                _ORACLE = oracle;
            }
        
            /**
             * @inheritdoc IValidatorTicketPricer
             */
            function setDailyMevPayoutsChangeToleranceBps(uint16 newValue) external restricted {
                if (newValue > _BPS_DECIMALS) {
                    // only <= 100% allowed
                    revert InvalidValue();
                }
        
                emit DailyMevPayoutsChangeToleranceBPSUpdated(_dailyMevPayoutsChangeToleranceBps, newValue);
        
                _dailyMevPayoutsChangeToleranceBps = newValue;
            }
        
            /**
             * @inheritdoc IValidatorTicketPricer
             */
            function setDailyConsensusRewardsChangeToleranceBps(uint16 newValue) external restricted {
                if (newValue > _BPS_DECIMALS) {
                    // only <= 100% allowed
                    revert InvalidValue();
                }
        
                emit DailyConsensusRewardsChangeToleranceBPSUpdated(_dailyConsensusRewardsChangeToleranceBps, newValue);
        
                _dailyConsensusRewardsChangeToleranceBps = newValue;
            }
        
            /**
             * @inheritdoc IValidatorTicketPricer
             */
            function setDiscountRate(uint16 newValue) external restricted {
                if (newValue >= _BPS_DECIMALS) {
                    // only < 100% allowed
                    revert InvalidValue();
                }
        
                emit DiscountRateUpdated(_discountRateBps, newValue);
        
                _discountRateBps = newValue;
            }
        
            /**
             * @inheritdoc IValidatorTicketPricer
             */
            function setDailyMevPayouts(uint104 newValue) external restricted {
                _setDailyMevPayouts(newValue);
            }
        
            /**
             * @inheritdoc IValidatorTicketPricer
             */
            function setDailyConsensusRewards(uint104 newValue) external restricted {
                _setDailyConsensusRewards(newValue);
            }
        
            /**
             * @inheritdoc IValidatorTicketPricer
             */
            function postMintPrice() external restricted {
                _postMintPrice();
            }
        
            /**
             * @inheritdoc IValidatorTicketPricer
             */
            function setDailyRewardsAndPostMintPrice(uint104 dailyMevPayouts, uint104 dailyConsensusRewards)
                external
                restricted
            {
                _setDailyMevPayouts(dailyMevPayouts);
                _setDailyConsensusRewards(dailyConsensusRewards);
                _postMintPrice();
            }
        
            /**
             * @inheritdoc IValidatorTicketPricer
             */
            function getDailyMevPayoutsChangeToleranceBps() external view returns (uint16) {
                return _dailyMevPayoutsChangeToleranceBps;
            }
        
            /**
             * @inheritdoc IValidatorTicketPricer
             */
            function getDailyConsensusRewardsChangeToleranceBps() external view returns (uint16) {
                return _dailyConsensusRewardsChangeToleranceBps;
            }
        
            /**
             * @inheritdoc IValidatorTicketPricer
             */
            function getDiscountRateBps() external view returns (uint16) {
                return _discountRateBps;
            }
        
            /**
             * @inheritdoc IValidatorTicketPricer
             */
            function getDailyMevPayouts() external view returns (uint104) {
                return _dailyMevPayouts;
            }
        
            /**
             * @inheritdoc IValidatorTicketPricer
             */
            function getDailyConsensusRewards() external view returns (uint104) {
                return _dailyConsensusRewards;
            }
        
            /**
             * @notice Checks if the new price is within the allowed range
             * @param oldValue The old price
             * @param newValue The new price to set for minting VT
             * @param toleranceBps The allowed tolerance in basis points
             * @return true if the new price is within the allowed range
             */
            function _isWithinRange(uint104 oldValue, uint104 newValue, uint16 toleranceBps) internal pure returns (bool) {
                if (toleranceBps == 0) {
                    return true;
                }
        
                uint256 allowedDifference = (uint256(oldValue) * toleranceBps) / _BPS_DECIMALS;
        
                if (newValue > oldValue) {
                    return newValue <= oldValue + allowedDifference;
                }
        
                return newValue >= oldValue - allowedDifference;
            }
        
            /**
             * @notice Posts the mint price to the oracle
             * @dev Calculates the new price based on MEV payouts and consensus rewards, applies the discount rate, and updates the oracle
             */
            function _postMintPrice() internal {
                // casting _dailyMevPayouts + _dailyConsensusRewards so that the whole expression is converted to uint256
                uint256 newPrice = (
                    (_BPS_DECIMALS - _discountRateBps) * (uint256(_dailyMevPayouts) + uint256(_dailyConsensusRewards))
                ) / _BPS_DECIMALS;
                if (newPrice == 0) {
                    revert InvalidValue();
                }
        
                _ORACLE.setMintPrice(newPrice);
            }
        
            /**
             * @notice Sets the daily consensus rewards value
             * @param newValue The new daily consensus rewards value to set
             * @dev Checks if the new value is within the allowed range and emits an event
             */
            function _setDailyConsensusRewards(uint104 newValue) internal {
                uint104 oldValue = _dailyConsensusRewards;
        
                if (!_isWithinRange(oldValue, newValue, _dailyConsensusRewardsChangeToleranceBps)) {
                    revert InvalidValue();
                }
        
                emit DailyConsensusRewardsUpdated(oldValue, newValue);
        
                _dailyConsensusRewards = newValue;
            }
        
            /**
             * @notice Sets the daily MEV payouts value
             * @param newValue The new daily MEV payouts value to set
             * @dev Checks if the new value is within the allowed range and emits an event
             */
            function _setDailyMevPayouts(uint104 newValue) internal {
                uint104 oldValue = _dailyMevPayouts;
        
                if (!_isWithinRange(oldValue, newValue, _dailyMevPayoutsChangeToleranceBps)) {
                    revert InvalidValue();
                }
        
                emit DailyMevPayoutsUpdated(oldValue, newValue);
        
                _dailyMevPayouts = newValue;
            }
        }

        File 4 of 4: AccessManager
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v5.0.0) (access/manager/AccessManager.sol)
        pragma solidity ^0.8.20;
        import {IAccessManager} from "./IAccessManager.sol";
        import {IAccessManaged} from "./IAccessManaged.sol";
        import {Address} from "../../utils/Address.sol";
        import {Context} from "../../utils/Context.sol";
        import {Multicall} from "../../utils/Multicall.sol";
        import {Math} from "../../utils/math/Math.sol";
        import {Time} from "../../utils/types/Time.sol";
        /**
         * @dev AccessManager is a central contract to store the permissions of a system.
         *
         * A smart contract under the control of an AccessManager instance is known as a target, and will inherit from the
         * {AccessManaged} contract, be connected to this contract as its manager and implement the {AccessManaged-restricted}
         * modifier on a set of functions selected to be permissioned. Note that any function without this setup won't be
         * effectively restricted.
         *
         * The restriction rules for such functions are defined in terms of "roles" identified by an `uint64` and scoped
         * by target (`address`) and function selectors (`bytes4`). These roles are stored in this contract and can be
         * configured by admins (`ADMIN_ROLE` members) after a delay (see {getTargetAdminDelay}).
         *
         * For each target contract, admins can configure the following without any delay:
         *
         * * The target's {AccessManaged-authority} via {updateAuthority}.
         * * Close or open a target via {setTargetClosed} keeping the permissions intact.
         * * The roles that are allowed (or disallowed) to call a given function (identified by its selector) through {setTargetFunctionRole}.
         *
         * By default every address is member of the `PUBLIC_ROLE` and every target function is restricted to the `ADMIN_ROLE` until configured otherwise.
         * Additionally, each role has the following configuration options restricted to this manager's admins:
         *
         * * A role's admin role via {setRoleAdmin} who can grant or revoke roles.
         * * A role's guardian role via {setRoleGuardian} who's allowed to cancel operations.
         * * A delay in which a role takes effect after being granted through {setGrantDelay}.
         * * A delay of any target's admin action via {setTargetAdminDelay}.
         * * A role label for discoverability purposes with {labelRole}.
         *
         * Any account can be added and removed into any number of these roles by using the {grantRole} and {revokeRole} functions
         * restricted to each role's admin (see {getRoleAdmin}).
         *
         * Since all the permissions of the managed system can be modified by the admins of this instance, it is expected that
         * they will be highly secured (e.g., a multisig or a well-configured DAO).
         *
         * NOTE: This contract implements a form of the {IAuthority} interface, but {canCall} has additional return data so it
         * doesn't inherit `IAuthority`. It is however compatible with the `IAuthority` interface since the first 32 bytes of
         * the return data are a boolean as expected by that interface.
         *
         * NOTE: Systems that implement other access control mechanisms (for example using {Ownable}) can be paired with an
         * {AccessManager} by transferring permissions (ownership in the case of {Ownable}) directly to the {AccessManager}.
         * Users will be able to interact with these contracts through the {execute} function, following the access rules
         * registered in the {AccessManager}. Keep in mind that in that context, the msg.sender seen by restricted functions
         * will be {AccessManager} itself.
         *
         * WARNING: When granting permissions over an {Ownable} or {AccessControl} contract to an {AccessManager}, be very
         * mindful of the danger associated with functions such as {{Ownable-renounceOwnership}} or
         * {{AccessControl-renounceRole}}.
         */
        contract AccessManager is Context, Multicall, IAccessManager {
            using Time for *;
            // Structure that stores the details for a target contract.
            struct TargetConfig {
                mapping(bytes4 selector => uint64 roleId) allowedRoles;
                Time.Delay adminDelay;
                bool closed;
            }
            // Structure that stores the details for a role/account pair. This structures fit into a single slot.
            struct Access {
                // Timepoint at which the user gets the permission.
                // If this is either 0 or in the future, then the role permission is not available.
                uint48 since;
                // Delay for execution. Only applies to restricted() / execute() calls.
                Time.Delay delay;
            }
            // Structure that stores the details of a role.
            struct Role {
                // Members of the role.
                mapping(address user => Access access) members;
                // Admin who can grant or revoke permissions.
                uint64 admin;
                // Guardian who can cancel operations targeting functions that need this role.
                uint64 guardian;
                // Delay in which the role takes effect after being granted.
                Time.Delay grantDelay;
            }
            // Structure that stores the details for a scheduled operation. This structure fits into a single slot.
            struct Schedule {
                // Moment at which the operation can be executed.
                uint48 timepoint;
                // Operation nonce to allow third-party contracts to identify the operation.
                uint32 nonce;
            }
            uint64 public constant ADMIN_ROLE = type(uint64).min; // 0
            uint64 public constant PUBLIC_ROLE = type(uint64).max; // 2**64-1
            mapping(address target => TargetConfig mode) private _targets;
            mapping(uint64 roleId => Role) private _roles;
            mapping(bytes32 operationId => Schedule) private _schedules;
            // Used to identify operations that are currently being executed via {execute}.
            // This should be transient storage when supported by the EVM.
            bytes32 private _executionId;
            /**
             * @dev Check that the caller is authorized to perform the operation, following the restrictions encoded in
             * {_getAdminRestrictions}.
             */
            modifier onlyAuthorized() {
                _checkAuthorized();
                _;
            }
            constructor(address initialAdmin) {
                if (initialAdmin == address(0)) {
                    revert AccessManagerInvalidInitialAdmin(address(0));
                }
                // admin is active immediately and without any execution delay.
                _grantRole(ADMIN_ROLE, initialAdmin, 0, 0);
            }
            // =================================================== GETTERS ====================================================
            /// @inheritdoc IAccessManager
            function canCall(
                address caller,
                address target,
                bytes4 selector
            ) public view virtual returns (bool immediate, uint32 delay) {
                if (isTargetClosed(target)) {
                    return (false, 0);
                } else if (caller == address(this)) {
                    // Caller is AccessManager, this means the call was sent through {execute} and it already checked
                    // permissions. We verify that the call "identifier", which is set during {execute}, is correct.
                    return (_isExecuting(target, selector), 0);
                } else {
                    uint64 roleId = getTargetFunctionRole(target, selector);
                    (bool isMember, uint32 currentDelay) = hasRole(roleId, caller);
                    return isMember ? (currentDelay == 0, currentDelay) : (false, 0);
                }
            }
            /// @inheritdoc IAccessManager
            function expiration() public view virtual returns (uint32) {
                return 1 weeks;
            }
            /// @inheritdoc IAccessManager
            function minSetback() public view virtual returns (uint32) {
                return 5 days;
            }
            /// @inheritdoc IAccessManager
            function isTargetClosed(address target) public view virtual returns (bool) {
                return _targets[target].closed;
            }
            /// @inheritdoc IAccessManager
            function getTargetFunctionRole(address target, bytes4 selector) public view virtual returns (uint64) {
                return _targets[target].allowedRoles[selector];
            }
            /// @inheritdoc IAccessManager
            function getTargetAdminDelay(address target) public view virtual returns (uint32) {
                return _targets[target].adminDelay.get();
            }
            /// @inheritdoc IAccessManager
            function getRoleAdmin(uint64 roleId) public view virtual returns (uint64) {
                return _roles[roleId].admin;
            }
            /// @inheritdoc IAccessManager
            function getRoleGuardian(uint64 roleId) public view virtual returns (uint64) {
                return _roles[roleId].guardian;
            }
            /// @inheritdoc IAccessManager
            function getRoleGrantDelay(uint64 roleId) public view virtual returns (uint32) {
                return _roles[roleId].grantDelay.get();
            }
            /// @inheritdoc IAccessManager
            function getAccess(
                uint64 roleId,
                address account
            ) public view virtual returns (uint48 since, uint32 currentDelay, uint32 pendingDelay, uint48 effect) {
                Access storage access = _roles[roleId].members[account];
                since = access.since;
                (currentDelay, pendingDelay, effect) = access.delay.getFull();
                return (since, currentDelay, pendingDelay, effect);
            }
            /// @inheritdoc IAccessManager
            function hasRole(
                uint64 roleId,
                address account
            ) public view virtual returns (bool isMember, uint32 executionDelay) {
                if (roleId == PUBLIC_ROLE) {
                    return (true, 0);
                } else {
                    (uint48 hasRoleSince, uint32 currentDelay, , ) = getAccess(roleId, account);
                    return (hasRoleSince != 0 && hasRoleSince <= Time.timestamp(), currentDelay);
                }
            }
            // =============================================== ROLE MANAGEMENT ===============================================
            /// @inheritdoc IAccessManager
            function labelRole(uint64 roleId, string calldata label) public virtual onlyAuthorized {
                if (roleId == ADMIN_ROLE || roleId == PUBLIC_ROLE) {
                    revert AccessManagerLockedRole(roleId);
                }
                emit RoleLabel(roleId, label);
            }
            /// @inheritdoc IAccessManager
            function grantRole(uint64 roleId, address account, uint32 executionDelay) public virtual onlyAuthorized {
                _grantRole(roleId, account, getRoleGrantDelay(roleId), executionDelay);
            }
            /// @inheritdoc IAccessManager
            function revokeRole(uint64 roleId, address account) public virtual onlyAuthorized {
                _revokeRole(roleId, account);
            }
            /// @inheritdoc IAccessManager
            function renounceRole(uint64 roleId, address callerConfirmation) public virtual {
                if (callerConfirmation != _msgSender()) {
                    revert AccessManagerBadConfirmation();
                }
                _revokeRole(roleId, callerConfirmation);
            }
            /// @inheritdoc IAccessManager
            function setRoleAdmin(uint64 roleId, uint64 admin) public virtual onlyAuthorized {
                _setRoleAdmin(roleId, admin);
            }
            /// @inheritdoc IAccessManager
            function setRoleGuardian(uint64 roleId, uint64 guardian) public virtual onlyAuthorized {
                _setRoleGuardian(roleId, guardian);
            }
            /// @inheritdoc IAccessManager
            function setGrantDelay(uint64 roleId, uint32 newDelay) public virtual onlyAuthorized {
                _setGrantDelay(roleId, newDelay);
            }
            /**
             * @dev Internal version of {grantRole} without access control. Returns true if the role was newly granted.
             *
             * Emits a {RoleGranted} event.
             */
            function _grantRole(
                uint64 roleId,
                address account,
                uint32 grantDelay,
                uint32 executionDelay
            ) internal virtual returns (bool) {
                if (roleId == PUBLIC_ROLE) {
                    revert AccessManagerLockedRole(roleId);
                }
                bool newMember = _roles[roleId].members[account].since == 0;
                uint48 since;
                if (newMember) {
                    since = Time.timestamp() + grantDelay;
                    _roles[roleId].members[account] = Access({since: since, delay: executionDelay.toDelay()});
                } else {
                    // No setback here. Value can be reset by doing revoke + grant, effectively allowing the admin to perform
                    // any change to the execution delay within the duration of the role admin delay.
                    (_roles[roleId].members[account].delay, since) = _roles[roleId].members[account].delay.withUpdate(
                        executionDelay,
                        0
                    );
                }
                emit RoleGranted(roleId, account, executionDelay, since, newMember);
                return newMember;
            }
            /**
             * @dev Internal version of {revokeRole} without access control. This logic is also used by {renounceRole}.
             * Returns true if the role was previously granted.
             *
             * Emits a {RoleRevoked} event if the account had the role.
             */
            function _revokeRole(uint64 roleId, address account) internal virtual returns (bool) {
                if (roleId == PUBLIC_ROLE) {
                    revert AccessManagerLockedRole(roleId);
                }
                if (_roles[roleId].members[account].since == 0) {
                    return false;
                }
                delete _roles[roleId].members[account];
                emit RoleRevoked(roleId, account);
                return true;
            }
            /**
             * @dev Internal version of {setRoleAdmin} without access control.
             *
             * Emits a {RoleAdminChanged} event.
             *
             * NOTE: Setting the admin role as the `PUBLIC_ROLE` is allowed, but it will effectively allow
             * anyone to set grant or revoke such role.
             */
            function _setRoleAdmin(uint64 roleId, uint64 admin) internal virtual {
                if (roleId == ADMIN_ROLE || roleId == PUBLIC_ROLE) {
                    revert AccessManagerLockedRole(roleId);
                }
                _roles[roleId].admin = admin;
                emit RoleAdminChanged(roleId, admin);
            }
            /**
             * @dev Internal version of {setRoleGuardian} without access control.
             *
             * Emits a {RoleGuardianChanged} event.
             *
             * NOTE: Setting the guardian role as the `PUBLIC_ROLE` is allowed, but it will effectively allow
             * anyone to cancel any scheduled operation for such role.
             */
            function _setRoleGuardian(uint64 roleId, uint64 guardian) internal virtual {
                if (roleId == ADMIN_ROLE || roleId == PUBLIC_ROLE) {
                    revert AccessManagerLockedRole(roleId);
                }
                _roles[roleId].guardian = guardian;
                emit RoleGuardianChanged(roleId, guardian);
            }
            /**
             * @dev Internal version of {setGrantDelay} without access control.
             *
             * Emits a {RoleGrantDelayChanged} event.
             */
            function _setGrantDelay(uint64 roleId, uint32 newDelay) internal virtual {
                if (roleId == PUBLIC_ROLE) {
                    revert AccessManagerLockedRole(roleId);
                }
                uint48 effect;
                (_roles[roleId].grantDelay, effect) = _roles[roleId].grantDelay.withUpdate(newDelay, minSetback());
                emit RoleGrantDelayChanged(roleId, newDelay, effect);
            }
            // ============================================= FUNCTION MANAGEMENT ==============================================
            /// @inheritdoc IAccessManager
            function setTargetFunctionRole(
                address target,
                bytes4[] calldata selectors,
                uint64 roleId
            ) public virtual onlyAuthorized {
                for (uint256 i = 0; i < selectors.length; ++i) {
                    _setTargetFunctionRole(target, selectors[i], roleId);
                }
            }
            /**
             * @dev Internal version of {setTargetFunctionRole} without access control.
             *
             * Emits a {TargetFunctionRoleUpdated} event.
             */
            function _setTargetFunctionRole(address target, bytes4 selector, uint64 roleId) internal virtual {
                _targets[target].allowedRoles[selector] = roleId;
                emit TargetFunctionRoleUpdated(target, selector, roleId);
            }
            /// @inheritdoc IAccessManager
            function setTargetAdminDelay(address target, uint32 newDelay) public virtual onlyAuthorized {
                _setTargetAdminDelay(target, newDelay);
            }
            /**
             * @dev Internal version of {setTargetAdminDelay} without access control.
             *
             * Emits a {TargetAdminDelayUpdated} event.
             */
            function _setTargetAdminDelay(address target, uint32 newDelay) internal virtual {
                uint48 effect;
                (_targets[target].adminDelay, effect) = _targets[target].adminDelay.withUpdate(newDelay, minSetback());
                emit TargetAdminDelayUpdated(target, newDelay, effect);
            }
            // =============================================== MODE MANAGEMENT ================================================
            /// @inheritdoc IAccessManager
            function setTargetClosed(address target, bool closed) public virtual onlyAuthorized {
                _setTargetClosed(target, closed);
            }
            /**
             * @dev Set the closed flag for a contract. This is an internal setter with no access restrictions.
             *
             * Emits a {TargetClosed} event.
             */
            function _setTargetClosed(address target, bool closed) internal virtual {
                if (target == address(this)) {
                    revert AccessManagerLockedAccount(target);
                }
                _targets[target].closed = closed;
                emit TargetClosed(target, closed);
            }
            // ============================================== DELAYED OPERATIONS ==============================================
            /// @inheritdoc IAccessManager
            function getSchedule(bytes32 id) public view virtual returns (uint48) {
                uint48 timepoint = _schedules[id].timepoint;
                return _isExpired(timepoint) ? 0 : timepoint;
            }
            /// @inheritdoc IAccessManager
            function getNonce(bytes32 id) public view virtual returns (uint32) {
                return _schedules[id].nonce;
            }
            /// @inheritdoc IAccessManager
            function schedule(
                address target,
                bytes calldata data,
                uint48 when
            ) public virtual returns (bytes32 operationId, uint32 nonce) {
                address caller = _msgSender();
                // Fetch restrictions that apply to the caller on the targeted function
                (, uint32 setback) = _canCallExtended(caller, target, data);
                uint48 minWhen = Time.timestamp() + setback;
                // if call with delay is not authorized, or if requested timing is too soon
                if (setback == 0 || (when > 0 && when < minWhen)) {
                    revert AccessManagerUnauthorizedCall(caller, target, _checkSelector(data));
                }
                // Reuse variable due to stack too deep
                when = uint48(Math.max(when, minWhen)); // cast is safe: both inputs are uint48
                // If caller is authorised, schedule operation
                operationId = hashOperation(caller, target, data);
                _checkNotScheduled(operationId);
                unchecked {
                    // It's not feasible to overflow the nonce in less than 1000 years
                    nonce = _schedules[operationId].nonce + 1;
                }
                _schedules[operationId].timepoint = when;
                _schedules[operationId].nonce = nonce;
                emit OperationScheduled(operationId, nonce, when, caller, target, data);
                // Using named return values because otherwise we get stack too deep
            }
            /**
             * @dev Reverts if the operation is currently scheduled and has not expired.
             * (Note: This function was introduced due to stack too deep errors in schedule.)
             */
            function _checkNotScheduled(bytes32 operationId) private view {
                uint48 prevTimepoint = _schedules[operationId].timepoint;
                if (prevTimepoint != 0 && !_isExpired(prevTimepoint)) {
                    revert AccessManagerAlreadyScheduled(operationId);
                }
            }
            /// @inheritdoc IAccessManager
            // Reentrancy is not an issue because permissions are checked on msg.sender. Additionally,
            // _consumeScheduledOp guarantees a scheduled operation is only executed once.
            // slither-disable-next-line reentrancy-no-eth
            function execute(address target, bytes calldata data) public payable virtual returns (uint32) {
                address caller = _msgSender();
                // Fetch restrictions that apply to the caller on the targeted function
                (bool immediate, uint32 setback) = _canCallExtended(caller, target, data);
                // If caller is not authorised, revert
                if (!immediate && setback == 0) {
                    revert AccessManagerUnauthorizedCall(caller, target, _checkSelector(data));
                }
                bytes32 operationId = hashOperation(caller, target, data);
                uint32 nonce;
                // If caller is authorised, check operation was scheduled early enough
                // Consume an available schedule even if there is no currently enforced delay
                if (setback != 0 || getSchedule(operationId) != 0) {
                    nonce = _consumeScheduledOp(operationId);
                }
                // Mark the target and selector as authorised
                bytes32 executionIdBefore = _executionId;
                _executionId = _hashExecutionId(target, _checkSelector(data));
                // Perform call
                Address.functionCallWithValue(target, data, msg.value);
                // Reset execute identifier
                _executionId = executionIdBefore;
                return nonce;
            }
            /// @inheritdoc IAccessManager
            function cancel(address caller, address target, bytes calldata data) public virtual returns (uint32) {
                address msgsender = _msgSender();
                bytes4 selector = _checkSelector(data);
                bytes32 operationId = hashOperation(caller, target, data);
                if (_schedules[operationId].timepoint == 0) {
                    revert AccessManagerNotScheduled(operationId);
                } else if (caller != msgsender) {
                    // calls can only be canceled by the account that scheduled them, a global admin, or by a guardian of the required role.
                    (bool isAdmin, ) = hasRole(ADMIN_ROLE, msgsender);
                    (bool isGuardian, ) = hasRole(getRoleGuardian(getTargetFunctionRole(target, selector)), msgsender);
                    if (!isAdmin && !isGuardian) {
                        revert AccessManagerUnauthorizedCancel(msgsender, caller, target, selector);
                    }
                }
                delete _schedules[operationId].timepoint; // reset the timepoint, keep the nonce
                uint32 nonce = _schedules[operationId].nonce;
                emit OperationCanceled(operationId, nonce);
                return nonce;
            }
            /// @inheritdoc IAccessManager
            function consumeScheduledOp(address caller, bytes calldata data) public virtual {
                address target = _msgSender();
                if (IAccessManaged(target).isConsumingScheduledOp() != IAccessManaged.isConsumingScheduledOp.selector) {
                    revert AccessManagerUnauthorizedConsume(target);
                }
                _consumeScheduledOp(hashOperation(caller, target, data));
            }
            /**
             * @dev Internal variant of {consumeScheduledOp} that operates on bytes32 operationId.
             *
             * Returns the nonce of the scheduled operation that is consumed.
             */
            function _consumeScheduledOp(bytes32 operationId) internal virtual returns (uint32) {
                uint48 timepoint = _schedules[operationId].timepoint;
                uint32 nonce = _schedules[operationId].nonce;
                if (timepoint == 0) {
                    revert AccessManagerNotScheduled(operationId);
                } else if (timepoint > Time.timestamp()) {
                    revert AccessManagerNotReady(operationId);
                } else if (_isExpired(timepoint)) {
                    revert AccessManagerExpired(operationId);
                }
                delete _schedules[operationId].timepoint; // reset the timepoint, keep the nonce
                emit OperationExecuted(operationId, nonce);
                return nonce;
            }
            /// @inheritdoc IAccessManager
            function hashOperation(address caller, address target, bytes calldata data) public view virtual returns (bytes32) {
                return keccak256(abi.encode(caller, target, data));
            }
            // ==================================================== OTHERS ====================================================
            /// @inheritdoc IAccessManager
            function updateAuthority(address target, address newAuthority) public virtual onlyAuthorized {
                IAccessManaged(target).setAuthority(newAuthority);
            }
            // ================================================= ADMIN LOGIC ==================================================
            /**
             * @dev Check if the current call is authorized according to admin logic.
             */
            function _checkAuthorized() private {
                address caller = _msgSender();
                (bool immediate, uint32 delay) = _canCallSelf(caller, _msgData());
                if (!immediate) {
                    if (delay == 0) {
                        (, uint64 requiredRole, ) = _getAdminRestrictions(_msgData());
                        revert AccessManagerUnauthorizedAccount(caller, requiredRole);
                    } else {
                        _consumeScheduledOp(hashOperation(caller, address(this), _msgData()));
                    }
                }
            }
            /**
             * @dev Get the admin restrictions of a given function call based on the function and arguments involved.
             *
             * Returns:
             * - bool restricted: does this data match a restricted operation
             * - uint64: which role is this operation restricted to
             * - uint32: minimum delay to enforce for that operation (max between operation's delay and admin's execution delay)
             */
            function _getAdminRestrictions(
                bytes calldata data
            ) private view returns (bool restricted, uint64 roleAdminId, uint32 executionDelay) {
                if (data.length < 4) {
                    return (false, 0, 0);
                }
                bytes4 selector = _checkSelector(data);
                // Restricted to ADMIN with no delay beside any execution delay the caller may have
                if (
                    selector == this.labelRole.selector ||
                    selector == this.setRoleAdmin.selector ||
                    selector == this.setRoleGuardian.selector ||
                    selector == this.setGrantDelay.selector ||
                    selector == this.setTargetAdminDelay.selector
                ) {
                    return (true, ADMIN_ROLE, 0);
                }
                // Restricted to ADMIN with the admin delay corresponding to the target
                if (
                    selector == this.updateAuthority.selector ||
                    selector == this.setTargetClosed.selector ||
                    selector == this.setTargetFunctionRole.selector
                ) {
                    // First argument is a target.
                    address target = abi.decode(data[0x04:0x24], (address));
                    uint32 delay = getTargetAdminDelay(target);
                    return (true, ADMIN_ROLE, delay);
                }
                // Restricted to that role's admin with no delay beside any execution delay the caller may have.
                if (selector == this.grantRole.selector || selector == this.revokeRole.selector) {
                    // First argument is a roleId.
                    uint64 roleId = abi.decode(data[0x04:0x24], (uint64));
                    return (true, getRoleAdmin(roleId), 0);
                }
                return (false, 0, 0);
            }
            // =================================================== HELPERS ====================================================
            /**
             * @dev An extended version of {canCall} for internal usage that checks {_canCallSelf}
             * when the target is this contract.
             *
             * Returns:
             * - bool immediate: whether the operation can be executed immediately (with no delay)
             * - uint32 delay: the execution delay
             */
            function _canCallExtended(
                address caller,
                address target,
                bytes calldata data
            ) private view returns (bool immediate, uint32 delay) {
                if (target == address(this)) {
                    return _canCallSelf(caller, data);
                } else {
                    return data.length < 4 ? (false, 0) : canCall(caller, target, _checkSelector(data));
                }
            }
            /**
             * @dev A version of {canCall} that checks for admin restrictions in this contract.
             */
            function _canCallSelf(address caller, bytes calldata data) private view returns (bool immediate, uint32 delay) {
                if (data.length < 4) {
                    return (false, 0);
                }
                if (caller == address(this)) {
                    // Caller is AccessManager, this means the call was sent through {execute} and it already checked
                    // permissions. We verify that the call "identifier", which is set during {execute}, is correct.
                    return (_isExecuting(address(this), _checkSelector(data)), 0);
                }
                (bool enabled, uint64 roleId, uint32 operationDelay) = _getAdminRestrictions(data);
                if (!enabled) {
                    return (false, 0);
                }
                (bool inRole, uint32 executionDelay) = hasRole(roleId, caller);
                if (!inRole) {
                    return (false, 0);
                }
                // downcast is safe because both options are uint32
                delay = uint32(Math.max(operationDelay, executionDelay));
                return (delay == 0, delay);
            }
            /**
             * @dev Returns true if a call with `target` and `selector` is being executed via {executed}.
             */
            function _isExecuting(address target, bytes4 selector) private view returns (bool) {
                return _executionId == _hashExecutionId(target, selector);
            }
            /**
             * @dev Returns true if a schedule timepoint is past its expiration deadline.
             */
            function _isExpired(uint48 timepoint) private view returns (bool) {
                return timepoint + expiration() <= Time.timestamp();
            }
            /**
             * @dev Extracts the selector from calldata. Panics if data is not at least 4 bytes
             */
            function _checkSelector(bytes calldata data) private pure returns (bytes4) {
                return bytes4(data[0:4]);
            }
            /**
             * @dev Hashing function for execute protection
             */
            function _hashExecutionId(address target, bytes4 selector) private pure returns (bytes32) {
                return keccak256(abi.encode(target, selector));
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v5.0.0) (access/manager/IAccessManager.sol)
        pragma solidity ^0.8.20;
        import {IAccessManaged} from "./IAccessManaged.sol";
        import {Time} from "../../utils/types/Time.sol";
        interface IAccessManager {
            /**
             * @dev A delayed operation was scheduled.
             */
            event OperationScheduled(
                bytes32 indexed operationId,
                uint32 indexed nonce,
                uint48 schedule,
                address caller,
                address target,
                bytes data
            );
            /**
             * @dev A scheduled operation was executed.
             */
            event OperationExecuted(bytes32 indexed operationId, uint32 indexed nonce);
            /**
             * @dev A scheduled operation was canceled.
             */
            event OperationCanceled(bytes32 indexed operationId, uint32 indexed nonce);
            /**
             * @dev Informational labelling for a roleId.
             */
            event RoleLabel(uint64 indexed roleId, string label);
            /**
             * @dev Emitted when `account` is granted `roleId`.
             *
             * NOTE: The meaning of the `since` argument depends on the `newMember` argument.
             * If the role is granted to a new member, the `since` argument indicates when the account becomes a member of the role,
             * otherwise it indicates the execution delay for this account and roleId is updated.
             */
            event RoleGranted(uint64 indexed roleId, address indexed account, uint32 delay, uint48 since, bool newMember);
            /**
             * @dev Emitted when `account` membership or `roleId` is revoked. Unlike granting, revoking is instantaneous.
             */
            event RoleRevoked(uint64 indexed roleId, address indexed account);
            /**
             * @dev Role acting as admin over a given `roleId` is updated.
             */
            event RoleAdminChanged(uint64 indexed roleId, uint64 indexed admin);
            /**
             * @dev Role acting as guardian over a given `roleId` is updated.
             */
            event RoleGuardianChanged(uint64 indexed roleId, uint64 indexed guardian);
            /**
             * @dev Grant delay for a given `roleId` will be updated to `delay` when `since` is reached.
             */
            event RoleGrantDelayChanged(uint64 indexed roleId, uint32 delay, uint48 since);
            /**
             * @dev Target mode is updated (true = closed, false = open).
             */
            event TargetClosed(address indexed target, bool closed);
            /**
             * @dev Role required to invoke `selector` on `target` is updated to `roleId`.
             */
            event TargetFunctionRoleUpdated(address indexed target, bytes4 selector, uint64 indexed roleId);
            /**
             * @dev Admin delay for a given `target` will be updated to `delay` when `since` is reached.
             */
            event TargetAdminDelayUpdated(address indexed target, uint32 delay, uint48 since);
            error AccessManagerAlreadyScheduled(bytes32 operationId);
            error AccessManagerNotScheduled(bytes32 operationId);
            error AccessManagerNotReady(bytes32 operationId);
            error AccessManagerExpired(bytes32 operationId);
            error AccessManagerLockedAccount(address account);
            error AccessManagerLockedRole(uint64 roleId);
            error AccessManagerBadConfirmation();
            error AccessManagerUnauthorizedAccount(address msgsender, uint64 roleId);
            error AccessManagerUnauthorizedCall(address caller, address target, bytes4 selector);
            error AccessManagerUnauthorizedConsume(address target);
            error AccessManagerUnauthorizedCancel(address msgsender, address caller, address target, bytes4 selector);
            error AccessManagerInvalidInitialAdmin(address initialAdmin);
            /**
             * @dev Check if an address (`caller`) is authorised to call a given function on a given contract directly (with
             * no restriction). Additionally, it returns the delay needed to perform the call indirectly through the {schedule}
             * & {execute} workflow.
             *
             * This function is usually called by the targeted contract to control immediate execution of restricted functions.
             * Therefore we only return true if the call can be performed without any delay. If the call is subject to a
             * previously set delay (not zero), then the function should return false and the caller should schedule the operation
             * for future execution.
             *
             * If `immediate` is true, the delay can be disregarded and the operation can be immediately executed, otherwise
             * the operation can be executed if and only if delay is greater than 0.
             *
             * NOTE: The IAuthority interface does not include the `uint32` delay. This is an extension of that interface that
             * is backward compatible. Some contracts may thus ignore the second return argument. In that case they will fail
             * to identify the indirect workflow, and will consider calls that require a delay to be forbidden.
             *
             * NOTE: This function does not report the permissions of this manager itself. These are defined by the
             * {_canCallSelf} function instead.
             */
            function canCall(
                address caller,
                address target,
                bytes4 selector
            ) external view returns (bool allowed, uint32 delay);
            /**
             * @dev Expiration delay for scheduled proposals. Defaults to 1 week.
             *
             * IMPORTANT: Avoid overriding the expiration with 0. Otherwise every contract proposal will be expired immediately,
             * disabling any scheduling usage.
             */
            function expiration() external view returns (uint32);
            /**
             * @dev Minimum setback for all delay updates, with the exception of execution delays. It
             * can be increased without setback (and reset via {revokeRole} in the case event of an
             * accidental increase). Defaults to 5 days.
             */
            function minSetback() external view returns (uint32);
            /**
             * @dev Get whether the contract is closed disabling any access. Otherwise role permissions are applied.
             */
            function isTargetClosed(address target) external view returns (bool);
            /**
             * @dev Get the role required to call a function.
             */
            function getTargetFunctionRole(address target, bytes4 selector) external view returns (uint64);
            /**
             * @dev Get the admin delay for a target contract. Changes to contract configuration are subject to this delay.
             */
            function getTargetAdminDelay(address target) external view returns (uint32);
            /**
             * @dev Get the id of the role that acts as an admin for the given role.
             *
             * The admin permission is required to grant the role, revoke the role and update the execution delay to execute
             * an operation that is restricted to this role.
             */
            function getRoleAdmin(uint64 roleId) external view returns (uint64);
            /**
             * @dev Get the role that acts as a guardian for a given role.
             *
             * The guardian permission allows canceling operations that have been scheduled under the role.
             */
            function getRoleGuardian(uint64 roleId) external view returns (uint64);
            /**
             * @dev Get the role current grant delay.
             *
             * Its value may change at any point without an event emitted following a call to {setGrantDelay}.
             * Changes to this value, including effect timepoint are notified in advance by the {RoleGrantDelayChanged} event.
             */
            function getRoleGrantDelay(uint64 roleId) external view returns (uint32);
            /**
             * @dev Get the access details for a given account for a given role. These details include the timepoint at which
             * membership becomes active, and the delay applied to all operation by this user that requires this permission
             * level.
             *
             * Returns:
             * [0] Timestamp at which the account membership becomes valid. 0 means role is not granted.
             * [1] Current execution delay for the account.
             * [2] Pending execution delay for the account.
             * [3] Timestamp at which the pending execution delay will become active. 0 means no delay update is scheduled.
             */
            function getAccess(uint64 roleId, address account) external view returns (uint48, uint32, uint32, uint48);
            /**
             * @dev Check if a given account currently has the permission level corresponding to a given role. Note that this
             * permission might be associated with an execution delay. {getAccess} can provide more details.
             */
            function hasRole(uint64 roleId, address account) external view returns (bool, uint32);
            /**
             * @dev Give a label to a role, for improved role discoverability by UIs.
             *
             * Requirements:
             *
             * - the caller must be a global admin
             *
             * Emits a {RoleLabel} event.
             */
            function labelRole(uint64 roleId, string calldata label) external;
            /**
             * @dev Add `account` to `roleId`, or change its execution delay.
             *
             * This gives the account the authorization to call any function that is restricted to this role. An optional
             * execution delay (in seconds) can be set. If that delay is non 0, the user is required to schedule any operation
             * that is restricted to members of this role. The user will only be able to execute the operation after the delay has
             * passed, before it has expired. During this period, admin and guardians can cancel the operation (see {cancel}).
             *
             * If the account has already been granted this role, the execution delay will be updated. This update is not
             * immediate and follows the delay rules. For example, if a user currently has a delay of 3 hours, and this is
             * called to reduce that delay to 1 hour, the new delay will take some time to take effect, enforcing that any
             * operation executed in the 3 hours that follows this update was indeed scheduled before this update.
             *
             * Requirements:
             *
             * - the caller must be an admin for the role (see {getRoleAdmin})
             * - granted role must not be the `PUBLIC_ROLE`
             *
             * Emits a {RoleGranted} event.
             */
            function grantRole(uint64 roleId, address account, uint32 executionDelay) external;
            /**
             * @dev Remove an account from a role, with immediate effect. If the account does not have the role, this call has
             * no effect.
             *
             * Requirements:
             *
             * - the caller must be an admin for the role (see {getRoleAdmin})
             * - revoked role must not be the `PUBLIC_ROLE`
             *
             * Emits a {RoleRevoked} event if the account had the role.
             */
            function revokeRole(uint64 roleId, address account) external;
            /**
             * @dev Renounce role permissions for the calling account with immediate effect. If the sender is not in
             * the role this call has no effect.
             *
             * Requirements:
             *
             * - the caller must be `callerConfirmation`.
             *
             * Emits a {RoleRevoked} event if the account had the role.
             */
            function renounceRole(uint64 roleId, address callerConfirmation) external;
            /**
             * @dev Change admin role for a given role.
             *
             * Requirements:
             *
             * - the caller must be a global admin
             *
             * Emits a {RoleAdminChanged} event
             */
            function setRoleAdmin(uint64 roleId, uint64 admin) external;
            /**
             * @dev Change guardian role for a given role.
             *
             * Requirements:
             *
             * - the caller must be a global admin
             *
             * Emits a {RoleGuardianChanged} event
             */
            function setRoleGuardian(uint64 roleId, uint64 guardian) external;
            /**
             * @dev Update the delay for granting a `roleId`.
             *
             * Requirements:
             *
             * - the caller must be a global admin
             *
             * Emits a {RoleGrantDelayChanged} event.
             */
            function setGrantDelay(uint64 roleId, uint32 newDelay) external;
            /**
             * @dev Set the role required to call functions identified by the `selectors` in the `target` contract.
             *
             * Requirements:
             *
             * - the caller must be a global admin
             *
             * Emits a {TargetFunctionRoleUpdated} event per selector.
             */
            function setTargetFunctionRole(address target, bytes4[] calldata selectors, uint64 roleId) external;
            /**
             * @dev Set the delay for changing the configuration of a given target contract.
             *
             * Requirements:
             *
             * - the caller must be a global admin
             *
             * Emits a {TargetAdminDelayUpdated} event.
             */
            function setTargetAdminDelay(address target, uint32 newDelay) external;
            /**
             * @dev Set the closed flag for a contract.
             *
             * Requirements:
             *
             * - the caller must be a global admin
             *
             * Emits a {TargetClosed} event.
             */
            function setTargetClosed(address target, bool closed) external;
            /**
             * @dev Return the timepoint at which a scheduled operation will be ready for execution. This returns 0 if the
             * operation is not yet scheduled, has expired, was executed, or was canceled.
             */
            function getSchedule(bytes32 id) external view returns (uint48);
            /**
             * @dev Return the nonce for the latest scheduled operation with a given id. Returns 0 if the operation has never
             * been scheduled.
             */
            function getNonce(bytes32 id) external view returns (uint32);
            /**
             * @dev Schedule a delayed operation for future execution, and return the operation identifier. It is possible to
             * choose the timestamp at which the operation becomes executable as long as it satisfies the execution delays
             * required for the caller. The special value zero will automatically set the earliest possible time.
             *
             * Returns the `operationId` that was scheduled. Since this value is a hash of the parameters, it can reoccur when
             * the same parameters are used; if this is relevant, the returned `nonce` can be used to uniquely identify this
             * scheduled operation from other occurrences of the same `operationId` in invocations of {execute} and {cancel}.
             *
             * Emits a {OperationScheduled} event.
             *
             * NOTE: It is not possible to concurrently schedule more than one operation with the same `target` and `data`. If
             * this is necessary, a random byte can be appended to `data` to act as a salt that will be ignored by the target
             * contract if it is using standard Solidity ABI encoding.
             */
            function schedule(address target, bytes calldata data, uint48 when) external returns (bytes32, uint32);
            /**
             * @dev Execute a function that is delay restricted, provided it was properly scheduled beforehand, or the
             * execution delay is 0.
             *
             * Returns the nonce that identifies the previously scheduled operation that is executed, or 0 if the
             * operation wasn't previously scheduled (if the caller doesn't have an execution delay).
             *
             * Emits an {OperationExecuted} event only if the call was scheduled and delayed.
             */
            function execute(address target, bytes calldata data) external payable returns (uint32);
            /**
             * @dev Cancel a scheduled (delayed) operation. Returns the nonce that identifies the previously scheduled
             * operation that is cancelled.
             *
             * Requirements:
             *
             * - the caller must be the proposer, a guardian of the targeted function, or a global admin
             *
             * Emits a {OperationCanceled} event.
             */
            function cancel(address caller, address target, bytes calldata data) external returns (uint32);
            /**
             * @dev Consume a scheduled operation targeting the caller. If such an operation exists, mark it as consumed
             * (emit an {OperationExecuted} event and clean the state). Otherwise, throw an error.
             *
             * This is useful for contract that want to enforce that calls targeting them were scheduled on the manager,
             * with all the verifications that it implies.
             *
             * Emit a {OperationExecuted} event.
             */
            function consumeScheduledOp(address caller, bytes calldata data) external;
            /**
             * @dev Hashing function for delayed operations.
             */
            function hashOperation(address caller, address target, bytes calldata data) external view returns (bytes32);
            /**
             * @dev Changes the authority of a target managed by this manager instance.
             *
             * Requirements:
             *
             * - the caller must be a global admin
             */
            function updateAuthority(address target, address newAuthority) external;
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v5.0.0) (access/manager/IAccessManaged.sol)
        pragma solidity ^0.8.20;
        interface IAccessManaged {
            /**
             * @dev Authority that manages this contract was updated.
             */
            event AuthorityUpdated(address authority);
            error AccessManagedUnauthorized(address caller);
            error AccessManagedRequiredDelay(address caller, uint32 delay);
            error AccessManagedInvalidAuthority(address authority);
            /**
             * @dev Returns the current authority.
             */
            function authority() external view returns (address);
            /**
             * @dev Transfers control to a new authority. The caller must be the current authority.
             */
            function setAuthority(address) external;
            /**
             * @dev Returns true only in the context of a delayed restricted call, at the moment that the scheduled operation is
             * being consumed. Prevents denial of service for delayed restricted calls in the case that the contract performs
             * attacker controlled calls.
             */
            function isConsumingScheduledOp() external view returns (bytes4);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
        pragma solidity ^0.8.20;
        /**
         * @dev Collection of functions related to the address type
         */
        library Address {
            /**
             * @dev The ETH balance of the account is not enough to perform the operation.
             */
            error AddressInsufficientBalance(address account);
            /**
             * @dev There's no code at `target` (it is not a contract).
             */
            error AddressEmptyCode(address target);
            /**
             * @dev A call to an address target failed. The target may have reverted.
             */
            error FailedInnerCall();
            /**
             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
             * `recipient`, forwarding all available gas and reverting on errors.
             *
             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
             * of certain opcodes, possibly making contracts go over the 2300 gas limit
             * imposed by `transfer`, making them unable to receive funds via
             * `transfer`. {sendValue} removes this limitation.
             *
             * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
             *
             * IMPORTANT: because control is transferred to `recipient`, care must be
             * taken to not create reentrancy vulnerabilities. Consider using
             * {ReentrancyGuard} or the
             * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
             */
            function sendValue(address payable recipient, uint256 amount) internal {
                if (address(this).balance < amount) {
                    revert AddressInsufficientBalance(address(this));
                }
                (bool success, ) = recipient.call{value: amount}("");
                if (!success) {
                    revert FailedInnerCall();
                }
            }
            /**
             * @dev Performs a Solidity function call using a low level `call`. A
             * plain `call` is an unsafe replacement for a function call: use this
             * function instead.
             *
             * If `target` reverts with a revert reason or custom error, it is bubbled
             * up by this function (like regular Solidity function calls). However, if
             * the call reverted with no returned reason, this function reverts with a
             * {FailedInnerCall} error.
             *
             * Returns the raw returned data. To convert to the expected return value,
             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
             *
             * Requirements:
             *
             * - `target` must be a contract.
             * - calling `target` with `data` must not revert.
             */
            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                return functionCallWithValue(target, data, 0);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but also transferring `value` wei to `target`.
             *
             * Requirements:
             *
             * - the calling contract must have an ETH balance of at least `value`.
             * - the called Solidity function must be `payable`.
             */
            function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                if (address(this).balance < value) {
                    revert AddressInsufficientBalance(address(this));
                }
                (bool success, bytes memory returndata) = target.call{value: value}(data);
                return verifyCallResultFromTarget(target, success, returndata);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but performing a static call.
             */
            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                (bool success, bytes memory returndata) = target.staticcall(data);
                return verifyCallResultFromTarget(target, success, returndata);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but performing a delegate call.
             */
            function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                (bool success, bytes memory returndata) = target.delegatecall(data);
                return verifyCallResultFromTarget(target, success, returndata);
            }
            /**
             * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
             * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
             * unsuccessful call.
             */
            function verifyCallResultFromTarget(
                address target,
                bool success,
                bytes memory returndata
            ) internal view returns (bytes memory) {
                if (!success) {
                    _revert(returndata);
                } else {
                    // only check if target is a contract if the call was successful and the return data is empty
                    // otherwise we already know that it was a contract
                    if (returndata.length == 0 && target.code.length == 0) {
                        revert AddressEmptyCode(target);
                    }
                    return returndata;
                }
            }
            /**
             * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
             * revert reason or with a default {FailedInnerCall} error.
             */
            function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
                if (!success) {
                    _revert(returndata);
                } else {
                    return returndata;
                }
            }
            /**
             * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
             */
            function _revert(bytes memory returndata) private pure {
                // Look for revert reason and bubble it up if present
                if (returndata.length > 0) {
                    // The easiest way to bubble the revert reason is using memory via assembly
                    /// @solidity memory-safe-assembly
                    assembly {
                        let returndata_size := mload(returndata)
                        revert(add(32, returndata), returndata_size)
                    }
                } else {
                    revert FailedInnerCall();
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
        pragma solidity ^0.8.20;
        /**
         * @dev Provides information about the current execution context, including the
         * sender of the transaction and its data. While these are generally available
         * via msg.sender and msg.data, they should not be accessed in such a direct
         * manner, since when dealing with meta-transactions the account sending and
         * paying for execution may not be the actual sender (as far as an application
         * is concerned).
         *
         * This contract is only required for intermediate, library-like contracts.
         */
        abstract contract Context {
            function _msgSender() internal view virtual returns (address) {
                return msg.sender;
            }
            function _msgData() internal view virtual returns (bytes calldata) {
                return msg.data;
            }
            function _contextSuffixLength() internal view virtual returns (uint256) {
                return 0;
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v5.0.1) (utils/Multicall.sol)
        pragma solidity ^0.8.20;
        import {Address} from "./Address.sol";
        import {Context} from "./Context.sol";
        /**
         * @dev Provides a function to batch together multiple calls in a single external call.
         *
         * Consider any assumption about calldata validation performed by the sender may be violated if it's not especially
         * careful about sending transactions invoking {multicall}. For example, a relay address that filters function
         * selectors won't filter calls nested within a {multicall} operation.
         *
         * NOTE: Since 5.0.1 and 4.9.4, this contract identifies non-canonical contexts (i.e. `msg.sender` is not {_msgSender}).
         * If a non-canonical context is identified, the following self `delegatecall` appends the last bytes of `msg.data`
         * to the subcall. This makes it safe to use with {ERC2771Context}. Contexts that don't affect the resolution of
         * {_msgSender} are not propagated to subcalls.
         */
        abstract contract Multicall is Context {
            /**
             * @dev Receives and executes a batch of function calls on this contract.
             * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
             */
            function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {
                bytes memory context = msg.sender == _msgSender()
                    ? new bytes(0)
                    : msg.data[msg.data.length - _contextSuffixLength():];
                results = new bytes[](data.length);
                for (uint256 i = 0; i < data.length; i++) {
                    results[i] = Address.functionDelegateCall(address(this), bytes.concat(data[i], context));
                }
                return results;
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
        pragma solidity ^0.8.20;
        /**
         * @dev Standard math utilities missing in the Solidity language.
         */
        library Math {
            /**
             * @dev Muldiv operation overflow.
             */
            error MathOverflowedMulDiv();
            enum Rounding {
                Floor, // Toward negative infinity
                Ceil, // Toward positive infinity
                Trunc, // Toward zero
                Expand // Away from zero
            }
            /**
             * @dev Returns the addition of two unsigned integers, with an overflow flag.
             */
            function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                unchecked {
                    uint256 c = a + b;
                    if (c < a) return (false, 0);
                    return (true, c);
                }
            }
            /**
             * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
             */
            function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                unchecked {
                    if (b > a) return (false, 0);
                    return (true, a - b);
                }
            }
            /**
             * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
             */
            function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                unchecked {
                    // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                    // benefit is lost if 'b' is also tested.
                    // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                    if (a == 0) return (true, 0);
                    uint256 c = a * b;
                    if (c / a != b) return (false, 0);
                    return (true, c);
                }
            }
            /**
             * @dev Returns the division of two unsigned integers, with a division by zero flag.
             */
            function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                unchecked {
                    if (b == 0) return (false, 0);
                    return (true, a / b);
                }
            }
            /**
             * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
             */
            function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                unchecked {
                    if (b == 0) return (false, 0);
                    return (true, a % b);
                }
            }
            /**
             * @dev Returns the largest of two numbers.
             */
            function max(uint256 a, uint256 b) internal pure returns (uint256) {
                return a > b ? a : b;
            }
            /**
             * @dev Returns the smallest of two numbers.
             */
            function min(uint256 a, uint256 b) internal pure returns (uint256) {
                return a < b ? a : b;
            }
            /**
             * @dev Returns the average of two numbers. The result is rounded towards
             * zero.
             */
            function average(uint256 a, uint256 b) internal pure returns (uint256) {
                // (a + b) / 2 can overflow.
                return (a & b) + (a ^ b) / 2;
            }
            /**
             * @dev Returns the ceiling of the division of two numbers.
             *
             * This differs from standard division with `/` in that it rounds towards infinity instead
             * of rounding towards zero.
             */
            function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
                if (b == 0) {
                    // Guarantee the same behavior as in a regular Solidity division.
                    return a / b;
                }
                // (a + b - 1) / b can overflow on addition, so we distribute.
                return a == 0 ? 0 : (a - 1) / b + 1;
            }
            /**
             * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
             * denominator == 0.
             * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
             * Uniswap Labs also under MIT license.
             */
            function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
                unchecked {
                    // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                    // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                    // variables such that product = prod1 * 2^256 + prod0.
                    uint256 prod0 = x * y; // Least significant 256 bits of the product
                    uint256 prod1; // Most significant 256 bits of the product
                    assembly {
                        let mm := mulmod(x, y, not(0))
                        prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                    }
                    // Handle non-overflow cases, 256 by 256 division.
                    if (prod1 == 0) {
                        // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                        // The surrounding unchecked block does not change this fact.
                        // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                        return prod0 / denominator;
                    }
                    // Make sure the result is less than 2^256. Also prevents denominator == 0.
                    if (denominator <= prod1) {
                        revert MathOverflowedMulDiv();
                    }
                    ///////////////////////////////////////////////
                    // 512 by 256 division.
                    ///////////////////////////////////////////////
                    // Make division exact by subtracting the remainder from [prod1 prod0].
                    uint256 remainder;
                    assembly {
                        // Compute remainder using mulmod.
                        remainder := mulmod(x, y, denominator)
                        // Subtract 256 bit number from 512 bit number.
                        prod1 := sub(prod1, gt(remainder, prod0))
                        prod0 := sub(prod0, remainder)
                    }
                    // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
                    // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
                    uint256 twos = denominator & (0 - denominator);
                    assembly {
                        // Divide denominator by twos.
                        denominator := div(denominator, twos)
                        // Divide [prod1 prod0] by twos.
                        prod0 := div(prod0, twos)
                        // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                        twos := add(div(sub(0, twos), twos), 1)
                    }
                    // Shift in bits from prod1 into prod0.
                    prod0 |= prod1 * twos;
                    // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                    // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                    // four bits. That is, denominator * inv = 1 mod 2^4.
                    uint256 inverse = (3 * denominator) ^ 2;
                    // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
                    // works in modular arithmetic, doubling the correct bits in each step.
                    inverse *= 2 - denominator * inverse; // inverse mod 2^8
                    inverse *= 2 - denominator * inverse; // inverse mod 2^16
                    inverse *= 2 - denominator * inverse; // inverse mod 2^32
                    inverse *= 2 - denominator * inverse; // inverse mod 2^64
                    inverse *= 2 - denominator * inverse; // inverse mod 2^128
                    inverse *= 2 - denominator * inverse; // inverse mod 2^256
                    // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                    // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                    // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                    // is no longer required.
                    result = prod0 * inverse;
                    return result;
                }
            }
            /**
             * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
             */
            function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
                uint256 result = mulDiv(x, y, denominator);
                if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
                    result += 1;
                }
                return result;
            }
            /**
             * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
             * towards zero.
             *
             * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
             */
            function sqrt(uint256 a) internal pure returns (uint256) {
                if (a == 0) {
                    return 0;
                }
                // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
                //
                // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
                // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
                //
                // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
                // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
                // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
                //
                // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
                uint256 result = 1 << (log2(a) >> 1);
                // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
                // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
                // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
                // into the expected uint128 result.
                unchecked {
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    return min(result, a / result);
                }
            }
            /**
             * @notice Calculates sqrt(a), following the selected rounding direction.
             */
            function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
                unchecked {
                    uint256 result = sqrt(a);
                    return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
                }
            }
            /**
             * @dev Return the log in base 2 of a positive value rounded towards zero.
             * Returns 0 if given 0.
             */
            function log2(uint256 value) internal pure returns (uint256) {
                uint256 result = 0;
                unchecked {
                    if (value >> 128 > 0) {
                        value >>= 128;
                        result += 128;
                    }
                    if (value >> 64 > 0) {
                        value >>= 64;
                        result += 64;
                    }
                    if (value >> 32 > 0) {
                        value >>= 32;
                        result += 32;
                    }
                    if (value >> 16 > 0) {
                        value >>= 16;
                        result += 16;
                    }
                    if (value >> 8 > 0) {
                        value >>= 8;
                        result += 8;
                    }
                    if (value >> 4 > 0) {
                        value >>= 4;
                        result += 4;
                    }
                    if (value >> 2 > 0) {
                        value >>= 2;
                        result += 2;
                    }
                    if (value >> 1 > 0) {
                        result += 1;
                    }
                }
                return result;
            }
            /**
             * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
             * Returns 0 if given 0.
             */
            function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
                unchecked {
                    uint256 result = log2(value);
                    return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
                }
            }
            /**
             * @dev Return the log in base 10 of a positive value rounded towards zero.
             * Returns 0 if given 0.
             */
            function log10(uint256 value) internal pure returns (uint256) {
                uint256 result = 0;
                unchecked {
                    if (value >= 10 ** 64) {
                        value /= 10 ** 64;
                        result += 64;
                    }
                    if (value >= 10 ** 32) {
                        value /= 10 ** 32;
                        result += 32;
                    }
                    if (value >= 10 ** 16) {
                        value /= 10 ** 16;
                        result += 16;
                    }
                    if (value >= 10 ** 8) {
                        value /= 10 ** 8;
                        result += 8;
                    }
                    if (value >= 10 ** 4) {
                        value /= 10 ** 4;
                        result += 4;
                    }
                    if (value >= 10 ** 2) {
                        value /= 10 ** 2;
                        result += 2;
                    }
                    if (value >= 10 ** 1) {
                        result += 1;
                    }
                }
                return result;
            }
            /**
             * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
             * Returns 0 if given 0.
             */
            function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
                unchecked {
                    uint256 result = log10(value);
                    return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
                }
            }
            /**
             * @dev Return the log in base 256 of a positive value rounded towards zero.
             * Returns 0 if given 0.
             *
             * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
             */
            function log256(uint256 value) internal pure returns (uint256) {
                uint256 result = 0;
                unchecked {
                    if (value >> 128 > 0) {
                        value >>= 128;
                        result += 16;
                    }
                    if (value >> 64 > 0) {
                        value >>= 64;
                        result += 8;
                    }
                    if (value >> 32 > 0) {
                        value >>= 32;
                        result += 4;
                    }
                    if (value >> 16 > 0) {
                        value >>= 16;
                        result += 2;
                    }
                    if (value >> 8 > 0) {
                        result += 1;
                    }
                }
                return result;
            }
            /**
             * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
             * Returns 0 if given 0.
             */
            function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
                unchecked {
                    uint256 result = log256(value);
                    return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
                }
            }
            /**
             * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
             */
            function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
                return uint8(rounding) % 2 == 1;
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v5.0.0) (utils/types/Time.sol)
        pragma solidity ^0.8.20;
        import {Math} from "../math/Math.sol";
        import {SafeCast} from "../math/SafeCast.sol";
        /**
         * @dev This library provides helpers for manipulating time-related objects.
         *
         * It uses the following types:
         * - `uint48` for timepoints
         * - `uint32` for durations
         *
         * While the library doesn't provide specific types for timepoints and duration, it does provide:
         * - a `Delay` type to represent duration that can be programmed to change value automatically at a given point
         * - additional helper functions
         */
        library Time {
            using Time for *;
            /**
             * @dev Get the block timestamp as a Timepoint.
             */
            function timestamp() internal view returns (uint48) {
                return SafeCast.toUint48(block.timestamp);
            }
            /**
             * @dev Get the block number as a Timepoint.
             */
            function blockNumber() internal view returns (uint48) {
                return SafeCast.toUint48(block.number);
            }
            // ==================================================== Delay =====================================================
            /**
             * @dev A `Delay` is a uint32 duration that can be programmed to change value automatically at a given point in the
             * future. The "effect" timepoint describes when the transitions happens from the "old" value to the "new" value.
             * This allows updating the delay applied to some operation while keeping some guarantees.
             *
             * In particular, the {update} function guarantees that if the delay is reduced, the old delay still applies for
             * some time. For example if the delay is currently 7 days to do an upgrade, the admin should not be able to set
             * the delay to 0 and upgrade immediately. If the admin wants to reduce the delay, the old delay (7 days) should
             * still apply for some time.
             *
             *
             * The `Delay` type is 112 bits long, and packs the following:
             *
             * ```
             *   | [uint48]: effect date (timepoint)
             *   |           | [uint32]: value before (duration)
             *   ↓           ↓       ↓ [uint32]: value after (duration)
             * 0xAAAAAAAAAAAABBBBBBBBCCCCCCCC
             * ```
             *
             * NOTE: The {get} and {withUpdate} functions operate using timestamps. Block number based delays are not currently
             * supported.
             */
            type Delay is uint112;
            /**
             * @dev Wrap a duration into a Delay to add the one-step "update in the future" feature
             */
            function toDelay(uint32 duration) internal pure returns (Delay) {
                return Delay.wrap(duration);
            }
            /**
             * @dev Get the value at a given timepoint plus the pending value and effect timepoint if there is a scheduled
             * change after this timepoint. If the effect timepoint is 0, then the pending value should not be considered.
             */
            function _getFullAt(Delay self, uint48 timepoint) private pure returns (uint32, uint32, uint48) {
                (uint32 valueBefore, uint32 valueAfter, uint48 effect) = self.unpack();
                return effect <= timepoint ? (valueAfter, 0, 0) : (valueBefore, valueAfter, effect);
            }
            /**
             * @dev Get the current value plus the pending value and effect timepoint if there is a scheduled change. If the
             * effect timepoint is 0, then the pending value should not be considered.
             */
            function getFull(Delay self) internal view returns (uint32, uint32, uint48) {
                return _getFullAt(self, timestamp());
            }
            /**
             * @dev Get the current value.
             */
            function get(Delay self) internal view returns (uint32) {
                (uint32 delay, , ) = self.getFull();
                return delay;
            }
            /**
             * @dev Update a Delay object so that it takes a new duration after a timepoint that is automatically computed to
             * enforce the old delay at the moment of the update. Returns the updated Delay object and the timestamp when the
             * new delay becomes effective.
             */
            function withUpdate(
                Delay self,
                uint32 newValue,
                uint32 minSetback
            ) internal view returns (Delay updatedDelay, uint48 effect) {
                uint32 value = self.get();
                uint32 setback = uint32(Math.max(minSetback, value > newValue ? value - newValue : 0));
                effect = timestamp() + setback;
                return (pack(value, newValue, effect), effect);
            }
            /**
             * @dev Split a delay into its components: valueBefore, valueAfter and effect (transition timepoint).
             */
            function unpack(Delay self) internal pure returns (uint32 valueBefore, uint32 valueAfter, uint48 effect) {
                uint112 raw = Delay.unwrap(self);
                valueAfter = uint32(raw);
                valueBefore = uint32(raw >> 32);
                effect = uint48(raw >> 64);
                return (valueBefore, valueAfter, effect);
            }
            /**
             * @dev pack the components into a Delay object.
             */
            function pack(uint32 valueBefore, uint32 valueAfter, uint48 effect) internal pure returns (Delay) {
                return Delay.wrap((uint112(effect) << 64) | (uint112(valueBefore) << 32) | uint112(valueAfter));
            }
        }
        // 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);
            }
        }