Hoodi Testnet

Contract

0xA41BaD16f59963A3ee0Bb38DB2c3eCEdaDaDca7d

Overview

ETH Balance

0 ETH

More Info

Multichain Info

N/A
Transaction Hash
Method
Block
From
To
Amount
Revoke Role12311682025-09-17 11:57:4858 days ago1758110268IN
0xA41BaD16...daDaDca7d
0 ETH0.000058151.10902811
Grant Role12311682025-09-17 11:57:4858 days ago1758110268IN
0xA41BaD16...daDaDca7d
0 ETH0.000111911.10902811
Grant Role12311682025-09-17 11:57:4858 days ago1758110268IN
0xA41BaD16...daDaDca7d
0 ETH0.000112341.10902811
Grant Role12311682025-09-17 11:57:4858 days ago1758110268IN
0xA41BaD16...daDaDca7d
0 ETH0.00013131.10902811
Grant Role12311682025-09-17 11:57:4858 days ago1758110268IN
0xA41BaD16...daDaDca7d
0 ETH0.00013131.10902811
Grant Role12311682025-09-17 11:57:4858 days ago1758110268IN
0xA41BaD16...daDaDca7d
0 ETH0.000111911.10902811

Advanced mode:
Parent Transaction Hash Method Block
From
To
Amount
View All Internal Transactions
Loading...
Loading

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading

Similar Match Source Code
This contract matches the deployed Bytecode of the Source Code for Contract 0x0E0A4B1d...39C51BdaA
The constructor portion of the code might be different and could alter the actual behaviour of the contract

Contract Name:
CSVerifier

Compiler Version
v0.8.24+commit.e11b9ed9

Optimization Enabled:
Yes with 250 runs

Other Settings:
cancun EvmVersion

Contract Source Code (Solidity Standard Json-Input format)

// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.24;

import { AccessControlEnumerable } from "@openzeppelin/contracts/access/extensions/AccessControlEnumerable.sol";

import { BeaconBlockHeader, Slot, Validator, Withdrawal } from "./lib/Types.sol";
import { PausableUntil } from "./lib/utils/PausableUntil.sol";
import { GIndex } from "./lib/GIndex.sol";
import { SSZ } from "./lib/SSZ.sol";

import { ICSVerifier } from "./interfaces/ICSVerifier.sol";
import { ICSModule, ValidatorWithdrawalInfo } from "./interfaces/ICSModule.sol";

/// @notice Convert withdrawal amount to wei
/// @param withdrawal Withdrawal struct
function amountWei(Withdrawal memory withdrawal) pure returns (uint256) {
    return gweiToWei(withdrawal.amount);
}

/// @notice Convert gwei to wei
/// @param amount Amount in gwei
function gweiToWei(uint64 amount) pure returns (uint256) {
    return uint256(amount) * 1 gwei;
}

contract CSVerifier is ICSVerifier, AccessControlEnumerable, PausableUntil {
    using { amountWei } for Withdrawal;

    using SSZ for BeaconBlockHeader;
    using SSZ for Withdrawal;
    using SSZ for Validator;

    bytes32 public constant PAUSE_ROLE = keccak256("PAUSE_ROLE");
    bytes32 public constant RESUME_ROLE = keccak256("RESUME_ROLE");

    // See `BEACON_ROOTS_ADDRESS` constant in the EIP-4788.
    address public constant BEACON_ROOTS =
        0x000F3df6D732807Ef1319fB7B8bB8522d0Beac02;

    uint64 public immutable SLOTS_PER_EPOCH;

    /// @dev Count of historical roots per accumulator.
    /// @dev See https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#time-parameters
    uint64 public immutable SLOTS_PER_HISTORICAL_ROOT;

    /// @dev This index is relative to a state like: `BeaconState.latest_execution_payload_header.withdrawals[0]`.
    GIndex public immutable GI_FIRST_WITHDRAWAL_PREV;

    /// @dev This index is relative to a state like: `BeaconState.latest_execution_payload_header.withdrawals[0]`.
    GIndex public immutable GI_FIRST_WITHDRAWAL_CURR;

    /// @dev This index is relative to a state like: `BeaconState.validators[0]`.
    GIndex public immutable GI_FIRST_VALIDATOR_PREV;

    /// @dev This index is relative to a state like: `BeaconState.validators[0]`.
    GIndex public immutable GI_FIRST_VALIDATOR_CURR;

    /// @dev This index is relative to a state like: `BeaconState.historical_summaries[0]`.
    GIndex public immutable GI_FIRST_HISTORICAL_SUMMARY_PREV;

    /// @dev This index is relative to a state like: `BeaconState.historical_summaries[0]`.
    GIndex public immutable GI_FIRST_HISTORICAL_SUMMARY_CURR;

    /// @dev This index is relative to HistoricalSummary like: HistoricalSummary.blockRoots[0].
    GIndex public immutable GI_FIRST_BLOCK_ROOT_IN_SUMMARY_PREV;

    /// @dev This index is relative to HistoricalSummary like: HistoricalSummary.blockRoots[0].
    GIndex public immutable GI_FIRST_BLOCK_ROOT_IN_SUMMARY_CURR;

    /// @dev The very first slot the verifier is supposed to accept proofs for.
    Slot public immutable FIRST_SUPPORTED_SLOT;

    /// @dev The first slot of the currently compatible fork.
    Slot public immutable PIVOT_SLOT;

    /// @dev Historical summaries started accumulating from the slot of Capella fork.
    Slot public immutable CAPELLA_SLOT;

    /// @dev An address withdrawals are supposed to happen to (Lido withdrawal credentials).
    address public immutable WITHDRAWAL_ADDRESS;

    /// @dev Staking module contract.
    ICSModule public immutable MODULE;

    /// @dev The previous and current forks can be essentially the same.
    constructor(
        address withdrawalAddress,
        address module,
        uint64 slotsPerEpoch,
        uint64 slotsPerHistoricalRoot,
        GIndices memory gindices,
        Slot firstSupportedSlot,
        Slot pivotSlot,
        Slot capellaSlot,
        address admin
    ) {
        if (withdrawalAddress == address(0)) {
            revert ZeroWithdrawalAddress();
        }

        if (module == address(0)) {
            revert ZeroModuleAddress();
        }

        if (admin == address(0)) {
            revert ZeroAdminAddress();
        }

        if (slotsPerEpoch == 0) {
            revert InvalidChainConfig();
        }

        if (slotsPerHistoricalRoot == 0) {
            revert InvalidChainConfig();
        }

        if (firstSupportedSlot > pivotSlot) {
            revert InvalidPivotSlot();
        }

        if (capellaSlot > firstSupportedSlot) {
            revert InvalidCapellaSlot();
        }

        WITHDRAWAL_ADDRESS = withdrawalAddress;
        MODULE = ICSModule(module);

        SLOTS_PER_EPOCH = slotsPerEpoch;
        SLOTS_PER_HISTORICAL_ROOT = slotsPerHistoricalRoot;

        GI_FIRST_WITHDRAWAL_PREV = gindices.gIFirstWithdrawalPrev;
        GI_FIRST_WITHDRAWAL_CURR = gindices.gIFirstWithdrawalCurr;

        GI_FIRST_VALIDATOR_PREV = gindices.gIFirstValidatorPrev;
        GI_FIRST_VALIDATOR_CURR = gindices.gIFirstValidatorCurr;

        GI_FIRST_HISTORICAL_SUMMARY_PREV = gindices
            .gIFirstHistoricalSummaryPrev;
        GI_FIRST_HISTORICAL_SUMMARY_CURR = gindices
            .gIFirstHistoricalSummaryCurr;

        GI_FIRST_BLOCK_ROOT_IN_SUMMARY_PREV = gindices
            .gIFirstBlockRootInSummaryPrev;
        GI_FIRST_BLOCK_ROOT_IN_SUMMARY_CURR = gindices
            .gIFirstBlockRootInSummaryCurr;

        FIRST_SUPPORTED_SLOT = firstSupportedSlot;
        PIVOT_SLOT = pivotSlot;
        CAPELLA_SLOT = capellaSlot;

        _grantRole(DEFAULT_ADMIN_ROLE, admin);
    }

    /// @inheritdoc ICSVerifier
    function resume() external onlyRole(RESUME_ROLE) {
        _resume();
    }

    /// @inheritdoc ICSVerifier
    function pauseFor(uint256 duration) external onlyRole(PAUSE_ROLE) {
        _pauseFor(duration);
    }

    /// @inheritdoc ICSVerifier
    function processWithdrawalProof(
        ProvableBeaconBlockHeader calldata beaconBlock,
        WithdrawalWitness calldata witness,
        uint256 nodeOperatorId,
        uint256 keyIndex
    ) external whenResumed {
        if (beaconBlock.header.slot < FIRST_SUPPORTED_SLOT) {
            revert UnsupportedSlot(beaconBlock.header.slot);
        }

        {
            bytes32 trustedHeaderRoot = _getParentBlockRoot(
                beaconBlock.rootsTimestamp
            );
            if (trustedHeaderRoot != beaconBlock.header.hashTreeRoot()) {
                revert InvalidBlockHeader();
            }
        }

        bytes memory pubkey = MODULE.getSigningKeys(
            nodeOperatorId,
            keyIndex,
            1
        );

        uint256 withdrawalAmount = _processWithdrawalProof({
            witness: witness,
            stateSlot: beaconBlock.header.slot,
            stateRoot: beaconBlock.header.stateRoot,
            pubkey: pubkey
        });

        ValidatorWithdrawalInfo[]
            memory withdrawalsInfo = new ValidatorWithdrawalInfo[](1);
        withdrawalsInfo[0] = ValidatorWithdrawalInfo(
            nodeOperatorId,
            keyIndex,
            withdrawalAmount
        );
        MODULE.submitWithdrawals(withdrawalsInfo);
    }

    /// @inheritdoc ICSVerifier
    function processHistoricalWithdrawalProof(
        ProvableBeaconBlockHeader calldata beaconBlock,
        HistoricalHeaderWitness calldata oldBlock,
        WithdrawalWitness calldata witness,
        uint256 nodeOperatorId,
        uint256 keyIndex
    ) external whenResumed {
        if (beaconBlock.header.slot < FIRST_SUPPORTED_SLOT) {
            revert UnsupportedSlot(beaconBlock.header.slot);
        }

        if (oldBlock.header.slot < FIRST_SUPPORTED_SLOT) {
            revert UnsupportedSlot(oldBlock.header.slot);
        }

        {
            bytes32 trustedHeaderRoot = _getParentBlockRoot(
                beaconBlock.rootsTimestamp
            );
            bytes32 headerRoot = beaconBlock.header.hashTreeRoot();
            if (trustedHeaderRoot != headerRoot) {
                revert InvalidBlockHeader();
            }
        }

        SSZ.verifyProof({
            proof: oldBlock.proof,
            root: beaconBlock.header.stateRoot,
            leaf: oldBlock.header.hashTreeRoot(),
            gI: _getHistoricalBlockRootGI(
                beaconBlock.header.slot,
                oldBlock.header.slot
            )
        });

        bytes memory pubkey = MODULE.getSigningKeys(
            nodeOperatorId,
            keyIndex,
            1
        );

        uint256 withdrawalAmount = _processWithdrawalProof({
            witness: witness,
            stateSlot: oldBlock.header.slot,
            stateRoot: oldBlock.header.stateRoot,
            pubkey: pubkey
        });

        ValidatorWithdrawalInfo[]
            memory withdrawalsInfo = new ValidatorWithdrawalInfo[](1);
        withdrawalsInfo[0] = ValidatorWithdrawalInfo(
            nodeOperatorId,
            keyIndex,
            withdrawalAmount
        );
        MODULE.submitWithdrawals(withdrawalsInfo);
    }

    function _getParentBlockRoot(
        uint64 blockTimestamp
    ) internal view returns (bytes32) {
        (bool success, bytes memory data) = BEACON_ROOTS.staticcall(
            abi.encode(blockTimestamp)
        );

        if (!success || data.length == 0) {
            revert RootNotFound();
        }

        return abi.decode(data, (bytes32));
    }

    /// @dev `stateRoot` is supposed to be trusted at this point.
    function _processWithdrawalProof(
        WithdrawalWitness calldata witness,
        Slot stateSlot,
        bytes32 stateRoot,
        bytes memory pubkey
    ) internal view returns (uint256 withdrawalAmount) {
        // WC to address
        address withdrawalAddress = address(
            uint160(uint256(witness.withdrawalCredentials))
        );
        if (withdrawalAddress != WITHDRAWAL_ADDRESS) {
            revert InvalidWithdrawalAddress();
        }

        if (_computeEpochAtSlot(stateSlot) < witness.withdrawableEpoch) {
            revert ValidatorNotWithdrawn();
        }

        // See https://hackmd.io/1wM8vqeNTjqt4pC3XoCUKQ
        //
        // ISSUE:
        // There is a possible way to bypass this check:
        // - wait for full withdrawal & sweep
        // - be lucky enough that no one provides proof for this withdrawal for at least 1 sweep cycle
        //  (~8 days with the network of 1M active validators)
        // - deposit 1 ETH for slashed or 8 ETH for non-slashed validator
        // - wait for a sweep of this deposit
        // - provide proof of the last withdrawal
        // As a result, the Node Operator's bond will be penalized for 32 ETH - additional deposit value
        // However, all ETH involved,
        // including 1 or 8 ETH deposited by the attacker will remain in the Lido on Ethereum protocol
        // Hence, the only consequence of the attack is an inconsistency in the bond accounting that can be resolved
        // through the bond deposit approved by the corresponding DAO decision
        //
        // Resolution:
        // Given no losses for the protocol,
        // significant cost of attack (1 or 8 ETH),
        // and lack of feasible ways to mitigate it in the smart contract's code,
        // it is proposed to acknowledge possibility of the attack
        // and be ready to propose a corresponding vote to the DAO if it will ever happen
        if (!witness.slashed && gweiToWei(witness.amount) < 8 ether) {
            revert PartialWithdrawal();
        }

        Validator memory validator = Validator({
            pubkey: pubkey,
            withdrawalCredentials: witness.withdrawalCredentials,
            effectiveBalance: witness.effectiveBalance,
            slashed: witness.slashed,
            activationEligibilityEpoch: witness.activationEligibilityEpoch,
            activationEpoch: witness.activationEpoch,
            exitEpoch: witness.exitEpoch,
            withdrawableEpoch: witness.withdrawableEpoch
        });

        SSZ.verifyProof({
            proof: witness.validatorProof,
            root: stateRoot,
            leaf: validator.hashTreeRoot(),
            gI: _getValidatorGI(witness.validatorIndex, stateSlot)
        });

        Withdrawal memory withdrawal = Withdrawal({
            index: witness.withdrawalIndex,
            validatorIndex: witness.validatorIndex,
            withdrawalAddress: withdrawalAddress,
            amount: witness.amount
        });

        SSZ.verifyProof({
            proof: witness.withdrawalProof,
            root: stateRoot,
            leaf: withdrawal.hashTreeRoot(),
            gI: _getWithdrawalGI(witness.withdrawalOffset, stateSlot)
        });

        return withdrawal.amountWei();
    }

    function _getValidatorGI(
        uint256 offset,
        Slot stateSlot
    ) internal view returns (GIndex) {
        GIndex gI = stateSlot < PIVOT_SLOT
            ? GI_FIRST_VALIDATOR_PREV
            : GI_FIRST_VALIDATOR_CURR;
        return gI.shr(offset);
    }

    function _getWithdrawalGI(
        uint256 offset,
        Slot stateSlot
    ) internal view returns (GIndex) {
        GIndex gI = stateSlot < PIVOT_SLOT
            ? GI_FIRST_WITHDRAWAL_PREV
            : GI_FIRST_WITHDRAWAL_CURR;
        return gI.shr(offset);
    }

    function _getHistoricalBlockRootGI(
        Slot recentSlot,
        Slot targetSlot
    ) internal view returns (GIndex gI) {
        uint64 targetSlotShifted = targetSlot.unwrap() - CAPELLA_SLOT.unwrap();
        uint64 summaryIndex = targetSlotShifted / SLOTS_PER_HISTORICAL_ROOT;
        uint64 rootIndex = targetSlot.unwrap() % SLOTS_PER_HISTORICAL_ROOT;

        Slot summaryCreatedAtSlot = Slot.wrap(
            targetSlot.unwrap() - rootIndex + SLOTS_PER_HISTORICAL_ROOT
        );
        if (summaryCreatedAtSlot > recentSlot) {
            revert HistoricalSummaryDoesNotExist();
        }

        gI = recentSlot < PIVOT_SLOT
            ? GI_FIRST_HISTORICAL_SUMMARY_PREV
            : GI_FIRST_HISTORICAL_SUMMARY_CURR;

        gI = gI.shr(summaryIndex); // historicalSummaries[summaryIndex]
        gI = gI.concat(
            summaryCreatedAtSlot < PIVOT_SLOT
                ? GI_FIRST_BLOCK_ROOT_IN_SUMMARY_PREV
                : GI_FIRST_BLOCK_ROOT_IN_SUMMARY_CURR
        ); // historicalSummaries[summaryIndex].blockRoots[0]
        gI = gI.shr(rootIndex); // historicalSummaries[summaryIndex].blockRoots[rootIndex]
    }

    // From HashConsensus contract.
    function _computeEpochAtSlot(Slot slot) internal view returns (uint256) {
        // See: github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#compute_epoch_at_slot
        return slot.unwrap() / SLOTS_PER_EPOCH;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/extensions/AccessControlEnumerable.sol)

pragma solidity ^0.8.20;

import {IAccessControlEnumerable} from "./IAccessControlEnumerable.sol";
import {AccessControl} from "../AccessControl.sol";
import {EnumerableSet} from "../../utils/structs/EnumerableSet.sol";

/**
 * @dev Extension of {AccessControl} that allows enumerating the members of each role.
 */
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
    using EnumerableSet for EnumerableSet.AddressSet;

    mapping(bytes32 role => EnumerableSet.AddressSet) private _roleMembers;

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) public view virtual returns (address) {
        return _roleMembers[role].at(index);
    }

    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) public view virtual returns (uint256) {
        return _roleMembers[role].length();
    }

    /**
     * @dev Overload {AccessControl-_grantRole} to track enumerable memberships
     */
    function _grantRole(bytes32 role, address account) internal virtual override returns (bool) {
        bool granted = super._grantRole(role, account);
        if (granted) {
            _roleMembers[role].add(account);
        }
        return granted;
    }

    /**
     * @dev Overload {AccessControl-_revokeRole} to track enumerable memberships
     */
    function _revokeRole(bytes32 role, address account) internal virtual override returns (bool) {
        bool revoked = super._revokeRole(role, account);
        if (revoked) {
            _roleMembers[role].remove(account);
        }
        return revoked;
    }
}

// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.24;

// As defined in phase0/beacon-chain.md:159
type Slot is uint64;

function unwrap(Slot slot) pure returns (uint64) {
    return Slot.unwrap(slot);
}

function gt(Slot lhs, Slot rhs) pure returns (bool) {
    return lhs.unwrap() > rhs.unwrap();
}

function lt(Slot lhs, Slot rhs) pure returns (bool) {
    return lhs.unwrap() < rhs.unwrap();
}

using { unwrap, lt as <, gt as > } for Slot global;

// As defined in capella/beacon-chain.md:99
struct Withdrawal {
    uint64 index;
    uint64 validatorIndex;
    address withdrawalAddress;
    uint64 amount;
}

// As defined in phase0/beacon-chain.md:356
struct Validator {
    bytes pubkey;
    bytes32 withdrawalCredentials;
    uint64 effectiveBalance;
    bool slashed;
    uint64 activationEligibilityEpoch;
    uint64 activationEpoch;
    uint64 exitEpoch;
    uint64 withdrawableEpoch;
}

// As defined in phase0/beacon-chain.md:436
struct BeaconBlockHeader {
    Slot slot;
    uint64 proposerIndex;
    bytes32 parentRoot;
    bytes32 stateRoot;
    bytes32 bodyRoot;
}

// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import { UnstructuredStorage } from "../UnstructuredStorage.sol";

contract PausableUntil {
    using UnstructuredStorage for bytes32;

    /// Contract resume/pause control storage slot
    bytes32 internal constant RESUME_SINCE_TIMESTAMP_POSITION =
        keccak256("lido.PausableUntil.resumeSinceTimestamp");
    /// Special value for the infinite pause
    uint256 public constant PAUSE_INFINITELY = type(uint256).max;

    /// @notice Emitted when paused by the `pauseFor` or `pauseUntil` call
    event Paused(uint256 duration);
    /// @notice Emitted when resumed by the `resume` call
    event Resumed();

    error ZeroPauseDuration();
    error PausedExpected();
    error ResumedExpected();
    error PauseUntilMustBeInFuture();

    /// @notice Reverts when resumed
    modifier whenPaused() {
        _checkPaused();
        _;
    }

    /// @notice Reverts when paused
    modifier whenResumed() {
        _checkResumed();
        _;
    }

    /// @notice Returns one of:
    ///  - PAUSE_INFINITELY if paused infinitely returns
    ///  - first second when get contract get resumed if paused for specific duration
    ///  - some timestamp in past if not paused
    function getResumeSinceTimestamp() external view returns (uint256) {
        return RESUME_SINCE_TIMESTAMP_POSITION.getStorageUint256();
    }

    /// @notice Returns whether the contract is paused
    function isPaused() public view returns (bool) {
        return
            block.timestamp <
            RESUME_SINCE_TIMESTAMP_POSITION.getStorageUint256();
    }

    function _resume() internal {
        _checkPaused();
        RESUME_SINCE_TIMESTAMP_POSITION.setStorageUint256(block.timestamp);
        emit Resumed();
    }

    function _pauseFor(uint256 duration) internal {
        _checkResumed();
        if (duration == 0) {
            revert ZeroPauseDuration();
        }

        uint256 resumeSince;
        if (duration == PAUSE_INFINITELY) {
            resumeSince = PAUSE_INFINITELY;
        } else {
            resumeSince = block.timestamp + duration;
        }
        _setPausedState(resumeSince);
    }

    function _pauseUntil(uint256 pauseUntilInclusive) internal {
        _checkResumed();
        if (pauseUntilInclusive < block.timestamp) {
            revert PauseUntilMustBeInFuture();
        }

        uint256 resumeSince;
        if (pauseUntilInclusive != PAUSE_INFINITELY) {
            resumeSince = pauseUntilInclusive + 1;
        } else {
            resumeSince = PAUSE_INFINITELY;
        }
        _setPausedState(resumeSince);
    }

    function _setPausedState(uint256 resumeSince) internal {
        RESUME_SINCE_TIMESTAMP_POSITION.setStorageUint256(resumeSince);
        if (resumeSince == PAUSE_INFINITELY) {
            emit Paused(PAUSE_INFINITELY);
        } else {
            emit Paused(resumeSince - block.timestamp);
        }
    }

    function _checkPaused() internal view {
        if (!isPaused()) {
            revert PausedExpected();
        }
    }

    function _checkResumed() internal view {
        if (isPaused()) {
            revert ResumedExpected();
        }
    }
}

// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.24;

type GIndex is bytes32;

using { isRoot, index, width, shr, shl, concat, unwrap, pow } for GIndex global;

error IndexOutOfRange();

/// @param gI Is a generalized index of a node in a tree.
/// @param p Is a power of a tree level the node belongs to.
/// @return GIndex
function pack(uint256 gI, uint8 p) pure returns (GIndex) {
    if (gI > type(uint248).max) {
        revert IndexOutOfRange();
    }

    // NOTE: We can consider adding additional metadata like a fork version.
    return GIndex.wrap(bytes32((gI << 8) | p));
}

function unwrap(GIndex self) pure returns (bytes32) {
    return GIndex.unwrap(self);
}

function isRoot(GIndex self) pure returns (bool) {
    return index(self) == 1;
}

function index(GIndex self) pure returns (uint256) {
    return uint256(unwrap(self)) >> 8;
}

function width(GIndex self) pure returns (uint256) {
    return 1 << pow(self);
}

function pow(GIndex self) pure returns (uint8) {
    return uint8(uint256(unwrap(self)));
}

/// @return Generalized index of the nth neighbor of the node to the right.
function shr(GIndex self, uint256 n) pure returns (GIndex) {
    uint256 i = index(self);
    uint256 w = width(self);

    if ((i % w) + n >= w) {
        revert IndexOutOfRange();
    }

    return pack(i + n, pow(self));
}

/// @return Generalized index of the nth neighbor of the node to the left.
function shl(GIndex self, uint256 n) pure returns (GIndex) {
    uint256 i = index(self);
    uint256 w = width(self);

    if (i % w < n) {
        revert IndexOutOfRange();
    }

    return pack(i - n, pow(self));
}

// See https://github.com/protolambda/remerkleable/blob/91ed092d08ef0ba5ab076f0a34b0b371623db728/remerkleable/tree.py#L46
function concat(GIndex lhs, GIndex rhs) pure returns (GIndex) {
    uint256 lindex = index(lhs);
    uint256 rindex = index(rhs);

    uint256 lhsMSbIndex = fls(lindex);
    uint256 rhsMSbIndex = fls(rindex);

    if (lhsMSbIndex + 1 + rhsMSbIndex > 248) {
        revert IndexOutOfRange();
    }

    return
        pack((lindex << rhsMSbIndex) | (rindex ^ (1 << rhsMSbIndex)), pow(rhs));
}

/// @dev From Solady LibBit, see https://github.com/Vectorized/solady/blob/main/src/utils/LibBit.sol.
/// @dev Find last set.
/// Returns the index of the most significant bit of `x`,
/// counting from the least significant bit position.
/// If `x` is zero, returns 256.
function fls(uint256 x) pure returns (uint256 r) {
    assembly ("memory-safe") {
        // prettier-ignore
        r := or(shl(8, iszero(x)), shl(7, lt(0xffffffffffffffffffffffffffffffff, x)))
        r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
        r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
        r := or(r, shl(4, lt(0xffff, shr(r, x))))
        r := or(r, shl(3, lt(0xff, shr(r, x))))
        // prettier-ignore
        r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0x0706060506020504060203020504030106050205030304010505030400000000))
    }
}

// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.24;

import { BeaconBlockHeader, Withdrawal, Validator } from "./Types.sol";
import { GIndex } from "./GIndex.sol";

library SSZ {
    error BranchHasMissingItem();
    error BranchHasExtraItem();
    error InvalidProof();

    function hashTreeRoot(
        BeaconBlockHeader memory header
    ) internal view returns (bytes32 root) {
        root = bytes32(0);

        bytes32[8] memory nodes = [
            toLittleEndian(header.slot.unwrap()),
            toLittleEndian(header.proposerIndex),
            header.parentRoot,
            header.stateRoot,
            header.bodyRoot,
            bytes32(0),
            bytes32(0),
            bytes32(0)
        ];

        assembly ("memory-safe") {
            // Count of nodes to hash
            let count := 8

            // Loop over levels
            // prettier-ignore
            for { } 1 { } {
                // Loop over nodes at the given depth

                // Initialize `offset` to the offset of `proof` elements in memory.
                let target := nodes
                let source := nodes
                let end := add(source, shl(5, count))

                // prettier-ignore
                for { } 1 { } {
                    // Read next two hashes to hash
                    mcopy(0x00, source, 0x40)

                    // Call sha256 precompile
                    let result := staticcall(
                        gas(),
                        0x02,
                        0x00,
                        0x40,
                        0x00,
                        0x20
                    )

                    if iszero(result) {
                        // Precompiles returns no data on OutOfGas error.
                        revert(0, 0)
                    }

                    // Store the resulting hash at the target location
                    mstore(target, mload(0x00))

                    // Advance the pointers
                    target := add(target, 0x20)
                    source := add(source, 0x40)

                    if iszero(lt(source, end)) {
                        break
                    }
                }

                count := shr(1, count)
                if eq(count, 1) {
                    root := mload(0x00)
                    break
                }
            }
        }
    }

    function hashTreeRoot(
        Validator memory validator
    ) internal view returns (bytes32 root) {
        root = bytes32(0);

        bytes32 pubkeyRoot;
        assembly ("memory-safe") {
            // Dynamic data types such as bytes are stored at the specified offset.
            let offset := mload(validator)
            // Copy the pubkey to the scratch space.
            mcopy(0x00, add(offset, 32), 48)
            // Clear the last 16 bytes.
            mcopy(48, 0x60, 16)
            // Call sha256 precompile.
            let result := staticcall(gas(), 0x02, 0x00, 0x40, 0x00, 0x20)

            if iszero(result) {
                // Precompiles returns no data on OutOfGas error.
                revert(0, 0)
            }

            pubkeyRoot := mload(0x00)
        }

        bytes32[8] memory nodes = [
            pubkeyRoot,
            validator.withdrawalCredentials,
            toLittleEndian(validator.effectiveBalance),
            toLittleEndian(validator.slashed),
            toLittleEndian(validator.activationEligibilityEpoch),
            toLittleEndian(validator.activationEpoch),
            toLittleEndian(validator.exitEpoch),
            toLittleEndian(validator.withdrawableEpoch)
        ];

        assembly ("memory-safe") {
            // Count of nodes to hash
            let count := 8

            // Loop over levels
            // prettier-ignore
            for { } 1 { } {
                // Loop over nodes at the given depth

                // Initialize `offset` to the offset of `proof` elements in memory.
                let target := nodes
                let source := nodes
                let end := add(source, shl(5, count))

                // prettier-ignore
                for { } 1 { } {
                    // Read next two hashes to hash
                    mcopy(0x00, source, 0x40)

                    // Call sha256 precompile
                    let result := staticcall(
                        gas(),
                        0x02,
                        0x00,
                        0x40,
                        0x00,
                        0x20
                    )

                    if iszero(result) {
                        // Precompiles returns no data on OutOfGas error.
                        revert(0, 0)
                    }

                    // Store the resulting hash at the target location
                    mstore(target, mload(0x00))

                    // Advance the pointers
                    target := add(target, 0x20)
                    source := add(source, 0x40)

                    if iszero(lt(source, end)) {
                        break
                    }
                }

                count := shr(1, count)
                if eq(count, 1) {
                    root := mload(0x00)
                    break
                }
            }
        }
    }

    /// @notice Modified version of `verify` from Solady `MerkleProofLib` to support generalized indices and sha256 precompile.
    /// @dev Reverts if `leaf` doesn't exist in the Merkle tree with `root`, given `proof`.
    function verifyProof(
        bytes32[] calldata proof,
        bytes32 root,
        bytes32 leaf,
        GIndex gI
    ) internal view {
        uint256 index = gI.index();

        assembly ("memory-safe") {
            // Check if `proof` is empty.
            if iszero(proof.length) {
                // revert InvalidProof()
                mstore(0x00, 0x09bde339)
                revert(0x1c, 0x04)
            }
            // Left shift by 5 is equivalent to multiplying by 0x20.
            let end := add(proof.offset, shl(5, proof.length))
            // Initialize `offset` to the offset of `proof` in the calldata.
            let offset := proof.offset
            // Iterate over proof elements to compute root hash.
            // prettier-ignore
            for { } 1 { } {
                // Slot of `leaf` in scratch space.
                // If the condition is true: 0x20, otherwise: 0x00.
                let scratch := shl(5, and(index, 1))
                index := shr(1, index)
                if iszero(index) {
                    // revert BranchHasExtraItem()
                    mstore(0x00, 0x5849603f)
                    // 0x1c = 28 => offset in 32-byte word of a slot 0x00
                    revert(0x1c, 0x04)
                }
                // Store elements to hash contiguously in scratch space.
                // Scratch space is 64 bytes (0x00 - 0x3f) and both elements are 32 bytes.
                mstore(scratch, leaf)
                mstore(xor(scratch, 0x20), calldataload(offset))
                // Call sha256 precompile.
                let result := staticcall(
                    gas(),
                    0x02,
                    0x00,
                    0x40,
                    0x00,
                    0x20
                )

                if iszero(result) {
                    // Precompile returns no data on OutOfGas error.
                    revert(0, 0)
                }

                // Reuse `leaf` to store the hash to reduce stack operations.
                leaf := mload(0x00)
                offset := add(offset, 0x20)
                if iszero(lt(offset, end)) {
                    break
                }
            }

            if iszero(eq(index, 1)) {
                // revert BranchHasMissingItem()
                mstore(0x00, 0x1b6661c3)
                revert(0x1c, 0x04)
            }

            if iszero(eq(leaf, root)) {
                // revert InvalidProof()
                mstore(0x00, 0x09bde339)
                revert(0x1c, 0x04)
            }
        }
    }

    // Inspired by https://github.com/succinctlabs/telepathy-contracts/blob/5aa4bb7/src/libraries/SimpleSerialize.sol#L59
    function hashTreeRoot(
        Withdrawal memory withdrawal
    ) internal pure returns (bytes32) {
        return
            sha256(
                bytes.concat(
                    sha256(
                        bytes.concat(
                            toLittleEndian(withdrawal.index),
                            toLittleEndian(withdrawal.validatorIndex)
                        )
                    ),
                    sha256(
                        bytes.concat(
                            bytes20(withdrawal.withdrawalAddress),
                            bytes12(0),
                            toLittleEndian(withdrawal.amount)
                        )
                    )
                )
            );
    }

    // See https://github.com/succinctlabs/telepathy-contracts/blob/5aa4bb7/src/libraries/SimpleSerialize.sol#L17-L28
    function toLittleEndian(uint256 v) internal pure returns (bytes32) {
        v =
            ((v &
                0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00) >>
                8) |
            ((v &
                0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) <<
                8);
        v =
            ((v &
                0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000) >>
                16) |
            ((v &
                0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) <<
                16);
        v =
            ((v &
                0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000) >>
                32) |
            ((v &
                0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) <<
                32);
        v =
            ((v &
                0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000) >>
                64) |
            ((v &
                0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) <<
                64);
        v = (v >> 128) | (v << 128);
        return bytes32(v);
    }

    function toLittleEndian(bool v) internal pure returns (bytes32) {
        return bytes32(v ? 1 << 248 : 0);
    }
}

// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.24;

import { BeaconBlockHeader, Slot } from "../lib/Types.sol";
import { GIndex } from "../lib/GIndex.sol";
import { ICSModule } from "./ICSModule.sol";

interface ICSVerifier {
    struct GIndices {
        GIndex gIFirstWithdrawalPrev;
        GIndex gIFirstWithdrawalCurr;
        GIndex gIFirstValidatorPrev;
        GIndex gIFirstValidatorCurr;
        GIndex gIFirstHistoricalSummaryPrev;
        GIndex gIFirstHistoricalSummaryCurr;
        GIndex gIFirstBlockRootInSummaryPrev;
        GIndex gIFirstBlockRootInSummaryCurr;
    }

    struct ProvableBeaconBlockHeader {
        BeaconBlockHeader header; // Header of a block which root is a root at rootsTimestamp.
        uint64 rootsTimestamp; // To be passed to the EIP-4788 block roots contract.
    }

    struct SlashingWitness {
        uint64 validatorIndex;
        bytes32 withdrawalCredentials;
        uint64 effectiveBalance;
        uint64 activationEligibilityEpoch;
        uint64 activationEpoch;
        uint64 exitEpoch;
        uint64 withdrawableEpoch;
        bytes32[] validatorProof;
    }

    struct WithdrawalWitness {
        // ── Withdrawal fields ─────────────────────────────────────────────────
        uint8 withdrawalOffset; // In the withdrawals list.
        uint64 withdrawalIndex; // Network-wise.
        uint64 validatorIndex;
        uint64 amount;
        // ── Validator fields ──────────────────────────────────────────────────
        bytes32 withdrawalCredentials;
        uint64 effectiveBalance;
        bool slashed;
        uint64 activationEligibilityEpoch;
        uint64 activationEpoch;
        uint64 exitEpoch;
        uint64 withdrawableEpoch;
        // ── Proofs ────────────────────────────────────────────────────────────
        // We accept the `withdrawalProof` against a state root, because it saves a few hops.
        bytes32[] withdrawalProof;
        bytes32[] validatorProof;
    }

    // A witness for a block header which root is accessible via `historical_summaries` field.
    struct HistoricalHeaderWitness {
        BeaconBlockHeader header;
        bytes32[] proof;
    }

    error RootNotFound();
    error InvalidBlockHeader();
    error InvalidChainConfig();
    error PartialWithdrawal();
    error ValidatorNotWithdrawn();
    error InvalidWithdrawalAddress();
    error UnsupportedSlot(Slot slot);
    error ZeroModuleAddress();
    error ZeroWithdrawalAddress();
    error ZeroAdminAddress();
    error InvalidPivotSlot();
    error InvalidCapellaSlot();
    error HistoricalSummaryDoesNotExist();

    function PAUSE_ROLE() external view returns (bytes32);

    function RESUME_ROLE() external view returns (bytes32);

    function BEACON_ROOTS() external view returns (address);

    function SLOTS_PER_EPOCH() external view returns (uint64);

    function SLOTS_PER_HISTORICAL_ROOT() external view returns (uint64);

    function GI_FIRST_WITHDRAWAL_PREV() external view returns (GIndex);

    function GI_FIRST_WITHDRAWAL_CURR() external view returns (GIndex);

    function GI_FIRST_VALIDATOR_PREV() external view returns (GIndex);

    function GI_FIRST_VALIDATOR_CURR() external view returns (GIndex);

    function GI_FIRST_HISTORICAL_SUMMARY_PREV() external view returns (GIndex);

    function GI_FIRST_HISTORICAL_SUMMARY_CURR() external view returns (GIndex);

    function GI_FIRST_BLOCK_ROOT_IN_SUMMARY_PREV()
        external
        view
        returns (GIndex);

    function GI_FIRST_BLOCK_ROOT_IN_SUMMARY_CURR()
        external
        view
        returns (GIndex);

    function FIRST_SUPPORTED_SLOT() external view returns (Slot);

    function PIVOT_SLOT() external view returns (Slot);

    function CAPELLA_SLOT() external view returns (Slot);

    function WITHDRAWAL_ADDRESS() external view returns (address);

    function MODULE() external view returns (ICSModule);

    /// @notice Pause write methods calls for `duration` seconds
    /// @param duration Duration of the pause in seconds
    function pauseFor(uint256 duration) external;

    /// @notice Resume write methods calls
    function resume() external;

    /// @notice Verify withdrawal proof and report withdrawal to the module for valid proofs
    /// @param beaconBlock Beacon block header
    /// @param witness Withdrawal witness against the `beaconBlock`'s state root.
    /// @param nodeOperatorId ID of the Node Operator
    /// @param keyIndex Index of the validator key in the Node Operator's key storage
    function processWithdrawalProof(
        ProvableBeaconBlockHeader calldata beaconBlock,
        WithdrawalWitness calldata witness,
        uint256 nodeOperatorId,
        uint256 keyIndex
    ) external;

    /// @notice Verify withdrawal proof against historical summaries data and report withdrawal to the module for valid proofs
    /// @param beaconBlock Beacon block header
    /// @param oldBlock Historical block header witness
    /// @param witness Withdrawal witness
    /// @param nodeOperatorId ID of the Node Operator
    /// @param keyIndex Index of the validator key in the Node Operator's key storage
    function processHistoricalWithdrawalProof(
        ProvableBeaconBlockHeader calldata beaconBlock,
        HistoricalHeaderWitness calldata oldBlock,
        WithdrawalWitness calldata witness,
        uint256 nodeOperatorId,
        uint256 keyIndex
    ) external;
}

File 8 of 40 : ICSModule.sol
// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.24;

import { IStakingModule } from "./IStakingModule.sol";
import { ICSAccounting } from "./ICSAccounting.sol";
import { IQueueLib } from "../lib/QueueLib.sol";
import { INOAddresses } from "../lib/NOAddresses.sol";
import { IAssetRecovererLib } from "../lib/AssetRecovererLib.sol";
import { Batch } from "../lib/QueueLib.sol";
import { ILidoLocator } from "./ILidoLocator.sol";
import { IStETH } from "./IStETH.sol";
import { ICSParametersRegistry } from "./ICSParametersRegistry.sol";
import { ICSExitPenalties } from "./ICSExitPenalties.sol";

struct NodeOperator {
    // All the counters below are used together e.g. in the _updateDepositableValidatorsCount
    /* 1 */ uint32 totalAddedKeys; // @dev increased and decreased when removed
    /* 1 */ uint32 totalWithdrawnKeys; // @dev only increased
    /* 1 */ uint32 totalDepositedKeys; // @dev only increased
    /* 1 */ uint32 totalVettedKeys; // @dev both increased and decreased
    /* 1 */ uint32 stuckValidatorsCount; // @dev both increased and decreased
    /* 1 */ uint32 depositableValidatorsCount; // @dev any value
    /* 1 */ uint32 targetLimit;
    /* 1 */ uint8 targetLimitMode;
    /* 2 */ uint32 totalExitedKeys; // @dev only increased except for the unsafe updates
    /* 2 */ uint32 enqueuedCount; // Tracks how many places are occupied by the node operator's keys in the queue.
    /* 2 */ address managerAddress;
    /* 3 */ address proposedManagerAddress;
    /* 4 */ address rewardAddress;
    /* 5 */ address proposedRewardAddress;
    /* 5 */ bool extendedManagerPermissions;
    /* 5 */ bool usedPriorityQueue;
}

struct NodeOperatorManagementProperties {
    address managerAddress;
    address rewardAddress;
    bool extendedManagerPermissions;
}

struct ValidatorWithdrawalInfo {
    uint256 nodeOperatorId; // @dev ID of the Node Operator
    uint256 keyIndex; // @dev Index of the withdrawn key in the Node Operator's keys storage
    uint256 amount; // @dev Amount of withdrawn ETH in wei
}

/// @title Lido's Community Staking Module interface
interface ICSModule is
    IQueueLib,
    INOAddresses,
    IAssetRecovererLib,
    IStakingModule
{
    error CannotAddKeys();
    error NodeOperatorDoesNotExist();
    error SenderIsNotEligible();
    error InvalidVetKeysPointer();
    error ExitedKeysHigherThanTotalDeposited();
    error ExitedKeysDecrease();

    error InvalidInput();
    error NotEnoughKeys();
    error PriorityQueueAlreadyUsed();
    error NotEligibleForPriorityQueue();
    error PriorityQueueMaxDepositsUsed();
    error NoQueuedKeysToMigrate();

    error KeysLimitExceeded();
    error SigningKeysInvalidOffset();

    error InvalidAmount();

    error ZeroLocatorAddress();
    error ZeroAccountingAddress();
    error ZeroExitPenaltiesAddress();
    error ZeroAdminAddress();
    error ZeroSenderAddress();
    error ZeroParametersRegistryAddress();

    event NodeOperatorAdded(
        uint256 indexed nodeOperatorId,
        address indexed managerAddress,
        address indexed rewardAddress,
        bool extendedManagerPermissions
    );
    event ReferrerSet(uint256 indexed nodeOperatorId, address indexed referrer);
    event DepositableSigningKeysCountChanged(
        uint256 indexed nodeOperatorId,
        uint256 depositableKeysCount
    );
    event VettedSigningKeysCountChanged(
        uint256 indexed nodeOperatorId,
        uint256 vettedKeysCount
    );
    event VettedSigningKeysCountDecreased(uint256 indexed nodeOperatorId);
    event DepositedSigningKeysCountChanged(
        uint256 indexed nodeOperatorId,
        uint256 depositedKeysCount
    );
    event ExitedSigningKeysCountChanged(
        uint256 indexed nodeOperatorId,
        uint256 exitedKeysCount
    );
    event TotalSigningKeysCountChanged(
        uint256 indexed nodeOperatorId,
        uint256 totalKeysCount
    );
    event TargetValidatorsCountChanged(
        uint256 indexed nodeOperatorId,
        uint256 targetLimitMode,
        uint256 targetValidatorsCount
    );
    event WithdrawalSubmitted(
        uint256 indexed nodeOperatorId,
        uint256 keyIndex,
        uint256 amount,
        bytes pubkey
    );

    event BatchEnqueued(
        uint256 indexed queuePriority,
        uint256 indexed nodeOperatorId,
        uint256 count
    );

    event KeyRemovalChargeApplied(uint256 indexed nodeOperatorId);
    event ELRewardsStealingPenaltyReported(
        uint256 indexed nodeOperatorId,
        bytes32 proposedBlockHash,
        uint256 stolenAmount
    );
    event ELRewardsStealingPenaltyCancelled(
        uint256 indexed nodeOperatorId,
        uint256 amount
    );
    event ELRewardsStealingPenaltyCompensated(
        uint256 indexed nodeOperatorId,
        uint256 amount
    );
    event ELRewardsStealingPenaltySettled(uint256 indexed nodeOperatorId);

    function PAUSE_ROLE() external view returns (bytes32);

    function RESUME_ROLE() external view returns (bytes32);

    function STAKING_ROUTER_ROLE() external view returns (bytes32);

    function REPORT_EL_REWARDS_STEALING_PENALTY_ROLE()
        external
        view
        returns (bytes32);

    function SETTLE_EL_REWARDS_STEALING_PENALTY_ROLE()
        external
        view
        returns (bytes32);

    function VERIFIER_ROLE() external view returns (bytes32);

    function RECOVERER_ROLE() external view returns (bytes32);

    function CREATE_NODE_OPERATOR_ROLE() external view returns (bytes32);

    function DEPOSIT_SIZE() external view returns (uint256);

    function LIDO_LOCATOR() external view returns (ILidoLocator);

    function STETH() external view returns (IStETH);

    function PARAMETERS_REGISTRY()
        external
        view
        returns (ICSParametersRegistry);

    function ACCOUNTING() external view returns (ICSAccounting);

    function EXIT_PENALTIES() external view returns (ICSExitPenalties);

    function FEE_DISTRIBUTOR() external view returns (address);

    function QUEUE_LOWEST_PRIORITY() external view returns (uint256);

    function QUEUE_LEGACY_PRIORITY() external view returns (uint256);

    /// @notice Returns the address of the accounting contract
    function accounting() external view returns (ICSAccounting);

    /// @notice Pause creation of the Node Operators and keys upload for `duration` seconds.
    ///         Existing NO management and reward claims are still available.
    ///         To pause reward claims use pause method on CSAccounting
    /// @param duration Duration of the pause in seconds
    function pauseFor(uint256 duration) external;

    /// @notice Resume creation of the Node Operators and keys upload
    function resume() external;

    /// @notice Returns the initialized version of the contract
    function getInitializedVersion() external view returns (uint64);

    /// @notice Permissioned method to add a new Node Operator
    ///         Should be called by `*Gate.sol` contracts. See `PermissionlessGate.sol` and `VettedGate.sol` for examples
    /// @param from Sender address. Initial sender address to be used as a default manager and reward addresses.
    ///             Gates must pass the correct address in order to specify which address should be the owner of the Node Operator.
    /// @param managementProperties Optional. Management properties to be used for the Node Operator.
    ///                             managerAddress: Used as `managerAddress` for the Node Operator. If not passed `from` will be used.
    ///                             rewardAddress: Used as `rewardAddress` for the Node Operator. If not passed `from` will be used.
    ///                             extendedManagerPermissions: Flag indicating that `managerAddress` will be able to change `rewardAddress`.
    ///                                                         If set to true `resetNodeOperatorManagerAddress` method will be disabled
    /// @param referrer Optional. Referrer address. Should be passed when Node Operator is created using partners integration
    function createNodeOperator(
        address from,
        NodeOperatorManagementProperties memory managementProperties,
        address referrer
    ) external returns (uint256 nodeOperatorId);

    /// @notice Add new keys to the existing Node Operator using ETH as a bond
    /// @param from Sender address. Commonly equals to `msg.sender` except for the case of Node Operator creation by `*Gate.sol` contracts
    /// @param nodeOperatorId ID of the Node Operator
    /// @param keysCount Signing keys count
    /// @param publicKeys Public keys to submit
    /// @param signatures Signatures of `(deposit_message_root, domain)` tuples
    ///                   https://github.com/ethereum/consensus-specs/blob/v1.4.0/specs/phase0/beacon-chain.md#signingdata
    function addValidatorKeysETH(
        address from,
        uint256 nodeOperatorId,
        uint256 keysCount,
        bytes memory publicKeys,
        bytes memory signatures
    ) external payable;

    /// @notice Add new keys to the existing Node Operator using stETH as a bond
    /// @notice Due to the stETH rounding issue make sure to make approval or sign permit with extra 10 wei to avoid revert
    /// @param from Sender address. Commonly equals to `msg.sender` except for the case of Node Operator creation by `*Gate.sol` contracts
    /// @param nodeOperatorId ID of the Node Operator
    /// @param keysCount Signing keys count
    /// @param publicKeys Public keys to submit
    /// @param signatures Signatures of `(deposit_message_root, domain)` tuples
    ///                   https://github.com/ethereum/consensus-specs/blob/v1.4.0/specs/phase0/beacon-chain.md#signingdata
    /// @param permit Optional. Permit to use stETH as bond
    function addValidatorKeysStETH(
        address from,
        uint256 nodeOperatorId,
        uint256 keysCount,
        bytes memory publicKeys,
        bytes memory signatures,
        ICSAccounting.PermitInput memory permit
    ) external;

    /// @notice Add new keys to the existing Node Operator using wstETH as a bond
    /// @notice Due to the stETH rounding issue make sure to make approval or sign permit with extra 10 wei to avoid revert
    /// @param from Sender address. Commonly equals to `msg.sender` except for the case of Node Operator creation by `*Gate.sol` contracts
    /// @param nodeOperatorId ID of the Node Operator
    /// @param keysCount Signing keys count
    /// @param publicKeys Public keys to submit
    /// @param signatures Signatures of `(deposit_message_root, domain)` tuples
    ///                   https://github.com/ethereum/consensus-specs/blob/v1.4.0/specs/phase0/beacon-chain.md#signingdata
    /// @param permit Optional. Permit to use wstETH as bond
    function addValidatorKeysWstETH(
        address from,
        uint256 nodeOperatorId,
        uint256 keysCount,
        bytes memory publicKeys,
        bytes memory signatures,
        ICSAccounting.PermitInput memory permit
    ) external;

    /// @notice Report EL rewards stealing for the given Node Operator
    /// @notice The final locked amount will be equal to the stolen funds plus EL stealing additional fine
    /// @param nodeOperatorId ID of the Node Operator
    /// @param blockHash Execution layer block hash of the proposed block with EL rewards stealing
    /// @param amount Amount of stolen EL rewards in ETH
    function reportELRewardsStealingPenalty(
        uint256 nodeOperatorId,
        bytes32 blockHash,
        uint256 amount
    ) external;

    /// @notice Compensate EL rewards stealing penalty for the given Node Operator to prevent further validator exits
    /// @dev Can only be called by the Node Operator manager
    /// @param nodeOperatorId ID of the Node Operator
    function compensateELRewardsStealingPenalty(
        uint256 nodeOperatorId
    ) external payable;

    /// @notice Cancel previously reported and not settled EL rewards stealing penalty for the given Node Operator
    /// @notice The funds will be unlocked
    /// @param nodeOperatorId ID of the Node Operator
    /// @param amount Amount of penalty to cancel
    function cancelELRewardsStealingPenalty(
        uint256 nodeOperatorId,
        uint256 amount
    ) external;

    /// @notice Settle locked bond for the given Node Operators
    /// @dev SETTLE_EL_REWARDS_STEALING_PENALTY_ROLE role is expected to be assigned to Easy Track
    /// @param nodeOperatorIds IDs of the Node Operators
    function settleELRewardsStealingPenalty(
        uint256[] memory nodeOperatorIds
    ) external;

    /// @notice Propose a new manager address for the Node Operator
    /// @param nodeOperatorId ID of the Node Operator
    /// @param proposedAddress Proposed manager address
    function proposeNodeOperatorManagerAddressChange(
        uint256 nodeOperatorId,
        address proposedAddress
    ) external;

    /// @notice Confirm a new manager address for the Node Operator.
    ///         Should be called from the currently proposed address
    /// @param nodeOperatorId ID of the Node Operator
    function confirmNodeOperatorManagerAddressChange(
        uint256 nodeOperatorId
    ) external;

    /// @notice Reset the manager address to the reward address.
    ///         Should be called from the reward address
    /// @param nodeOperatorId ID of the Node Operator
    function resetNodeOperatorManagerAddress(uint256 nodeOperatorId) external;

    /// @notice Propose a new reward address for the Node Operator
    /// @param nodeOperatorId ID of the Node Operator
    /// @param proposedAddress Proposed reward address
    function proposeNodeOperatorRewardAddressChange(
        uint256 nodeOperatorId,
        address proposedAddress
    ) external;

    /// @notice Confirm a new reward address for the Node Operator.
    ///         Should be called from the currently proposed address
    /// @param nodeOperatorId ID of the Node Operator
    function confirmNodeOperatorRewardAddressChange(
        uint256 nodeOperatorId
    ) external;

    /// @notice Change rewardAddress if extendedManagerPermissions is enabled for the Node Operator
    /// @param nodeOperatorId ID of the Node Operator
    /// @param newAddress Proposed reward address
    function changeNodeOperatorRewardAddress(
        uint256 nodeOperatorId,
        address newAddress
    ) external;

    /// @notice Get the pointers to the head and tail of queue with the given priority.
    /// @param queuePriority Priority of the queue to get the pointers.
    /// @return head Pointer to the head of the queue.
    /// @return tail Pointer to the tail of the queue.
    function depositQueuePointers(
        uint256 queuePriority
    ) external view returns (uint128 head, uint128 tail);

    /// @notice Get the deposit queue item by an index
    /// @param queuePriority Priority of the queue to get an item from
    /// @param index Index of a queue item
    /// @return Deposit queue item from the priority queue
    function depositQueueItem(
        uint256 queuePriority,
        uint128 index
    ) external view returns (Batch);

    /// @notice Clean the deposit queue from batches with no depositable keys
    /// @dev Use **eth_call** to check how many items will be removed
    /// @param maxItems How many queue items to review
    /// @return removed Count of batches to be removed by visiting `maxItems` batches
    /// @return lastRemovedAtDepth The value to use as `maxItems` to remove `removed` batches if the static call of the method was used
    function cleanDepositQueue(
        uint256 maxItems
    ) external returns (uint256 removed, uint256 lastRemovedAtDepth);

    /// @notice Update depositable validators data and enqueue all unqueued keys for the given Node Operator.
    ///         Unqueued stands for vetted but not enqueued keys.
    /// @dev The following rules are applied:
    ///         - Unbonded keys can not be depositable
    ///         - Unvetted keys can not be depositable
    ///         - Depositable keys count should respect targetLimit value
    /// @param nodeOperatorId ID of the Node Operator
    function updateDepositableValidatorsCount(uint256 nodeOperatorId) external;

    /// Performs a one-time migration of allocated seats from the legacy or default queue to a priority queue
    /// for an eligible node operator. This is possible, e.g., in the following scenario: A node
    /// operator uploaded keys before CSM v2 and have no deposits due to a long queue.
    /// After the CSM v2 release, the node operator has claimed the ICS or other priority node operator type.
    /// This node operator type gives the node operator the ability to get several deposits through
    /// the priority queue. So, by calling the migration method, the node operator can obtain seats
    /// in the priority queue, even though they already have seats in the legacy queue.
    /// The method can also be used by the node operators who joined CSM v2 permissionlessly after the release
    /// and had their node operator type upgraded to ICS or another priority type.
    /// The method does not remove the old queue items. Hence, the node operator can upload additional keys that
    /// will take the place of the migrated keys in the original queue.
    /// @param nodeOperatorId ID of the Node Operator
    function migrateToPriorityQueue(uint256 nodeOperatorId) external;

    /// @notice Get Node Operator info
    /// @param nodeOperatorId ID of the Node Operator
    /// @return Node Operator info
    function getNodeOperator(
        uint256 nodeOperatorId
    ) external view returns (NodeOperator memory);

    /// @notice Get Node Operator management properties
    /// @param nodeOperatorId ID of the Node Operator
    /// @return Node Operator management properties
    function getNodeOperatorManagementProperties(
        uint256 nodeOperatorId
    ) external view returns (NodeOperatorManagementProperties memory);

    /// @notice Get Node Operator owner. Owner is manager address if `extendedManagerPermissions` is enabled and reward address otherwise
    /// @param nodeOperatorId ID of the Node Operator
    /// @return Node Operator owner
    function getNodeOperatorOwner(
        uint256 nodeOperatorId
    ) external view returns (address);

    /// @notice Get Node Operator non-withdrawn keys
    /// @param nodeOperatorId ID of the Node Operator
    /// @return Non-withdrawn keys count
    function getNodeOperatorNonWithdrawnKeys(
        uint256 nodeOperatorId
    ) external view returns (uint256);

    /// @notice Get Node Operator total deposited keys
    /// @param nodeOperatorId ID of the Node Operator
    /// @return Total deposited keys count
    function getNodeOperatorTotalDepositedKeys(
        uint256 nodeOperatorId
    ) external view returns (uint256);

    /// @notice Get Node Operator signing keys
    /// @param nodeOperatorId ID of the Node Operator
    /// @param startIndex Index of the first key
    /// @param keysCount Count of keys to get
    /// @return Signing keys
    function getSigningKeys(
        uint256 nodeOperatorId,
        uint256 startIndex,
        uint256 keysCount
    ) external view returns (bytes memory);

    /// @notice Get Node Operator signing keys with signatures
    /// @param nodeOperatorId ID of the Node Operator
    /// @param startIndex Index of the first key
    /// @param keysCount Count of keys to get
    /// @return keys Signing keys
    /// @return signatures Signatures of `(deposit_message_root, domain)` tuples
    ///                    https://github.com/ethereum/consensus-specs/blob/v1.4.0/specs/phase0/beacon-chain.md#signingdata
    function getSigningKeysWithSignatures(
        uint256 nodeOperatorId,
        uint256 startIndex,
        uint256 keysCount
    ) external view returns (bytes memory keys, bytes memory signatures);

    /// @notice Report Node Operator's keys as withdrawn and settle withdrawn amount
    /// @notice Called by `CSVerifier` contract.
    ///         See `CSVerifier.processWithdrawalProof` to use this method permissionless
    /// @param withdrawalsInfo An array for the validator withdrawals info structs
    function submitWithdrawals(
        ValidatorWithdrawalInfo[] calldata withdrawalsInfo
    ) external;

    /// @notice Check if the given Node Operator's key is reported as withdrawn
    /// @param nodeOperatorId ID of the Node Operator
    /// @param keyIndex index of the key to check
    /// @return Is validator reported as withdrawn or not
    function isValidatorWithdrawn(
        uint256 nodeOperatorId,
        uint256 keyIndex
    ) external view returns (bool);

    /// @notice Remove keys for the Node Operator and confiscate removal charge for each deleted key
    ///         This method is a part of the Optimistic Vetting scheme. After key deletion `totalVettedKeys`
    ///         is set equal to `totalAddedKeys`. If invalid keys are not removed, the unvetting process will be repeated
    ///         and `decreaseVettedSigningKeysCount` will be called by StakingRouter.
    /// @param nodeOperatorId ID of the Node Operator
    /// @param startIndex Index of the first key
    /// @param keysCount Keys count to delete
    function removeKeys(
        uint256 nodeOperatorId,
        uint256 startIndex,
        uint256 keysCount
    ) external;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/extensions/IAccessControlEnumerable.sol)

pragma solidity ^0.8.20;

import {IAccessControl} from "../IAccessControl.sol";

/**
 * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
 */
interface IAccessControlEnumerable is IAccessControl {
    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) external view returns (address);

    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) external view returns (uint256);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)

pragma solidity ^0.8.20;

import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    mapping(bytes32 role => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        return _roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        if (!hasRole(role, account)) {
            _roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        if (hasRole(role, account)) {
            _roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes32 value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}

/*
 * SPDX-License-Identifier: MIT
 */

pragma solidity 0.8.24;

/**
 * @notice Aragon Unstructured Storage library
 */
library UnstructuredStorage {
    function setStorageAddress(bytes32 position, address data) internal {
        assembly {
            sstore(position, data)
        }
    }

    function setStorageUint256(bytes32 position, uint256 data) internal {
        assembly {
            sstore(position, data)
        }
    }

    function getStorageAddress(
        bytes32 position
    ) internal view returns (address data) {
        assembly {
            data := sload(position)
        }
    }

    function getStorageUint256(
        bytes32 position
    ) internal view returns (uint256 data) {
        assembly {
            data := sload(position)
        }
    }
}

// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.24;

/// @title Lido's Staking Module interface
interface IStakingModule {
    /// @dev Event to be emitted on StakingModule's nonce change
    event NonceChanged(uint256 nonce);

    /// @dev Event to be emitted when a signing key is added to the StakingModule
    event SigningKeyAdded(uint256 indexed nodeOperatorId, bytes pubkey);

    /// @dev Event to be emitted when a signing key is removed from the StakingModule
    event SigningKeyRemoved(uint256 indexed nodeOperatorId, bytes pubkey);

    /// @notice Handles tracking and penalization logic for a validator that remains active beyond its eligible exit window.
    /// @dev This function is called by the StakingRouter to report the current exit-related status of a validator
    ///      belonging to a specific node operator. It accepts a validator's public key, associated
    ///      with the duration (in seconds) it was eligible to exit but has not exited.
    ///      This data could be used to trigger penalties for the node operator if the validator has exceeded the allowed exit window.
    /// @param _nodeOperatorId The ID of the node operator whose validator's status is being delivered.
    /// @param _proofSlotTimestamp The timestamp (slot time) when the validator was last known to be in an active ongoing state.
    /// @param _publicKey The public key of the validator being reported.
    /// @param _eligibleToExitInSec The duration (in seconds) indicating how long the validator has been eligible to exit but has not exited.
    function reportValidatorExitDelay(
        uint256 _nodeOperatorId,
        uint256 _proofSlotTimestamp,
        bytes calldata _publicKey,
        uint256 _eligibleToExitInSec
    ) external;

    /// @notice Handles the triggerable exit event for a validator belonging to a specific node operator.
    /// @dev This function is called by the StakingRouter when a validator is exited using the triggerable
    ///      exit request on the Execution Layer (EL).
    /// @param _nodeOperatorId The ID of the node operator.
    /// @param _publicKey The public key of the validator being reported.
    /// @param _withdrawalRequestPaidFee Fee amount paid to send a withdrawal request on the Execution Layer (EL).
    /// @param _exitType The type of exit being performed.
    ///        This parameter may be interpreted differently across various staking modules, depending on their specific implementation.
    function onValidatorExitTriggered(
        uint256 _nodeOperatorId,
        bytes calldata _publicKey,
        uint256 _withdrawalRequestPaidFee,
        uint256 _exitType
    ) external;

    /// @notice Determines whether a validator's exit status should be updated and will have an effect on the Node Operator.
    /// @param _nodeOperatorId The ID of the node operator.
    /// @param _proofSlotTimestamp The timestamp (slot time) when the validator was last known to be in an active ongoing state.
    /// @param _publicKey The public key of the validator.
    /// @param _eligibleToExitInSec The number of seconds the validator was eligible to exit but did not.
    /// @return bool Returns true if the contract should receive the updated status of the validator.
    function isValidatorExitDelayPenaltyApplicable(
        uint256 _nodeOperatorId,
        uint256 _proofSlotTimestamp,
        bytes calldata _publicKey,
        uint256 _eligibleToExitInSec
    ) external view returns (bool);

    /// @notice Returns the number of seconds after which a validator is considered late.
    /// @param _nodeOperatorId The ID of the node operator.
    /// @return The exit deadline threshold in seconds.
    function exitDeadlineThreshold(
        uint256 _nodeOperatorId
    ) external view returns (uint256);

    /// @notice Returns the type of the staking module
    /// @return Module type
    function getType() external view returns (bytes32);

    /// @notice Returns all-validators summary in the staking module
    /// @return totalExitedValidators total number of validators in the EXITED state
    ///     on the Consensus Layer. This value can't decrease in normal conditions
    /// @return totalDepositedValidators total number of validators deposited via the
    ///     official Deposit Contract. This value is a cumulative counter: even when the validator
    ///     goes into EXITED state this counter is not decreasing
    /// @return depositableValidatorsCount number of validators in the set available for deposit
    function getStakingModuleSummary()
        external
        view
        returns (
            uint256 totalExitedValidators,
            uint256 totalDepositedValidators,
            uint256 depositableValidatorsCount
        );

    /// @notice Returns all-validators summary belonging to the node operator with the given id
    /// @param nodeOperatorId id of the operator to return report for
    /// @return targetLimitMode shows whether the current target limit applied to the node operator (1 = soft mode, 2 = forced mode)
    /// @return targetValidatorsCount relative target active validators limit for operator
    /// @return stuckValidatorsCount number of validators with an expired request to exit time
    /// @return refundedValidatorsCount number of validators that can't be withdrawn, but deposit
    ///     costs were compensated to the Lido by the node operator
    /// @return stuckPenaltyEndTimestamp time when the penalty for stuck validators stops applying
    ///     to node operator rewards
    /// @return totalExitedValidators total number of validators in the EXITED state
    ///     on the Consensus Layer. This value can't decrease in normal conditions
    /// @return totalDepositedValidators total number of validators deposited via the official
    ///     Deposit Contract. This value is a cumulative counter: even when the validator goes into
    ///     EXITED state this counter is not decreasing
    /// @return depositableValidatorsCount number of validators in the set available for deposit
    function getNodeOperatorSummary(
        uint256 nodeOperatorId
    )
        external
        view
        returns (
            uint256 targetLimitMode,
            uint256 targetValidatorsCount,
            uint256 stuckValidatorsCount,
            uint256 refundedValidatorsCount,
            uint256 stuckPenaltyEndTimestamp,
            uint256 totalExitedValidators,
            uint256 totalDepositedValidators,
            uint256 depositableValidatorsCount
        );

    /// @notice Returns a counter that MUST change its value whenever the deposit data set changes.
    ///     Below is the typical list of actions that requires an update of the nonce:
    ///     1. a node operator's deposit data is added
    ///     2. a node operator's deposit data is removed
    ///     3. a node operator's ready-to-deposit data size is changed
    ///     4. a node operator was activated/deactivated
    ///     5. a node operator's deposit data is used for the deposit
    ///     Note: Depending on the StakingModule implementation above list might be extended
    /// @dev In some scenarios, it's allowed to update nonce without actual change of the deposit
    ///      data subset, but it MUST NOT lead to the DOS of the staking module via continuous
    ///      update of the nonce by the malicious actor
    function getNonce() external view returns (uint256);

    /// @notice Returns total number of node operators
    function getNodeOperatorsCount() external view returns (uint256);

    /// @notice Returns number of active node operators
    function getActiveNodeOperatorsCount() external view returns (uint256);

    /// @notice Returns if the node operator with given id is active
    /// @param nodeOperatorId Id of the node operator
    function getNodeOperatorIsActive(
        uint256 nodeOperatorId
    ) external view returns (bool);

    /// @notice Returns up to `limit` node operator ids starting from the `offset`. The order of
    ///     the returned ids is not defined and might change between calls.
    /// @dev This view must not revert in case of invalid data passed. When `offset` exceeds the
    ///     total node operators count or when `limit` is equal to 0 MUST be returned empty array.
    function getNodeOperatorIds(
        uint256 offset,
        uint256 limit
    ) external view returns (uint256[] memory nodeOperatorIds);

    /// @notice Called by StakingRouter to signal that stETH rewards were minted for this module.
    /// @param totalShares Amount of stETH shares that were minted to reward all node operators.
    /// @dev IMPORTANT: this method SHOULD revert with empty error data ONLY because of "out of gas".
    ///      Details about error data: https://docs.soliditylang.org/en/v0.8.9/control-structures.html#error-handling-assert-require-revert-and-exceptions
    function onRewardsMinted(uint256 totalShares) external;

    /// @notice Called by StakingRouter to decrease the number of vetted keys for Node Operators with given ids
    /// @param nodeOperatorIds Bytes packed array of the Node Operator ids
    /// @param vettedSigningKeysCounts Bytes packed array of the new numbers of vetted keys for the Node Operators
    function decreaseVettedSigningKeysCount(
        bytes calldata nodeOperatorIds,
        bytes calldata vettedSigningKeysCounts
    ) external;

    /// @notice Updates the number of the validators in the EXITED state for node operator with given id
    /// @param nodeOperatorIds bytes packed array of the node operators id
    /// @param exitedValidatorsCounts bytes packed array of the new number of EXITED validators for the node operators
    function updateExitedValidatorsCount(
        bytes calldata nodeOperatorIds,
        bytes calldata exitedValidatorsCounts
    ) external;

    /// @notice Updates the limit of the validators that can be used for deposit
    /// @param nodeOperatorId ID of the Node Operator
    /// @param targetLimitMode Target limit mode for the Node Operator (see https://hackmd.io/@lido/BJXRTxMRp)
    ///                        0 - disabled
    ///                        1 - soft mode
    ///                        2 - forced mode
    /// @param targetLimit Target limit of validators
    function updateTargetValidatorsLimits(
        uint256 nodeOperatorId,
        uint256 targetLimitMode,
        uint256 targetLimit
    ) external;

    /// @notice Unsafely updates the number of validators in the EXITED/STUCK states for node operator with given id
    ///      'unsafely' means that this method can both increase and decrease exited and stuck counters
    /// @param _nodeOperatorId Id of the node operator
    /// @param _exitedValidatorsCount New number of EXITED validators for the node operator
    function unsafeUpdateValidatorsCount(
        uint256 _nodeOperatorId,
        uint256 _exitedValidatorsCount
    ) external;

    /// @notice Obtains deposit data to be used by StakingRouter to deposit to the Ethereum Deposit
    ///     contract
    /// @dev The method MUST revert when the staking module has not enough deposit data items
    /// @param depositsCount Number of deposits to be done
    /// @param depositCalldata Staking module defined data encoded as bytes.
    ///        IMPORTANT: depositCalldata MUST NOT modify the deposit data set of the staking module
    /// @return publicKeys Batch of the concatenated public validators keys
    /// @return signatures Batch of the concatenated deposit signatures for returned public keys
    function obtainDepositData(
        uint256 depositsCount,
        bytes calldata depositCalldata
    ) external returns (bytes memory publicKeys, bytes memory signatures);

    /// @notice Called by StakingRouter after it finishes updating exited and stuck validators
    /// counts for this module's node operators.
    ///
    /// Guaranteed to be called after an oracle report is applied, regardless of whether any node
    /// operator in this module has actually received any updated counts as a result of the report
    /// but given that the total number of exited validators returned from getStakingModuleSummary
    /// is the same as StakingRouter expects based on the total count received from the oracle.
    ///
    /// @dev IMPORTANT: this method SHOULD revert with empty error data ONLY because of "out of gas".
    ///      Details about error data: https://docs.soliditylang.org/en/v0.8.9/control-structures.html#error-handling-assert-require-revert-and-exceptions
    function onExitedAndStuckValidatorsCountsUpdated() external;

    /// @notice Called by StakingRouter when withdrawal credentials are changed.
    /// @dev This method MUST discard all StakingModule's unused deposit data cause they become
    ///      invalid after the withdrawal credentials are changed
    ///
    /// @dev IMPORTANT: this method SHOULD revert with empty error data ONLY because of "out of gas".
    ///      Details about error data: https://docs.soliditylang.org/en/v0.8.9/control-structures.html#error-handling-assert-require-revert-and-exceptions
    function onWithdrawalCredentialsChanged() external;
}

File 14 of 40 : ICSAccounting.sol
// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.24;

import { ICSBondCore } from "./ICSBondCore.sol";
import { ICSBondCurve } from "./ICSBondCurve.sol";
import { ICSBondLock } from "./ICSBondLock.sol";
import { ICSFeeDistributor } from "./ICSFeeDistributor.sol";
import { IAssetRecovererLib } from "../lib/AssetRecovererLib.sol";
import { ICSModule } from "./ICSModule.sol";

interface ICSAccounting is
    ICSBondCore,
    ICSBondCurve,
    ICSBondLock,
    IAssetRecovererLib
{
    struct PermitInput {
        uint256 value;
        uint256 deadline;
        uint8 v;
        bytes32 r;
        bytes32 s;
    }

    event BondLockCompensated(uint256 indexed nodeOperatorId, uint256 amount);
    event ChargePenaltyRecipientSet(address chargePenaltyRecipient);

    error SenderIsNotModule();
    error SenderIsNotEligible();
    error ZeroModuleAddress();
    error ZeroAdminAddress();
    error ZeroFeeDistributorAddress();
    error ZeroChargePenaltyRecipientAddress();
    error NodeOperatorDoesNotExist();
    error ElRewardsVaultReceiveFailed();
    error InvalidBondCurvesLength();

    function PAUSE_ROLE() external view returns (bytes32);

    function RESUME_ROLE() external view returns (bytes32);

    function MANAGE_BOND_CURVES_ROLE() external view returns (bytes32);

    function SET_BOND_CURVE_ROLE() external view returns (bytes32);

    function RECOVERER_ROLE() external view returns (bytes32);

    function MODULE() external view returns (ICSModule);

    function FEE_DISTRIBUTOR() external view returns (ICSFeeDistributor);

    function feeDistributor() external view returns (ICSFeeDistributor);

    function chargePenaltyRecipient() external view returns (address);

    /// @notice Get the initialized version of the contract
    function getInitializedVersion() external view returns (uint64);

    /// @notice Resume reward claims and deposits
    function resume() external;

    /// @notice Pause reward claims and deposits for `duration` seconds
    /// @dev Must be called together with `CSModule.pauseFor`
    /// @dev Passing MAX_UINT_256 as `duration` pauses indefinitely
    /// @param duration Duration of the pause in seconds
    function pauseFor(uint256 duration) external;

    /// @notice Set charge recipient address
    /// @param _chargePenaltyRecipient Charge recipient address
    function setChargePenaltyRecipient(
        address _chargePenaltyRecipient
    ) external;

    /// @notice Set bond lock period
    /// @param period Period in seconds to retain bond lock
    function setBondLockPeriod(uint256 period) external;

    /// @notice Add a new bond curve
    /// @param bondCurve Bond curve definition to add
    /// @return id Id of the added curve
    function addBondCurve(
        BondCurveIntervalInput[] calldata bondCurve
    ) external returns (uint256 id);

    /// @notice Update existing bond curve
    /// @dev If the curve is updated to a curve with higher values for any point,
    ///      Extensive checks and actions should be performed by the method caller to avoid
    ///      inconsistency in the keys accounting. A manual update of the depositable validators count
    ///      in CSM might be required to ensure that the keys pointers are consistent.
    /// @param curveId Bond curve ID to update
    /// @param bondCurve Bond curve definition
    function updateBondCurve(
        uint256 curveId,
        BondCurveIntervalInput[] calldata bondCurve
    ) external;

    /// @notice Get the required bond in ETH (inc. missed and excess) for the given Node Operator to upload new deposit data
    /// @param nodeOperatorId ID of the Node Operator
    /// @param additionalKeys Number of new keys to add
    /// @return Required bond amount in ETH
    function getRequiredBondForNextKeys(
        uint256 nodeOperatorId,
        uint256 additionalKeys
    ) external view returns (uint256);

    /// @notice Get the bond amount in wstETH required for the `keysCount` keys using the default bond curve
    /// @param keysCount Keys count to calculate the required bond amount
    /// @param curveId Id of the curve to perform calculations against
    /// @return wstETH amount required for the `keysCount`
    function getBondAmountByKeysCountWstETH(
        uint256 keysCount,
        uint256 curveId
    ) external view returns (uint256);

    /// @notice Get the required bond in wstETH (inc. missed and excess) for the given Node Operator to upload new keys
    /// @param nodeOperatorId ID of the Node Operator
    /// @param additionalKeys Number of new keys to add
    /// @return Required bond in wstETH
    function getRequiredBondForNextKeysWstETH(
        uint256 nodeOperatorId,
        uint256 additionalKeys
    ) external view returns (uint256);

    /// @notice Get the number of the unbonded keys
    /// @param nodeOperatorId ID of the Node Operator
    /// @return Unbonded keys count
    function getUnbondedKeysCount(
        uint256 nodeOperatorId
    ) external view returns (uint256);

    /// @notice Get the number of the unbonded keys to be ejected using a forcedTargetLimit
    ///         Locked bond is not considered for this calculation to allow Node Operators to
    ///         compensate the locked bond via `compensateLockedBondETH` method before the ejection happens
    /// @param nodeOperatorId ID of the Node Operator
    /// @return Unbonded keys count
    function getUnbondedKeysCountToEject(
        uint256 nodeOperatorId
    ) external view returns (uint256);

    /// @notice Get current and required bond amounts in ETH (stETH) for the given Node Operator
    /// @dev To calculate excess bond amount subtract `required` from `current` value.
    ///      To calculate missed bond amount subtract `current` from `required` value
    /// @param nodeOperatorId ID of the Node Operator
    /// @return current Current bond amount in ETH
    /// @return required Required bond amount in ETH
    function getBondSummary(
        uint256 nodeOperatorId
    ) external view returns (uint256 current, uint256 required);

    /// @notice Get current and required bond amounts in stETH shares for the given Node Operator
    /// @dev To calculate excess bond amount subtract `required` from `current` value.
    ///      To calculate missed bond amount subtract `current` from `required` value
    /// @param nodeOperatorId ID of the Node Operator
    /// @return current Current bond amount in stETH shares
    /// @return required Required bond amount in stETH shares
    function getBondSummaryShares(
        uint256 nodeOperatorId
    ) external view returns (uint256 current, uint256 required);

    /// @notice Get current claimable bond in stETH shares for the given Node Operator
    /// @param nodeOperatorId ID of the Node Operator
    /// @return Current claimable bond in stETH shares
    function getClaimableBondShares(
        uint256 nodeOperatorId
    ) external view returns (uint256);

    /// @notice Get current claimable bond in stETH shares for the given Node Operator
    ///         Includes potential rewards distributed by the Fee Distributor
    /// @param nodeOperatorId ID of the Node Operator
    /// @param cumulativeFeeShares Cumulative fee stETH shares for the Node Operator
    /// @param rewardsProof Merkle proof of the rewards
    /// @return Current claimable bond in stETH shares
    function getClaimableRewardsAndBondShares(
        uint256 nodeOperatorId,
        uint256 cumulativeFeeShares,
        bytes32[] calldata rewardsProof
    ) external view returns (uint256);

    /// @notice Unwrap the user's wstETH and deposit stETH to the bond for the given Node Operator
    /// @dev Called by CSM exclusively. CSM should check node operator existence and update depositable validators count
    /// @param from Address to unwrap wstETH from
    /// @param nodeOperatorId ID of the Node Operator
    /// @param wstETHAmount Amount of wstETH to deposit
    /// @param permit wstETH permit for the contract
    function depositWstETH(
        address from,
        uint256 nodeOperatorId,
        uint256 wstETHAmount,
        PermitInput calldata permit
    ) external;

    /// @notice Unwrap the user's wstETH and deposit stETH to the bond for the given Node Operator
    /// @dev Permissionless. Enqueues Node Operator's keys if needed
    /// @param nodeOperatorId ID of the Node Operator
    /// @param wstETHAmount Amount of wstETH to deposit
    /// @param permit wstETH permit for the contract
    function depositWstETH(
        uint256 nodeOperatorId,
        uint256 wstETHAmount,
        PermitInput calldata permit
    ) external;

    /// @notice Deposit user's stETH to the bond for the given Node Operator
    /// @dev Called by CSM exclusively. CSM should check node operator existence and update depositable validators count
    /// @param from Address to deposit stETH from.
    /// @param nodeOperatorId ID of the Node Operator
    /// @param stETHAmount Amount of stETH to deposit
    /// @param permit stETH permit for the contract
    function depositStETH(
        address from,
        uint256 nodeOperatorId,
        uint256 stETHAmount,
        PermitInput calldata permit
    ) external;

    /// @notice Deposit user's stETH to the bond for the given Node Operator
    /// @dev Permissionless. Enqueues Node Operator's keys if needed
    /// @param nodeOperatorId ID of the Node Operator
    /// @param stETHAmount Amount of stETH to deposit
    /// @param permit stETH permit for the contract
    function depositStETH(
        uint256 nodeOperatorId,
        uint256 stETHAmount,
        PermitInput calldata permit
    ) external;

    /// @notice Stake user's ETH with Lido and deposit stETH to the bond
    /// @dev Called by CSM exclusively. CSM should check node operator existence and update depositable validators count
    /// @param from Address to stake ETH and deposit stETH from
    /// @param nodeOperatorId ID of the Node Operator
    function depositETH(address from, uint256 nodeOperatorId) external payable;

    /// @notice Stake user's ETH with Lido and deposit stETH to the bond
    /// @dev Permissionless. Enqueues Node Operator's keys if needed
    /// @param nodeOperatorId ID of the Node Operator
    function depositETH(uint256 nodeOperatorId) external payable;

    /// @notice Claim full reward (fee + bond) in stETH for the given Node Operator with desirable value.
    ///         `rewardsProof` and `cumulativeFeeShares` might be empty in order to claim only excess bond
    /// @param nodeOperatorId ID of the Node Operator
    /// @param stETHAmount Amount of stETH to claim
    /// @param cumulativeFeeShares Cumulative fee stETH shares for the Node Operator
    /// @param rewardsProof Merkle proof of the rewards
    /// @return shares Amount of stETH shares claimed
    /// @dev It's impossible to use single-leaf proof via this method, so this case should be treated carefully by
    /// off-chain tooling, e.g. to make sure a tree has at least 2 leafs.
    function claimRewardsStETH(
        uint256 nodeOperatorId,
        uint256 stETHAmount,
        uint256 cumulativeFeeShares,
        bytes32[] calldata rewardsProof
    ) external returns (uint256 shares);

    /// @notice Claim full reward (fee + bond) in wstETH for the given Node Operator available for this moment.
    ///         `rewardsProof` and `cumulativeFeeShares` might be empty in order to claim only excess bond
    /// @param nodeOperatorId ID of the Node Operator
    /// @param wstETHAmount Amount of wstETH to claim
    /// @param cumulativeFeeShares Cumulative fee stETH shares for the Node Operator
    /// @param rewardsProof Merkle proof of the rewards
    /// @return claimedWstETHAmount Amount of wstETH claimed
    /// @dev It's impossible to use single-leaf proof via this method, so this case should be treated carefully by
    /// off-chain tooling, e.g. to make sure a tree has at least 2 leafs.
    function claimRewardsWstETH(
        uint256 nodeOperatorId,
        uint256 wstETHAmount,
        uint256 cumulativeFeeShares,
        bytes32[] calldata rewardsProof
    ) external returns (uint256 claimedWstETHAmount);

    /// @notice Request full reward (fee + bond) in Withdrawal NFT (unstETH) for the given Node Operator available for this moment.
    ///         `rewardsProof` and `cumulativeFeeShares` might be empty in order to claim only excess bond
    /// @dev Reverts if amount isn't between `MIN_STETH_WITHDRAWAL_AMOUNT` and `MAX_STETH_WITHDRAWAL_AMOUNT`
    /// @param nodeOperatorId ID of the Node Operator
    /// @param stETHAmount Amount of ETH to request
    /// @param cumulativeFeeShares Cumulative fee stETH shares for the Node Operator
    /// @param rewardsProof Merkle proof of the rewards
    /// @return requestId Withdrawal NFT ID
    /// @dev It's impossible to use single-leaf proof via this method, so this case should be treated carefully by
    /// off-chain tooling, e.g. to make sure a tree has at least 2 leafs.
    function claimRewardsUnstETH(
        uint256 nodeOperatorId,
        uint256 stETHAmount,
        uint256 cumulativeFeeShares,
        bytes32[] calldata rewardsProof
    ) external returns (uint256 requestId);

    /// @notice Lock bond in ETH for the given Node Operator
    /// @dev Called by CSM exclusively
    /// @param nodeOperatorId ID of the Node Operator
    /// @param amount Amount to lock in ETH (stETH)
    function lockBondETH(uint256 nodeOperatorId, uint256 amount) external;

    /// @notice Release locked bond in ETH for the given Node Operator
    /// @dev Called by CSM exclusively
    /// @param nodeOperatorId ID of the Node Operator
    /// @param amount Amount to release in ETH (stETH)
    function releaseLockedBondETH(
        uint256 nodeOperatorId,
        uint256 amount
    ) external;

    /// @notice Settle locked bond ETH for the given Node Operator
    /// @dev Called by CSM exclusively
    /// @param nodeOperatorId ID of the Node Operator
    function settleLockedBondETH(
        uint256 nodeOperatorId
    ) external returns (bool);

    /// @notice Compensate locked bond ETH for the given Node Operator
    /// @dev Called by CSM exclusively
    /// @param nodeOperatorId ID of the Node Operator
    function compensateLockedBondETH(uint256 nodeOperatorId) external payable;

    /// @notice Set the bond curve for the given Node Operator
    /// @dev Updates depositable validators count in CSM to ensure key pointers consistency
    /// @param nodeOperatorId ID of the Node Operator
    /// @param curveId ID of the bond curve to set
    function setBondCurve(uint256 nodeOperatorId, uint256 curveId) external;

    /// @notice Penalize bond by burning stETH shares of the given Node Operator
    /// @dev Penalty application has a priority over the locked bond.
    ///      Method call can result in the remaining bond being lower than the locked bond.
    /// @param nodeOperatorId ID of the Node Operator
    /// @param amount Amount to penalize in ETH (stETH)
    function penalize(uint256 nodeOperatorId, uint256 amount) external;

    /// @notice Charge fee from bond by transferring stETH shares of the given Node Operator to the charge recipient
    /// @dev Charge confiscation has a priority over the locked bond.
    ///      Method call can result in the remaining bond being lower than the locked bond.
    /// @param nodeOperatorId ID of the Node Operator
    /// @param amount Amount to charge in ETH (stETH)
    function chargeFee(uint256 nodeOperatorId, uint256 amount) external;

    /// @notice Pull fees from CSFeeDistributor to the Node Operator's bond
    /// @dev Permissionless method. Can be called before penalty application to ensure that rewards are also penalized
    /// @param nodeOperatorId ID of the Node Operator
    /// @param cumulativeFeeShares Cumulative fee stETH shares for the Node Operator
    /// @param rewardsProof Merkle proof of the rewards
    function pullFeeRewards(
        uint256 nodeOperatorId,
        uint256 cumulativeFeeShares,
        bytes32[] calldata rewardsProof
    ) external;

    /// @notice Service method to update allowance to Burner in case it has changed
    function renewBurnerAllowance() external;
}

// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import { NodeOperator } from "../interfaces/ICSModule.sol";
import { TransientUintUintMap } from "./TransientUintUintMapLib.sol";

// Batch is an uint256 as it's the internal data type used by solidity.
// Batch is a packed value, consisting of the following fields:
//    - uint64  nodeOperatorId
//    - uint64  keysCount -- count of keys enqueued by the batch
//    - uint128 next -- index of the next batch in the queue
type Batch is uint256;

/// @notice Batch of the operator with index 0, with no keys in it and the next Batch' index 0 is meaningless.
function isNil(Batch self) pure returns (bool) {
    return Batch.unwrap(self) == 0;
}

/// @dev Syntactic sugar for the type.
function unwrap(Batch self) pure returns (uint256) {
    return Batch.unwrap(self);
}

function noId(Batch self) pure returns (uint64 n) {
    assembly {
        n := shr(192, self)
    }
}

function keys(Batch self) pure returns (uint64 n) {
    assembly {
        n := shl(64, self)
        n := shr(192, n)
    }
}

function next(Batch self) pure returns (uint128 n) {
    assembly {
        n := shl(128, self)
        n := shr(128, n)
    }
}

/// @dev keys count cast is unsafe
function setKeys(Batch self, uint256 keysCount) pure returns (Batch) {
    assembly {
        self := or(
            and(
                self,
                0xffffffffffffffff0000000000000000ffffffffffffffffffffffffffffffff
            ),
            shl(128, and(keysCount, 0xffffffffffffffff))
        ) // self.keys = keysCount
    }

    return self;
}

/// @dev can be unsafe if the From batch is previous to the self
function setNext(Batch self, uint128 nextIndex) pure returns (Batch) {
    assembly {
        self := or(
            and(
                self,
                0xffffffffffffffffffffffffffffffff00000000000000000000000000000000
            ),
            nextIndex
        ) // self.next = next
    }
    return self;
}

/// @dev Instantiate a new Batch to be added to the queue. The `next` field will be determined upon the enqueue.
/// @dev Parameters are uint256 to make usage easier.
function createBatch(
    uint256 nodeOperatorId,
    uint256 keysCount
) pure returns (Batch item) {
    // NOTE: No need to safe cast due to internal logic.
    nodeOperatorId = uint64(nodeOperatorId);
    keysCount = uint64(keysCount);

    assembly {
        item := shl(128, keysCount) // `keysCount` in [64:127]
        item := or(item, shl(192, nodeOperatorId)) // `nodeOperatorId` in [0:63]
    }
}

using { noId, keys, setKeys, setNext, next, isNil, unwrap } for Batch global;
using QueueLib for QueueLib.Queue;

interface IQueueLib {
    error QueueIsEmpty();
    error QueueLookupNoLimit();
}

/// @author madlabman
library QueueLib {
    struct Queue {
        // Pointer to the item to be dequeued.
        uint128 head;
        // Tracks the total number of batches ever enqueued.
        uint128 tail;
        // Mapping saves a little in costs and allows easily fallback to a zeroed batch on out-of-bounds access.
        mapping(uint128 => Batch) queue;
    }

    //////
    /// External methods
    //////

    function clean(
        Queue storage self,
        mapping(uint256 => NodeOperator) storage nodeOperators,
        uint256 maxItems,
        TransientUintUintMap queueLookup
    )
        external
        returns (
            uint256 removed,
            uint256 lastRemovedAtDepth,
            uint256 visited,
            bool reachedOutOfQueue
        )
    {
        removed = 0;
        lastRemovedAtDepth = 0;
        visited = 0;
        reachedOutOfQueue = false;

        if (maxItems == 0) {
            revert IQueueLib.QueueLookupNoLimit();
        }

        Batch prevItem;
        uint128 indexOfPrev;

        uint128 head = self.head;
        uint128 curr = head;

        while (visited < maxItems) {
            Batch item = self.queue[curr];
            if (item.isNil()) {
                reachedOutOfQueue = true;
                break;
            }

            visited++;

            NodeOperator storage no = nodeOperators[item.noId()];
            if (queueLookup.get(item.noId()) >= no.depositableValidatorsCount) {
                // NOTE: Since we reached that point there's no way for a Node Operator to have a depositable batch
                // later in the queue, and hence we don't update _queueLookup for the Node Operator.
                if (curr == head) {
                    self.dequeue();
                    head = self.head;
                } else {
                    // There's no `prev` item while we call `dequeue`, and removing an item will keep the `prev` intact
                    // other than changing its `next` field.
                    prevItem = prevItem.setNext(item.next());
                    self.queue[indexOfPrev] = prevItem;
                }

                // We assume that the invariant `enqueuedCount` >= `keys` is kept.
                // NOTE: No need to safe cast due to internal logic.
                no.enqueuedCount -= uint32(item.keys());

                unchecked {
                    lastRemovedAtDepth = visited;
                    ++removed;
                }
            } else {
                queueLookup.add(item.noId(), item.keys());
                indexOfPrev = curr;
                prevItem = item;
            }

            curr = item.next();
        }
    }

    /////
    /// Internal methods
    /////
    function enqueue(
        Queue storage self,
        uint256 nodeOperatorId,
        uint256 keysCount
    ) internal returns (Batch item) {
        uint128 tail = self.tail;
        item = createBatch(nodeOperatorId, keysCount);

        assembly {
            item := or(
                and(
                    item,
                    0xffffffffffffffffffffffffffffffff00000000000000000000000000000000
                ),
                add(tail, 1)
            ) // item.next = self.tail + 1;
        }

        self.queue[tail] = item;
        unchecked {
            ++self.tail;
        }
    }

    function dequeue(Queue storage self) internal returns (Batch item) {
        item = peek(self);

        if (item.isNil()) {
            revert IQueueLib.QueueIsEmpty();
        }

        self.head = item.next();
    }

    function peek(Queue storage self) internal view returns (Batch) {
        return self.queue[self.head];
    }

    function at(
        Queue storage self,
        uint128 index
    ) internal view returns (Batch) {
        return self.queue[index];
    }
}

// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import { NodeOperator, ICSModule } from "../interfaces/ICSModule.sol";

/// Library for changing and reset node operator's manager and reward addresses
/// @dev the only use of this to be a library is to save CSModule contract size via delegatecalls
interface INOAddresses {
    event NodeOperatorManagerAddressChangeProposed(
        uint256 indexed nodeOperatorId,
        address indexed oldProposedAddress,
        address indexed newProposedAddress
    );
    event NodeOperatorRewardAddressChangeProposed(
        uint256 indexed nodeOperatorId,
        address indexed oldProposedAddress,
        address indexed newProposedAddress
    );
    // args order as in https://github.com/OpenZeppelin/openzeppelin-contracts/blob/11dc5e3809ebe07d5405fe524385cbe4f890a08b/contracts/access/Ownable.sol#L33
    event NodeOperatorManagerAddressChanged(
        uint256 indexed nodeOperatorId,
        address indexed oldAddress,
        address indexed newAddress
    );
    // args order as in https://github.com/OpenZeppelin/openzeppelin-contracts/blob/11dc5e3809ebe07d5405fe524385cbe4f890a08b/contracts/access/Ownable.sol#L33
    event NodeOperatorRewardAddressChanged(
        uint256 indexed nodeOperatorId,
        address indexed oldAddress,
        address indexed newAddress
    );

    error AlreadyProposed();
    error SameAddress();
    error SenderIsNotManagerAddress();
    error SenderIsNotRewardAddress();
    error SenderIsNotProposedAddress();
    error MethodCallIsNotAllowed();
    error ZeroRewardAddress();
}

library NOAddresses {
    /// @notice Propose a new manager address for the Node Operator
    /// @param nodeOperatorId ID of the Node Operator
    /// @param proposedAddress Proposed manager address
    function proposeNodeOperatorManagerAddressChange(
        mapping(uint256 => NodeOperator) storage nodeOperators,
        uint256 nodeOperatorId,
        address proposedAddress
    ) external {
        NodeOperator storage no = nodeOperators[nodeOperatorId];
        address managerAddress = no.managerAddress;

        if (managerAddress == address(0)) {
            revert ICSModule.NodeOperatorDoesNotExist();
        }

        if (managerAddress != msg.sender) {
            revert INOAddresses.SenderIsNotManagerAddress();
        }

        if (managerAddress == proposedAddress) {
            revert INOAddresses.SameAddress();
        }

        address oldProposedAddress = no.proposedManagerAddress;

        if (oldProposedAddress == proposedAddress) {
            revert INOAddresses.AlreadyProposed();
        }

        no.proposedManagerAddress = proposedAddress;

        emit INOAddresses.NodeOperatorManagerAddressChangeProposed(
            nodeOperatorId,
            oldProposedAddress,
            proposedAddress
        );
    }

    /// @notice Confirm a new manager address for the Node Operator.
    ///         Should be called from the currently proposed address
    /// @param nodeOperatorId ID of the Node Operator
    function confirmNodeOperatorManagerAddressChange(
        mapping(uint256 => NodeOperator) storage nodeOperators,
        uint256 nodeOperatorId
    ) external {
        NodeOperator storage no = nodeOperators[nodeOperatorId];
        address oldManagerAddress = no.managerAddress;

        if (oldManagerAddress == address(0)) {
            revert ICSModule.NodeOperatorDoesNotExist();
        }

        if (no.proposedManagerAddress != msg.sender) {
            revert INOAddresses.SenderIsNotProposedAddress();
        }

        no.managerAddress = msg.sender;
        delete no.proposedManagerAddress;

        emit INOAddresses.NodeOperatorManagerAddressChanged(
            nodeOperatorId,
            oldManagerAddress,
            msg.sender
        );
    }

    /// @notice Propose a new reward address for the Node Operator
    /// @param nodeOperatorId ID of the Node Operator
    /// @param proposedAddress Proposed reward address
    function proposeNodeOperatorRewardAddressChange(
        mapping(uint256 => NodeOperator) storage nodeOperators,
        uint256 nodeOperatorId,
        address proposedAddress
    ) external {
        NodeOperator storage no = nodeOperators[nodeOperatorId];
        address rewardAddress = no.rewardAddress;

        if (rewardAddress == address(0)) {
            revert ICSModule.NodeOperatorDoesNotExist();
        }

        if (rewardAddress != msg.sender) {
            revert INOAddresses.SenderIsNotRewardAddress();
        }

        if (rewardAddress == proposedAddress) {
            revert INOAddresses.SameAddress();
        }

        address oldProposedAddress = no.proposedRewardAddress;

        if (oldProposedAddress == proposedAddress) {
            revert INOAddresses.AlreadyProposed();
        }

        no.proposedRewardAddress = proposedAddress;

        emit INOAddresses.NodeOperatorRewardAddressChangeProposed(
            nodeOperatorId,
            oldProposedAddress,
            proposedAddress
        );
    }

    /// @notice Confirm a new reward address for the Node Operator.
    ///         Should be called from the currently proposed address
    /// @param nodeOperatorId ID of the Node Operator
    function confirmNodeOperatorRewardAddressChange(
        mapping(uint256 => NodeOperator) storage nodeOperators,
        uint256 nodeOperatorId
    ) external {
        NodeOperator storage no = nodeOperators[nodeOperatorId];
        address oldRewardAddress = no.rewardAddress;

        if (oldRewardAddress == address(0)) {
            revert ICSModule.NodeOperatorDoesNotExist();
        }

        if (no.proposedRewardAddress != msg.sender) {
            revert INOAddresses.SenderIsNotProposedAddress();
        }

        no.rewardAddress = msg.sender;
        delete no.proposedRewardAddress;

        emit INOAddresses.NodeOperatorRewardAddressChanged(
            nodeOperatorId,
            oldRewardAddress,
            msg.sender
        );
    }

    /// @notice Reset the manager address to the reward address.
    ///         Should be called from the reward address
    /// @param nodeOperatorId ID of the Node Operator
    function resetNodeOperatorManagerAddress(
        mapping(uint256 => NodeOperator) storage nodeOperators,
        uint256 nodeOperatorId
    ) external {
        NodeOperator storage no = nodeOperators[nodeOperatorId];
        address rewardAddress = no.rewardAddress;

        if (rewardAddress == address(0)) {
            revert ICSModule.NodeOperatorDoesNotExist();
        }

        if (no.extendedManagerPermissions) {
            revert INOAddresses.MethodCallIsNotAllowed();
        }

        if (rewardAddress != msg.sender) {
            revert INOAddresses.SenderIsNotRewardAddress();
        }

        address previousManagerAddress = no.managerAddress;

        if (previousManagerAddress == rewardAddress) {
            revert INOAddresses.SameAddress();
        }

        no.managerAddress = rewardAddress;
        // @dev Gas golfing
        if (no.proposedManagerAddress != address(0)) {
            delete no.proposedManagerAddress;
        }

        emit INOAddresses.NodeOperatorManagerAddressChanged(
            nodeOperatorId,
            previousManagerAddress,
            rewardAddress
        );
    }

    /// @notice Change rewardAddress if extendedManagerPermissions is enabled for the Node Operator.
    ///         Should be called from the current manager address
    /// @param nodeOperatorId ID of the Node Operator
    /// @param newAddress New reward address
    function changeNodeOperatorRewardAddress(
        mapping(uint256 => NodeOperator) storage nodeOperators,
        uint256 nodeOperatorId,
        address newAddress
    ) external {
        if (newAddress == address(0)) {
            revert INOAddresses.ZeroRewardAddress();
        }

        NodeOperator storage no = nodeOperators[nodeOperatorId];
        address oldRewardAddress = no.rewardAddress;

        if (oldRewardAddress == newAddress) {
            revert INOAddresses.SameAddress();
        }

        address managerAddress = no.managerAddress;

        if (managerAddress == address(0)) {
            revert ICSModule.NodeOperatorDoesNotExist();
        }

        if (!no.extendedManagerPermissions) {
            revert INOAddresses.MethodCallIsNotAllowed();
        }

        if (managerAddress != msg.sender) {
            revert INOAddresses.SenderIsNotManagerAddress();
        }

        no.rewardAddress = newAddress;
        // @dev Gas golfing
        if (no.proposedRewardAddress != address(0)) {
            delete no.proposedRewardAddress;
        }

        emit INOAddresses.NodeOperatorRewardAddressChanged(
            nodeOperatorId,
            oldRewardAddress,
            newAddress
        );
    }
}

// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import { IERC1155 } from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ILido } from "../interfaces/ILido.sol";

interface IAssetRecovererLib {
    event EtherRecovered(address indexed recipient, uint256 amount);
    event ERC20Recovered(
        address indexed token,
        address indexed recipient,
        uint256 amount
    );
    event StETHSharesRecovered(address indexed recipient, uint256 shares);
    event ERC721Recovered(
        address indexed token,
        uint256 tokenId,
        address indexed recipient
    );
    event ERC1155Recovered(
        address indexed token,
        uint256 tokenId,
        address indexed recipient,
        uint256 amount
    );

    error FailedToSendEther();
    error NotAllowedToRecover();
}

/*
 * @title AssetRecovererLib
 * @dev Library providing mechanisms for recovering various asset types (ETH, ERC20, ERC721, ERC1155).
 * This library is designed to be used by a contract that implements the AssetRecoverer interface.
 */
library AssetRecovererLib {
    using SafeERC20 for IERC20;

    /**
     * @dev Allows the sender to recover Ether held by the contract.
     * Emits an EtherRecovered event upon success.
     */
    function recoverEther() external {
        uint256 amount = address(this).balance;
        (bool success, ) = msg.sender.call{ value: amount }("");
        if (!success) {
            revert IAssetRecovererLib.FailedToSendEther();
        }

        emit IAssetRecovererLib.EtherRecovered(msg.sender, amount);
    }

    /**
     * @dev Allows the sender to recover ERC20 tokens held by the contract.
     * @param token The address of the ERC20 token to recover.
     * @param amount The amount of the ERC20 token to recover.
     * Emits an ERC20Recovered event upon success.
     */
    function recoverERC20(address token, uint256 amount) external {
        IERC20(token).safeTransfer(msg.sender, amount);
        emit IAssetRecovererLib.ERC20Recovered(token, msg.sender, amount);
    }

    /**
     * @dev Allows the sender to recover stETH shares held by the contract.
     * The use of a separate method for stETH is to avoid rounding problems when converting shares to stETH.
     * @param lido The address of the Lido contract.
     * @param shares The amount of stETH shares to recover.
     * Emits an StETHSharesRecovered event upon success.
     */
    function recoverStETHShares(address lido, uint256 shares) external {
        ILido(lido).transferShares(msg.sender, shares);
        emit IAssetRecovererLib.StETHSharesRecovered(msg.sender, shares);
    }

    /**
     * @dev Allows the sender to recover ERC721 tokens held by the contract.
     * @param token The address of the ERC721 token to recover.
     * @param tokenId The token ID of the ERC721 token to recover.
     * Emits an ERC721Recovered event upon success.
     */
    function recoverERC721(address token, uint256 tokenId) external {
        IERC721(token).safeTransferFrom(address(this), msg.sender, tokenId);
        emit IAssetRecovererLib.ERC721Recovered(token, tokenId, msg.sender);
    }

    /**
     * @dev Allows the sender to recover ERC1155 tokens held by the contract.
     * @param token The address of the ERC1155 token to recover.
     * @param tokenId The token ID of the ERC1155 token to recover.
     * Emits an ERC1155Recovered event upon success.
     */
    function recoverERC1155(address token, uint256 tokenId) external {
        uint256 amount = IERC1155(token).balanceOf(address(this), tokenId);
        IERC1155(token).safeTransferFrom({
            from: address(this),
            to: msg.sender,
            id: tokenId,
            value: amount,
            data: ""
        });
        emit IAssetRecovererLib.ERC1155Recovered(
            token,
            tokenId,
            msg.sender,
            amount
        );
    }
}

// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.24;

interface ILidoLocator {
    error ZeroAddress();

    function accountingOracle() external view returns (address);

    function burner() external view returns (address);

    function coreComponents()
        external
        view
        returns (address, address, address, address, address, address);

    function depositSecurityModule() external view returns (address);

    function elRewardsVault() external view returns (address);

    function legacyOracle() external view returns (address);

    function lido() external view returns (address);

    function oracleDaemonConfig() external view returns (address);

    function oracleReportComponentsForLido()
        external
        view
        returns (address, address, address, address, address, address, address);

    function oracleReportSanityChecker() external view returns (address);

    function postTokenRebaseReceiver() external view returns (address);

    function stakingRouter() external view returns (address payable);

    function treasury() external view returns (address);

    function validatorsExitBusOracle() external view returns (address);

    function withdrawalQueue() external view returns (address);

    function withdrawalVault() external view returns (address);

    function triggerableWithdrawalsGateway() external view returns (address);
}

// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.24;

/**
 * @title Interface defining ERC20-compatible StETH token
 */
interface IStETH {
    /**
     * @notice Get stETH amount by the provided shares amount
     * @param _sharesAmount shares amount
     * @dev dual to `getSharesByPooledEth`.
     */
    function getPooledEthByShares(
        uint256 _sharesAmount
    ) external view returns (uint256);

    /**
     * @notice Get shares amount by the provided stETH amount
     * @param _pooledEthAmount stETH amount
     * @dev dual to `getPooledEthByShares`.
     */
    function getSharesByPooledEth(
        uint256 _pooledEthAmount
    ) external view returns (uint256);

    /**
     * @notice Get shares amount of the provided account
     * @param _account provided account address.
     */
    function sharesOf(address _account) external view returns (uint256);

    function balanceOf(address _account) external view returns (uint256);

    /**
     * @notice Transfer `_sharesAmount` stETH shares from `_sender` to `_recipient` using allowance.
     */
    function transferSharesFrom(
        address _sender,
        address _recipient,
        uint256 _sharesAmount
    ) external returns (uint256);

    /**
     * @notice Moves `_sharesAmount` token shares from the caller's account to the `_recipient` account.
     */
    function transferShares(
        address _recipient,
        uint256 _sharesAmount
    ) external returns (uint256);

    /**
     * @notice Moves `_amount` stETH from the caller's account to the `_recipient` account.
     */
    function transfer(
        address _recipient,
        uint256 _amount
    ) external returns (bool);

    /**
     * @notice Moves `_amount` stETH from the `_sender` account to the `_recipient` account.
     */
    function transferFrom(
        address _sender,
        address _recipient,
        uint256 _amount
    ) external returns (bool);

    function approve(address _spender, uint256 _amount) external returns (bool);

    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    function allowance(
        address _owner,
        address _spender
    ) external view returns (uint256);
}

File 20 of 40 : ICSParametersRegistry.sol
// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.24;

interface ICSParametersRegistry {
    struct MarkedUint248 {
        uint248 value;
        bool isValue;
    }

    struct QueueConfig {
        uint32 priority;
        uint32 maxDeposits;
    }

    struct StrikesParams {
        uint32 lifetime;
        uint32 threshold;
    }

    struct PerformanceCoefficients {
        uint32 attestationsWeight;
        uint32 blocksWeight;
        uint32 syncWeight;
    }

    struct InitializationData {
        uint256 keyRemovalCharge;
        uint256 elRewardsStealingAdditionalFine;
        uint256 keysLimit;
        uint256 rewardShare;
        uint256 performanceLeeway;
        uint256 strikesLifetime;
        uint256 strikesThreshold;
        uint256 defaultQueuePriority;
        uint256 defaultQueueMaxDeposits;
        uint256 badPerformancePenalty;
        uint256 attestationsWeight;
        uint256 blocksWeight;
        uint256 syncWeight;
        uint256 defaultAllowedExitDelay;
        uint256 defaultExitDelayPenalty;
        uint256 defaultMaxWithdrawalRequestFee;
    }

    /// @dev Defines a value interval starting from `minKeyNumber`.
    ///      All keys with number >= `minKeyNumber` are assigned the corresponding `value`
    ///      until the next interval begins. Intervals must be sorted by ascending `minKeyNumber`
    ///      and must start from one (i.e., the first interval must have minKeyNumber == 1).
    ///      Example: [{1, 10000}, {11, 8000}] means first 10 keys with 10000, other keys with 8000.
    struct KeyNumberValueInterval {
        uint256 minKeyNumber;
        uint256 value;
    }

    event DefaultKeyRemovalChargeSet(uint256 value);
    event DefaultElRewardsStealingAdditionalFineSet(uint256 value);
    event DefaultKeysLimitSet(uint256 value);
    event DefaultRewardShareSet(uint256 value);
    event DefaultPerformanceLeewaySet(uint256 value);
    event DefaultStrikesParamsSet(uint256 lifetime, uint256 threshold);
    event DefaultBadPerformancePenaltySet(uint256 value);
    event DefaultPerformanceCoefficientsSet(
        uint256 attestationsWeight,
        uint256 blocksWeight,
        uint256 syncWeight
    );
    event DefaultQueueConfigSet(uint256 priority, uint256 maxDeposits);
    event DefaultAllowedExitDelaySet(uint256 delay);
    event DefaultExitDelayPenaltySet(uint256 penalty);
    event DefaultMaxWithdrawalRequestFeeSet(uint256 fee);

    event KeyRemovalChargeSet(
        uint256 indexed curveId,
        uint256 keyRemovalCharge
    );
    event ElRewardsStealingAdditionalFineSet(
        uint256 indexed curveId,
        uint256 fine
    );
    event KeysLimitSet(uint256 indexed curveId, uint256 limit);
    event RewardShareDataSet(
        uint256 indexed curveId,
        KeyNumberValueInterval[] data
    );
    event PerformanceLeewayDataSet(
        uint256 indexed curveId,
        KeyNumberValueInterval[] data
    );
    event StrikesParamsSet(
        uint256 indexed curveId,
        uint256 lifetime,
        uint256 threshold
    );
    event BadPerformancePenaltySet(uint256 indexed curveId, uint256 penalty);
    event PerformanceCoefficientsSet(
        uint256 indexed curveId,
        uint256 attestationsWeight,
        uint256 blocksWeight,
        uint256 syncWeight
    );

    event KeyRemovalChargeUnset(uint256 indexed curveId);
    event ElRewardsStealingAdditionalFineUnset(uint256 indexed curveId);
    event KeysLimitUnset(uint256 indexed curveId);
    event RewardShareDataUnset(uint256 indexed curveId);
    event PerformanceLeewayDataUnset(uint256 indexed curveId);
    event StrikesParamsUnset(uint256 indexed curveId);
    event BadPerformancePenaltyUnset(uint256 indexed curveId);
    event PerformanceCoefficientsUnset(uint256 indexed curveId);
    event QueueConfigSet(
        uint256 indexed curveId,
        uint256 priority,
        uint256 maxDeposits
    );
    event QueueConfigUnset(uint256 indexed curveId);
    event AllowedExitDelaySet(uint256 indexed curveId, uint256 delay);
    event AllowedExitDelayUnset(uint256 indexed curveId);
    event ExitDelayPenaltySet(uint256 indexed curveId, uint256 penalty);
    event ExitDelayPenaltyUnset(uint256 indexed curveId);
    event MaxWithdrawalRequestFeeSet(uint256 indexed curveId, uint256 fee);
    event MaxWithdrawalRequestFeeUnset(uint256 indexed curveId);

    error InvalidRewardShareData();
    error InvalidPerformanceLeewayData();
    error InvalidKeyNumberValueIntervals();
    error InvalidPerformanceCoefficients();
    error InvalidStrikesParams();
    error ZeroMaxDeposits();
    error ZeroAdminAddress();
    error QueueCannotBeUsed();
    error InvalidAllowedExitDelay();
    error ZeroQueueLowestPriority();

    /// @notice The lowest priority a deposit queue can be assigned with.
    function QUEUE_LOWEST_PRIORITY() external view returns (uint256);

    /// @notice The priority reserved to be used for legacy queue only.
    function QUEUE_LEGACY_PRIORITY() external view returns (uint256);

    /// @notice Set default value for the key removal charge. Default value is used if a specific value is not set for the curveId
    /// @param keyRemovalCharge value to be set as default for the key removal charge
    function setDefaultKeyRemovalCharge(uint256 keyRemovalCharge) external;

    /// @notice Get default value for the key removal charge
    function defaultKeyRemovalCharge() external returns (uint256);

    /// @notice Set default value for the EL rewards stealing additional fine. Default value is used if a specific value is not set for the curveId
    /// @param fine value to be set as default for the EL rewards stealing additional fine
    function setDefaultElRewardsStealingAdditionalFine(uint256 fine) external;

    /// @notice Get default value for the EL rewards stealing additional fine
    function defaultElRewardsStealingAdditionalFine()
        external
        returns (uint256);

    /// @notice Set default value for the keys limit. Default value is used if a specific value is not set for the curveId
    /// @param limit value to be set as default for the keys limit
    function setDefaultKeysLimit(uint256 limit) external;

    /// @notice Get default value for the key removal charge
    function defaultKeysLimit() external returns (uint256);

    /// @notice Set default value for the reward share. Default value is used if a specific value is not set for the curveId
    /// @param share value to be set as default for the reward share
    function setDefaultRewardShare(uint256 share) external;

    /// @notice Get default value for the reward share
    function defaultRewardShare() external returns (uint256);

    /// @notice Set default value for the performance leeway. Default value is used if a specific value is not set for the curveId
    /// @param leeway value to be set as default for the performance leeway
    function setDefaultPerformanceLeeway(uint256 leeway) external;

    /// @notice Get default value for the performance leeway
    function defaultPerformanceLeeway() external returns (uint256);

    /// @notice Set default values for the strikes lifetime and threshold. Default values are used if specific values are not set for the curveId
    /// @param lifetime The default number of CSM Performance Oracle frames to store strikes values
    /// @param threshold The default strikes value leading to validator force ejection.
    function setDefaultStrikesParams(
        uint256 lifetime,
        uint256 threshold
    ) external;

    /// @notice Get default value for the strikes lifetime (frames count) and threshold (integer)
    /// @return lifetime The default number of CSM Performance Oracle frames to store strikes values
    /// @return threshold The default strikes value leading to validator force ejection.
    function defaultStrikesParams() external returns (uint32, uint32);

    /// @notice Set default value for the bad performance penalty. Default value is used if a specific value is not set for the curveId
    /// @param penalty value to be set as default for the bad performance penalty
    function setDefaultBadPerformancePenalty(uint256 penalty) external;

    /// @notice Get default value for the bad performance penalty
    function defaultBadPerformancePenalty() external returns (uint256);

    /// @notice Set default values for the performance coefficients. Default values are used if specific values are not set for the curveId
    /// @param attestationsWeight value to be set as default for the attestations effectiveness weight
    /// @param blocksWeight value to be set as default for block proposals effectiveness weight
    /// @param syncWeight value to be set as default for sync participation effectiveness weight
    function setDefaultPerformanceCoefficients(
        uint256 attestationsWeight,
        uint256 blocksWeight,
        uint256 syncWeight
    ) external;

    /// @notice Get default value for the performance coefficients
    function defaultPerformanceCoefficients()
        external
        returns (uint32, uint32, uint32);

    /// @notice set default value for allowed delay before the exit was initiated exit delay in seconds. Default value is used if a specific value is not set for the curveId
    /// @param delay value to be set as default for the allowed exit delay
    function setDefaultAllowedExitDelay(uint256 delay) external;

    /// @notice set default value for exit delay penalty. Default value is used if a specific value is not set for the curveId
    /// @param penalty value to be set as default for the exit delay penalty
    function setDefaultExitDelayPenalty(uint256 penalty) external;

    /// @notice set default value for max withdrawal request fee. Default value is used if a specific value is not set for the curveId
    /// @param fee value to be set as default for the max withdrawal request fee
    function setDefaultMaxWithdrawalRequestFee(uint256 fee) external;

    /// @notice Get default value for the allowed exit delay
    function defaultAllowedExitDelay() external returns (uint256);

    /// @notice Set key removal charge for the curveId.
    /// @param curveId Curve Id to associate key removal charge with
    /// @param keyRemovalCharge Key removal charge
    function setKeyRemovalCharge(
        uint256 curveId,
        uint256 keyRemovalCharge
    ) external;

    /// @notice Unset key removal charge for the curveId
    /// @param curveId Curve Id to unset custom key removal charge for
    function unsetKeyRemovalCharge(uint256 curveId) external;

    /// @notice Get key removal charge by the curveId. A charge is taken from the bond for each removed key from CSM
    /// @dev `defaultKeyRemovalCharge` is returned if the value is not set for the given curveId.
    /// @param curveId Curve Id to get key removal charge for
    /// @return keyRemovalCharge Key removal charge
    function getKeyRemovalCharge(
        uint256 curveId
    ) external view returns (uint256 keyRemovalCharge);

    /// @notice Set EL rewards stealing additional fine for the curveId.
    /// @param curveId Curve Id to associate EL rewards stealing additional fine limit with
    /// @param fine EL rewards stealing additional fine
    function setElRewardsStealingAdditionalFine(
        uint256 curveId,
        uint256 fine
    ) external;

    /// @notice Unset EL rewards stealing additional fine for the curveId
    /// @param curveId Curve Id to unset custom EL rewards stealing additional fine for
    function unsetElRewardsStealingAdditionalFine(uint256 curveId) external;

    /// @notice Get EL rewards stealing additional fine by the curveId. Additional fine is added to the EL rewards stealing penalty by CSM
    /// @dev `defaultElRewardsStealingAdditionalFine` is returned if the value is not set for the given curveId.
    /// @param curveId Curve Id to get EL rewards stealing additional fine for
    /// @return fine EL rewards stealing additional fine
    function getElRewardsStealingAdditionalFine(
        uint256 curveId
    ) external view returns (uint256 fine);

    /// @notice Set keys limit for the curveId.
    /// @param curveId Curve Id to associate keys limit with
    /// @param limit Keys limit
    function setKeysLimit(uint256 curveId, uint256 limit) external;

    /// @notice Unset key removal charge for the curveId
    /// @param curveId Curve Id to unset custom key removal charge for
    function unsetKeysLimit(uint256 curveId) external;

    /// @notice Get keys limit by the curveId. A limit indicates the maximal amount of the non-exited keys Node Operator can upload
    /// @dev `defaultKeysLimit` is returned if the value is not set for the given curveId.
    /// @param curveId Curve Id to get keys limit for
    /// @return limit Keys limit
    function getKeysLimit(
        uint256 curveId
    ) external view returns (uint256 limit);

    /// @notice Set reward share parameters for the curveId
    /// @dev KeyNumberValueInterval = [[1, 10000], [11, 8000], [51, 5000]] stands for
    ///      100% rewards for the first 10 keys, 80% rewards for the keys 11-50, and 50% rewards for the keys > 50
    /// @param curveId Curve Id to associate reward share data with
    /// @param data Interval values for keys count and reward share percentages in BP (ex. [[1, 10000], [11, 8000], [51, 5000]])
    function setRewardShareData(
        uint256 curveId,
        KeyNumberValueInterval[] calldata data
    ) external;

    /// @notice Unset reward share parameters for the curveId
    /// @param curveId Curve Id to unset custom reward share parameters for
    function unsetRewardShareData(uint256 curveId) external;

    /// @notice Get reward share parameters by the curveId.
    /// @dev Returns [[1, defaultRewardShare]] if no intervals are set for the given curveId.
    /// @dev KeyNumberValueInterval = [[1, 10000], [11, 8000], [51, 5000]] stands for
    ///      100% rewards for the first 10 keys, 80% rewards for the keys 11-50, and 50% rewards for the keys > 50
    /// @param curveId Curve Id to get reward share data for
    /// @param data Interval values for keys count and reward share percentages in BP (ex. [[1, 10000], [11, 8000], [51, 5000]])
    function getRewardShareData(
        uint256 curveId
    ) external view returns (KeyNumberValueInterval[] memory data);

    /// @notice Set default value for QueueConfig. Default value is used if a specific value is not set for the curveId.
    /// @param priority Queue priority.
    /// @param maxDeposits Maximum number of the fist deposits a Node Operator can get via the priority queue.
    ///                    Ex. with `maxDeposits = 10` the Node Operator сan get keys added to the priority queue
    ///                    until the Node Operator has totalDepositedKeys + enqueued >= 10.
    function setDefaultQueueConfig(
        uint256 priority,
        uint256 maxDeposits
    ) external;

    /// @notice Sets the provided config to the given curve.
    /// @param curveId Curve Id to set the config.
    /// @param priority Queue priority.
    /// @param maxDeposits Maximum number of the fist deposits a Node Operator can get via the priority queue.
    ///                    Ex. with `maxDeposits = 10` the Node Operator сan get keys added to the priority queue
    ///                    until the Node Operator has totalDepositedKeys + enqueued >= 10.
    function setQueueConfig(
        uint256 curveId,
        uint256 priority,
        uint256 maxDeposits
    ) external;

    /// @notice Set the given curve's config to the default one.
    /// @param curveId Curve Id to unset custom config.
    function unsetQueueConfig(uint256 curveId) external;

    /// @notice Get the queue config for the given curve.
    /// @param curveId Curve Id to get the queue config for.
    /// @return priority Queue priority.
    /// @param maxDeposits Maximum number of the fist deposits a Node Operator can get via the priority queue.
    ///                    Ex. with `maxDeposits = 10` the Node Operator сan get keys added to the priority queue
    ///                    until the Node Operator has totalDepositedKeys + enqueued >= 10.
    function getQueueConfig(
        uint256 curveId
    ) external view returns (uint32 priority, uint32 maxDeposits);

    /// @notice Set performance leeway parameters for the curveId
    /// @dev Returns [[1, defaultPerformanceLeeway]] if no intervals are set for the given curveId.
    /// @dev KeyNumberValueInterval = [[1, 500], [101, 450], [501, 400]] stands for
    ///      5% performance leeway for the first 100 keys, 4.5% performance leeway for the keys 101-500, and 4% performance leeway for the keys > 500
    /// @param curveId Curve Id to associate performance leeway data with
    /// @param data Interval values for keys count and performance leeway percentages in BP (ex. [[1, 500], [101, 450], [501, 400]])
    function setPerformanceLeewayData(
        uint256 curveId,
        KeyNumberValueInterval[] calldata data
    ) external;

    /// @notice Unset performance leeway parameters for the curveId
    /// @param curveId Curve Id to unset custom performance leeway parameters for
    function unsetPerformanceLeewayData(uint256 curveId) external;

    /// @notice Get performance leeway parameters by the curveId
    /// @dev Returns [[1, defaultPerformanceLeeway]] if no intervals are set for the given curveId.
    /// @dev KeyNumberValueInterval = [[1, 500], [101, 450], [501, 400]] stands for
    ///      5% performance leeway for the first 100 keys, 4.5% performance leeway for the keys 101-500, and 4% performance leeway for the keys > 500
    /// @param curveId Curve Id to get performance leeway data for
    /// @param data Interval values for keys count and performance leeway percentages in BP (ex. [[1, 500], [101, 450], [501, 400]])
    function getPerformanceLeewayData(
        uint256 curveId
    ) external view returns (KeyNumberValueInterval[] memory data);

    /// @notice Set performance strikes lifetime and threshold for the curveId
    /// @param curveId Curve Id to associate performance strikes lifetime and threshold with
    /// @param lifetime Number of CSM Performance Oracle frames to store strikes values
    /// @param threshold The strikes value leading to validator force ejection
    function setStrikesParams(
        uint256 curveId,
        uint256 lifetime,
        uint256 threshold
    ) external;

    /// @notice Unset custom performance strikes lifetime and threshold for the curveId
    /// @param curveId Curve Id to unset custom performance strikes lifetime and threshold for
    function unsetStrikesParams(uint256 curveId) external;

    /// @notice Get performance strikes lifetime and threshold by the curveId
    /// @dev `defaultStrikesParams` are returned if the value is not set for the given curveId
    /// @param curveId Curve Id to get performance strikes lifetime and threshold for
    /// @return lifetime Number of CSM Performance Oracle frames to store strikes values
    /// @return threshold The strikes value leading to validator force ejection
    function getStrikesParams(
        uint256 curveId
    ) external view returns (uint256 lifetime, uint256 threshold);

    /// @notice Set bad performance penalty for the curveId
    /// @param curveId Curve Id to associate bad performance penalty with
    /// @param penalty Bad performance penalty
    function setBadPerformancePenalty(
        uint256 curveId,
        uint256 penalty
    ) external;

    /// @notice Unset bad performance penalty for the curveId
    /// @param curveId Curve Id to unset custom bad performance penalty for
    function unsetBadPerformancePenalty(uint256 curveId) external;

    /// @notice Get bad performance penalty by the curveId
    /// @dev `defaultBadPerformancePenalty` is returned if the value is not set for the given curveId.
    /// @param curveId Curve Id to get bad performance penalty for
    /// @return penalty Bad performance penalty
    function getBadPerformancePenalty(
        uint256 curveId
    ) external view returns (uint256 penalty);

    /// @notice Set performance coefficients for the curveId
    /// @param curveId Curve Id to associate performance coefficients with
    /// @param attestationsWeight Attestations effectiveness weight
    /// @param blocksWeight Block proposals effectiveness weight
    /// @param syncWeight Sync participation effectiveness weight
    function setPerformanceCoefficients(
        uint256 curveId,
        uint256 attestationsWeight,
        uint256 blocksWeight,
        uint256 syncWeight
    ) external;

    /// @notice Unset custom performance coefficients for the curveId
    /// @param curveId Curve Id to unset custom performance coefficients for
    function unsetPerformanceCoefficients(uint256 curveId) external;

    /// @notice Get performance coefficients by the curveId
    /// @dev `defaultPerformanceCoefficients` are returned if the value is not set for the given curveId.
    /// @param curveId Curve Id to get performance coefficients for
    /// @return attestationsWeight Attestations effectiveness weight
    /// @return blocksWeight Block proposals effectiveness weight
    /// @return syncWeight Sync participation effectiveness weight
    function getPerformanceCoefficients(
        uint256 curveId
    )
        external
        view
        returns (
            uint256 attestationsWeight,
            uint256 blocksWeight,
            uint256 syncWeight
        );

    /// @notice Set allowed exit delay for the curveId in seconds
    /// @param curveId Curve Id to associate allowed exit delay with
    /// @param delay allowed exit delay
    function setAllowedExitDelay(uint256 curveId, uint256 delay) external;

    /// @notice Unset exit timeframe deadline delay for the curveId
    /// @param curveId Curve Id to unset allowed exit delay for
    function unsetAllowedExitDelay(uint256 curveId) external;

    /// @notice Get allowed exit delay by the curveId in seconds
    /// @dev `defaultAllowedExitDelay` is returned if the value is not set for the given curveId.
    /// @param curveId Curve Id to get allowed exit delay for
    function getAllowedExitDelay(
        uint256 curveId
    ) external view returns (uint256 delay);

    /// @notice Set exit delay penalty for the curveId
    /// @dev cannot be zero
    /// @param curveId Curve Id to associate exit delay penalty with
    /// @param penalty exit delay penalty
    function setExitDelayPenalty(uint256 curveId, uint256 penalty) external;

    /// @notice Unset exit delay penalty for the curveId
    /// @param curveId Curve Id to unset exit delay penalty for
    function unsetExitDelayPenalty(uint256 curveId) external;

    /// @notice Get exit delay penalty by the curveId
    /// @dev `defaultExitDelayPenalty` is returned if the value is not set for the given curveId.
    /// @param curveId Curve Id to get exit delay penalty for
    function getExitDelayPenalty(
        uint256 curveId
    ) external view returns (uint256 penalty);

    /// @notice Set max withdrawal request fee for the curveId
    /// @param curveId Curve Id to associate max withdrawal request fee with
    /// @param fee max withdrawal request fee
    function setMaxWithdrawalRequestFee(uint256 curveId, uint256 fee) external;

    /// @notice Unset max withdrawal request fee for the curveId
    /// @param curveId Curve Id to unset max withdrawal request fee for
    function unsetMaxWithdrawalRequestFee(uint256 curveId) external;

    /// @notice Get max withdrawal request fee by the curveId
    /// @dev `defaultMaxWithdrawalRequestFee` is returned if the value is not set for the given curveId.
    /// @param curveId Curve Id to get max withdrawal request fee for
    function getMaxWithdrawalRequestFee(
        uint256 curveId
    ) external view returns (uint256 fee);

    /// @notice Returns the initialized version of the contract
    function getInitializedVersion() external view returns (uint64);
}

// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.24;

import { ICSAccounting } from "./ICSAccounting.sol";
import { ICSParametersRegistry } from "./ICSParametersRegistry.sol";
import { ICSModule } from "./ICSModule.sol";
import { IExitTypes } from "./IExitTypes.sol";

struct MarkedUint248 {
    uint248 value;
    bool isValue;
}

struct ExitPenaltyInfo {
    MarkedUint248 delayPenalty;
    MarkedUint248 strikesPenalty;
    MarkedUint248 withdrawalRequestFee;
}

interface ICSExitPenalties is IExitTypes {
    error ZeroModuleAddress();
    error ZeroParametersRegistryAddress();
    error ZeroStrikesAddress();
    error SenderIsNotModule();
    error SenderIsNotStrikes();
    error ValidatorExitDelayNotApplicable();

    event ValidatorExitDelayProcessed(
        uint256 indexed nodeOperatorId,
        bytes pubkey,
        uint256 delayPenalty
    );
    event TriggeredExitFeeRecorded(
        uint256 indexed nodeOperatorId,
        uint256 indexed exitType,
        bytes pubkey,
        uint256 withdrawalRequestPaidFee,
        uint256 withdrawalRequestRecordedFee
    );
    event StrikesPenaltyProcessed(
        uint256 indexed nodeOperatorId,
        bytes pubkey,
        uint256 strikesPenalty
    );

    function MODULE() external view returns (ICSModule);

    function ACCOUNTING() external view returns (ICSAccounting);

    function PARAMETERS_REGISTRY()
        external
        view
        returns (ICSParametersRegistry);

    function STRIKES() external view returns (address);

    /// @notice Handles tracking and penalization logic for a validator that remains active beyond its eligible exit window.
    /// @dev see IStakingModule.reportValidatorExitDelay for details
    /// @param nodeOperatorId The ID of the node operator whose validator's status is being delivered.
    /// @param publicKey The public key of the validator being reported.
    /// @param eligibleToExitInSec The duration (in seconds) indicating how long the validator has been eligible to exit but has not exited.
    function processExitDelayReport(
        uint256 nodeOperatorId,
        bytes calldata publicKey,
        uint256 eligibleToExitInSec
    ) external;

    /// @notice Process the triggered exit report
    /// @param nodeOperatorId ID of the Node Operator
    /// @param publicKey Public key of the validator
    /// @param withdrawalRequestPaidFee The fee paid for the withdrawal request
    /// @param exitType The type of the exit (0 - direct exit, 1 - forced exit)
    function processTriggeredExit(
        uint256 nodeOperatorId,
        bytes calldata publicKey,
        uint256 withdrawalRequestPaidFee,
        uint256 exitType
    ) external;

    /// @notice Process the strikes report
    /// @param nodeOperatorId ID of the Node Operator
    /// @param publicKey Public key of the validator
    function processStrikesReport(
        uint256 nodeOperatorId,
        bytes calldata publicKey
    ) external;

    /// @notice Determines whether a validator exit status should be updated and will have affect on Node Operator.
    /// @dev called only by CSM
    /// @param nodeOperatorId The ID of the node operator.
    /// @param publicKey Validator's public key.
    /// @param eligibleToExitInSec The number of seconds the validator was eligible to exit but did not.
    /// @return bool Returns true if contract should receive updated validator's status.
    function isValidatorExitDelayPenaltyApplicable(
        uint256 nodeOperatorId,
        bytes calldata publicKey,
        uint256 eligibleToExitInSec
    ) external view returns (bool);

    /// @notice get delayed exit penalty info for the given Node Operator
    /// @param nodeOperatorId ID of the Node Operator
    /// @param publicKey Public key of the validator
    /// @return penaltyInfo Delayed exit penalty info
    function getExitPenaltyInfo(
        uint256 nodeOperatorId,
        bytes calldata publicKey
    ) external view returns (ExitPenaltyInfo memory penaltyInfo);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)

pragma solidity ^0.8.20;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.24;

import { ILidoLocator } from "./ILidoLocator.sol";
import { ILido } from "./ILido.sol";
import { IWithdrawalQueue } from "./IWithdrawalQueue.sol";
import { IWstETH } from "./IWstETH.sol";

interface ICSBondCore {
    event BondDepositedETH(
        uint256 indexed nodeOperatorId,
        address from,
        uint256 amount
    );
    event BondDepositedStETH(
        uint256 indexed nodeOperatorId,
        address from,
        uint256 amount
    );
    event BondDepositedWstETH(
        uint256 indexed nodeOperatorId,
        address from,
        uint256 amount
    );
    event BondClaimedUnstETH(
        uint256 indexed nodeOperatorId,
        address to,
        uint256 amount,
        uint256 requestId
    );
    event BondClaimedStETH(
        uint256 indexed nodeOperatorId,
        address to,
        uint256 amount
    );
    event BondClaimedWstETH(
        uint256 indexed nodeOperatorId,
        address to,
        uint256 amount
    );
    event BondBurned(
        uint256 indexed nodeOperatorId,
        uint256 amountToBurn,
        uint256 burnedAmount
    );
    event BondCharged(
        uint256 indexed nodeOperatorId,
        uint256 toChargeAmount,
        uint256 chargedAmount
    );

    error ZeroLocatorAddress();
    error NothingToClaim();

    function LIDO_LOCATOR() external view returns (ILidoLocator);

    function LIDO() external view returns (ILido);

    function WITHDRAWAL_QUEUE() external view returns (IWithdrawalQueue);

    function WSTETH() external view returns (IWstETH);

    /// @notice Get total bond shares (stETH) stored on the contract
    /// @return Total bond shares (stETH)
    function totalBondShares() external view returns (uint256);

    /// @notice Get bond shares (stETH) for the given Node Operator
    /// @param nodeOperatorId ID of the Node Operator
    /// @return Bond in stETH shares
    function getBondShares(
        uint256 nodeOperatorId
    ) external view returns (uint256);

    /// @notice Get bond amount in ETH (stETH) for the given Node Operator
    /// @param nodeOperatorId ID of the Node Operator
    /// @return Bond amount in ETH (stETH)
    function getBond(uint256 nodeOperatorId) external view returns (uint256);
}

// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.24;

interface ICSBondCurve {
    /// @dev Bond curve structure.
    ///
    /// It contains:
    ///  - intervals    |> intervals-based representation of the bond curve
    ///
    /// The interval is defined by:
    ///  - minKeysCount |> minimum keys count (inclusive) of the interval
    ///  - minBond      |> minimum bond amount (inclusive) of the interval
    ///  - trend        |> trend of the bond amount in the interval
    ///
    /// For example, how the curve intervals look like:
    ///   Interval 0: minKeysCount = 1, minBond = 2 ETH, trend = 2 ETH
    ///   Interval 1: minKeysCount = 2, minBond = 3.9 ETH, trend = 1.9 ETH
    ///   Interval 2: minKeysCount = 3, minBond = 5.7 ETH, trend = 1.8 ETH
    ///
    ///   Bond Amount (ETH)
    ///       ^
    ///       |
    ///     6 -
    ///       | ------------------ 5.7 ETH --> .
    ///   5.5 -                              ..^
    ///       |                             .  |
    ///     5 -                            .   |
    ///       |                           .    |
    ///   4.5 -                          .     |
    ///       |                         .      |
    ///     4 -                       ..       |
    ///       | ------- 3.9 ETH --> ..         |
    ///   3.5 -                    .^          |
    ///       |                  .. |          |
    ///     3 -                ..   |          |
    ///       |               .     |          |
    ///   2.5 -              .      |          |
    ///       |            ..       |          |
    ///     2 - -------->..         |          |
    ///       |          ^          |          |
    ///       |----------|----------|----------|----------|----> Keys Count
    ///       |          1          2          3          i
    ///
    struct BondCurve {
        BondCurveInterval[] intervals;
    }

    struct BondCurveInterval {
        uint256 minKeysCount;
        uint256 minBond;
        uint256 trend;
    }

    struct BondCurveIntervalInput {
        uint256 minKeysCount;
        uint256 trend;
    }

    event BondCurveAdded(
        uint256 indexed curveId,
        BondCurveIntervalInput[] bondCurveIntervals
    );
    event BondCurveUpdated(
        uint256 indexed curveId,
        BondCurveIntervalInput[] bondCurveIntervals
    );
    event BondCurveSet(uint256 indexed nodeOperatorId, uint256 curveId);

    error InvalidBondCurveLength();
    error InvalidBondCurveValues();
    error InvalidBondCurveId();
    error InvalidInitializationCurveId();

    function MIN_CURVE_LENGTH() external view returns (uint256);

    function MAX_CURVE_LENGTH() external view returns (uint256);

    function DEFAULT_BOND_CURVE_ID() external view returns (uint256);

    /// @notice Get the number of available curves
    /// @return Number of available curves
    function getCurvesCount() external view returns (uint256);

    /// @notice Return bond curve for the given curve id
    /// @param curveId Curve id to get bond curve for
    /// @return Bond curve
    /// @dev Reverts if `curveId` is invalid
    function getCurveInfo(
        uint256 curveId
    ) external view returns (BondCurve memory);

    /// @notice Get bond curve for the given Node Operator
    /// @param nodeOperatorId ID of the Node Operator
    /// @return Bond curve
    function getBondCurve(
        uint256 nodeOperatorId
    ) external view returns (BondCurve memory);

    /// @notice Get bond curve ID for the given Node Operator
    /// @param nodeOperatorId ID of the Node Operator
    /// @return Bond curve ID
    function getBondCurveId(
        uint256 nodeOperatorId
    ) external view returns (uint256);

    /// @notice Get required bond in ETH for the given number of keys for default bond curve
    /// @dev To calculate the amount for the new keys 2 calls are required:
    ///      getBondAmountByKeysCount(newTotal) - getBondAmountByKeysCount(currentTotal)
    /// @param keys Number of keys to get required bond for
    /// @param curveId Id of the curve to perform calculations against
    /// @return Amount for particular keys count
    function getBondAmountByKeysCount(
        uint256 keys,
        uint256 curveId
    ) external view returns (uint256);

    /// @notice Get keys count for the given bond amount with default bond curve
    /// @param amount Bond amount in ETH (stETH)to get keys count for
    /// @param curveId Id of the curve to perform calculations against
    /// @return Keys count
    function getKeysCountByBondAmount(
        uint256 amount,
        uint256 curveId
    ) external view returns (uint256);
}

// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.24;

interface ICSBondLock {
    /// @dev Bond lock structure.
    /// It contains:
    ///  - amount   |> amount of locked bond
    ///  - until    |> timestamp until locked bond is retained
    struct BondLock {
        uint128 amount;
        uint128 until;
    }

    event BondLockChanged(
        uint256 indexed nodeOperatorId,
        uint256 newAmount,
        uint256 until
    );
    event BondLockRemoved(uint256 indexed nodeOperatorId);

    event BondLockPeriodChanged(uint256 period);

    error InvalidBondLockPeriod();
    error InvalidBondLockAmount();

    function MIN_BOND_LOCK_PERIOD() external view returns (uint256);

    function MAX_BOND_LOCK_PERIOD() external view returns (uint256);

    /// @notice Get default bond lock period
    /// @return period Default bond lock period
    function getBondLockPeriod() external view returns (uint256 period);

    /// @notice Get information about the locked bond for the given Node Operator
    /// @param nodeOperatorId ID of the Node Operator
    /// @return Locked bond info
    function getLockedBondInfo(
        uint256 nodeOperatorId
    ) external view returns (BondLock memory);

    /// @notice Get amount of the locked bond in ETH (stETH) by the given Node Operator
    /// @param nodeOperatorId ID of the Node Operator
    /// @return Amount of the actual locked bond
    function getActualLockedBond(
        uint256 nodeOperatorId
    ) external view returns (uint256);
}

// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

import { IAssetRecovererLib } from "../lib/AssetRecovererLib.sol";
import { IStETH } from "./IStETH.sol";

pragma solidity 0.8.24;

interface ICSFeeDistributor is IAssetRecovererLib {
    struct DistributionData {
        /// @dev Reference slot for which the report was calculated. If the slot
        /// contains a block, the state being reported should include all state
        /// changes resulting from that block. The epoch containing the slot
        /// should be finalized prior to calculating the report.
        uint256 refSlot;
        /// @notice Merkle Tree root.
        bytes32 treeRoot;
        /// @notice CID of the published Merkle tree.
        string treeCid;
        /// @notice CID of the file with log of the frame reported.
        string logCid;
        /// @notice Total amount of fees distributed in the report.
        uint256 distributed;
        /// @notice Amount of the rebate shares in the report
        uint256 rebate;
    }

    /// @dev Emitted when fees are distributed
    event OperatorFeeDistributed(
        uint256 indexed nodeOperatorId,
        uint256 shares
    );

    /// @dev Emitted when distribution data is updated
    event DistributionDataUpdated(
        uint256 totalClaimableShares,
        bytes32 treeRoot,
        string treeCid
    );

    /// @dev Emitted when distribution log is updated
    event DistributionLogUpdated(string logCid);

    /// @dev It logs how many shares were distributed in the latest report
    event ModuleFeeDistributed(uint256 shares);

    /// @dev Emitted when rebate is transferred
    event RebateTransferred(uint256 shares);

    /// @dev Emitted when rebate recipient is set
    event RebateRecipientSet(address recipient);

    error ZeroAccountingAddress();
    error ZeroStEthAddress();
    error ZeroAdminAddress();
    error ZeroOracleAddress();
    error ZeroRebateRecipientAddress();
    error SenderIsNotAccounting();
    error SenderIsNotOracle();

    error InvalidReportData();
    error InvalidTreeRoot();
    error InvalidTreeCid();
    error InvalidLogCID();
    error InvalidShares();
    error InvalidProof();
    error FeeSharesDecrease();
    error NotEnoughShares();

    function RECOVERER_ROLE() external view returns (bytes32);

    function STETH() external view returns (IStETH);

    function ACCOUNTING() external view returns (address);

    function ORACLE() external view returns (address);

    function treeRoot() external view returns (bytes32);

    function treeCid() external view returns (string calldata);

    function logCid() external view returns (string calldata);

    function distributedShares(uint256) external view returns (uint256);

    function totalClaimableShares() external view returns (uint256);

    function distributionDataHistoryCount() external view returns (uint256);

    function rebateRecipient() external view returns (address);

    /// @notice Get the initialized version of the contract
    function getInitializedVersion() external view returns (uint64);

    /// @notice Set address to send rebate to
    /// @param _rebateRecipient Address to send rebate to
    function setRebateRecipient(address _rebateRecipient) external;

    /// @notice Get the Amount of stETH shares that can be distributed in favor of the Node Operator
    /// @param nodeOperatorId ID of the Node Operator
    /// @param cumulativeFeeShares Total Amount of stETH shares earned as fees
    /// @param proof Merkle proof of the leaf
    /// @return sharesToDistribute Amount of stETH shares that can be distributed
    function getFeesToDistribute(
        uint256 nodeOperatorId,
        uint256 cumulativeFeeShares,
        bytes32[] calldata proof
    ) external view returns (uint256);

    /// @notice Distribute fees to the Accounting in favor of the Node Operator
    /// @param nodeOperatorId ID of the Node Operator
    /// @param cumulativeFeeShares Total Amount of stETH shares earned as fees
    /// @param proof Merkle proof of the leaf
    /// @return sharesToDistribute Amount of stETH shares distributed
    function distributeFees(
        uint256 nodeOperatorId,
        uint256 cumulativeFeeShares,
        bytes32[] calldata proof
    ) external returns (uint256);

    /// @notice Receive the data of the Merkle tree from the Oracle contract and process it
    /// @param _treeRoot Root of the Merkle tree
    /// @param _treeCid an IPFS CID of the tree
    /// @param _logCid an IPFS CID of the log
    /// @param distributed an amount of the distributed shares
    /// @param rebate an amount of the rebate shares
    /// @param refSlot refSlot of the report
    function processOracleReport(
        bytes32 _treeRoot,
        string calldata _treeCid,
        string calldata _logCid,
        uint256 distributed,
        uint256 rebate,
        uint256 refSlot
    ) external;

    /// @notice Get the Amount of stETH shares that are pending to be distributed
    /// @return pendingShares Amount shares that are pending to distribute
    function pendingSharesToDistribute() external view returns (uint256);

    /// @notice Get the historical record of distribution data
    /// @param index Historical entry index
    /// @return Historical distribution data
    function getHistoricalDistributionData(
        uint256 index
    ) external view returns (DistributionData memory);

    /// @notice Get a hash of a leaf
    /// @param nodeOperatorId ID of the Node Operator
    /// @param shares Amount of stETH shares
    /// @return Hash of the leaf
    /// @dev Double hash the leaf to prevent second preimage attacks
    function hashLeaf(
        uint256 nodeOperatorId,
        uint256 shares
    ) external pure returns (bytes32);
}

// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.24;

type TransientUintUintMap is uint256;

using TransientUintUintMapLib for TransientUintUintMap global;

library TransientUintUintMapLib {
    function create() internal returns (TransientUintUintMap self) {
        // keccak256(abi.encode(uint256(keccak256("TransientUintUintMap")) - 1)) & ~bytes32(uint256(0xff))
        uint256 anchor = 0x6e38e7eaa4307e6ee6c66720337876ca65012869fbef035f57219354c1728400;

        // `anchor` slot in the transient storage tracks the "address" of the last created object.
        // The next address is being computed as keccak256(`anchor` . `prev`).
        assembly ("memory-safe") {
            let prev := tload(anchor)
            mstore(0x00, anchor)
            mstore(0x20, prev)
            self := keccak256(0x00, 0x40)
            tstore(anchor, self)
        }
    }

    function add(
        TransientUintUintMap self,
        uint256 key,
        uint256 value
    ) internal {
        uint256 slot = _slot(self, key);
        assembly ("memory-safe") {
            let v := tload(slot)
            // NOTE: Here's no overflow check.
            v := add(v, value)
            tstore(slot, v)
        }
    }

    function set(
        TransientUintUintMap self,
        uint256 key,
        uint256 value
    ) internal {
        uint256 slot = _slot(self, key);
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    function get(
        TransientUintUintMap self,
        uint256 key
    ) internal view returns (uint256 v) {
        uint256 slot = _slot(self, key);
        assembly ("memory-safe") {
            v := tload(slot)
        }
    }

    function load(
        bytes32 tslot
    ) internal pure returns (TransientUintUintMap self) {
        assembly ("memory-safe") {
            self := tslot
        }
    }

    function _slot(
        TransientUintUintMap self,
        uint256 key
    ) internal pure returns (uint256 slot) {
        // Compute an address in the transient storage in the same manner it works for storage mappings.
        // `slot` = keccak256(`self` . `key`)
        assembly ("memory-safe") {
            mstore(0x00, self)
            mstore(0x20, key)
            slot := keccak256(0x00, 0x40)
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
     *   {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (token/ERC1155/IERC1155.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[EIP].
 */
interface IERC1155 is IERC165 {
    /**
     * @dev Emitted when `value` amount of tokens of type `id` are transferred from `from` to `to` by `operator`.
     */
    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);

    /**
     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
     * transfers.
     */
    event TransferBatch(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256[] ids,
        uint256[] values
    );

    /**
     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
     * `approved`.
     */
    event ApprovalForAll(address indexed account, address indexed operator, bool approved);

    /**
     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
     *
     * If an {URI} event was emitted for `id`, the standard
     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
     * returned by {IERC1155MetadataURI-uri}.
     */
    event URI(string value, uint256 indexed id);

    /**
     * @dev Returns the value of tokens of token type `id` owned by `account`.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function balanceOf(address account, uint256 id) external view returns (uint256);

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(
        address[] calldata accounts,
        uint256[] calldata ids
    ) external view returns (uint256[] memory);

    /**
     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `operator` cannot be the caller.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
     *
     * See {setApprovalForAll}.
     */
    function isApprovedForAll(address account, address operator) external view returns (bool);

    /**
     * @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`.
     *
     * WARNING: This function can potentially allow a reentrancy attack when transferring tokens
     * to an untrusted contract, when invoking {onERC1155Received} on the receiver.
     * Ensure to follow the checks-effects-interactions pattern and consider employing
     * reentrancy guards when interacting with untrusted contracts.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
     * - `from` must have a balance of tokens of type `id` of at least `value` amount.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes calldata data) external;

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
     *
     * WARNING: This function can potentially allow a reentrancy attack when transferring tokens
     * to an untrusted contract, when invoking {onERC1155BatchReceived} on the receiver.
     * Ensure to follow the checks-effects-interactions pattern and consider employing
     * reentrancy guards when interacting with untrusted contracts.
     *
     * Emits either a {TransferSingle} or a {TransferBatch} event, depending on the length of the array arguments.
     *
     * Requirements:
     *
     * - `ids` and `values` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev An operation with an ERC20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
    }
}

// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.24;

import { IStETH } from "./IStETH.sol";

/**
 * @title Interface defining Lido contract
 */
interface ILido is IStETH {
    function STAKING_CONTROL_ROLE() external view returns (bytes32);

    function submit(address _referral) external payable returns (uint256);

    function deposit(
        uint256 _maxDepositsCount,
        uint256 _stakingModuleId,
        bytes calldata _depositCalldata
    ) external;

    function removeStakingLimit() external;

    function kernel() external returns (address);

    function sharesOf(address _account) external view returns (uint256);
}

// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.24;

interface IExitTypes {
    function VOLUNTARY_EXIT_TYPE_ID() external view returns (uint8);

    function STRIKES_EXIT_TYPE_ID() external view returns (uint8);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.24;

interface IWithdrawalQueue {
    struct WithdrawalRequestStatus {
        /// @notice stETH token amount that was locked on withdrawal queue for this request
        uint256 amountOfStETH;
        /// @notice amount of stETH shares locked on withdrawal queue for this request
        uint256 amountOfShares;
        /// @notice address that can claim or transfer this request
        address owner;
        /// @notice timestamp of when the request was created, in seconds
        uint256 timestamp;
        /// @notice true, if request is finalized
        bool isFinalized;
        /// @notice true, if request is claimed. Request is claimable if (isFinalized && !isClaimed)
        bool isClaimed;
    }

    function ORACLE_ROLE() external view returns (bytes32);

    function getRoleMember(
        bytes32 role,
        uint256 index
    ) external view returns (address);

    function WSTETH() external view returns (address);

    /// @notice minimal amount of stETH that is possible to withdraw
    function MIN_STETH_WITHDRAWAL_AMOUNT() external view returns (uint256);

    /// @notice maximum amount of stETH that is possible to withdraw by a single request
    /// Prevents accumulating too much funds per single request fulfillment in the future.
    /// @dev To withdraw larger amounts, it's recommended to split it to several requests
    function MAX_STETH_WITHDRAWAL_AMOUNT() external view returns (uint256);

    function requestWithdrawals(
        uint256[] calldata _amounts,
        address _owner
    ) external returns (uint256[] memory requestIds);

    function getWithdrawalStatus(
        uint256[] calldata _requestIds
    ) external view returns (WithdrawalRequestStatus[] memory statuses);

    function getWithdrawalRequests(
        address _owner
    ) external view returns (uint256[] memory requestsIds);

    function isBunkerModeActive() external view returns (bool);

    function onOracleReport(
        bool _isBunkerModeNow,
        uint256 _bunkerStartTimestamp,
        uint256 _currentReportTimestamp
    ) external;
}

// SPDX-FileCopyrightText: 2025 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.24;

interface IWstETH {
    function balanceOf(address account) external view returns (uint256);

    function approve(address _spender, uint256 _amount) external returns (bool);

    function wrap(uint256 _stETHAmount) external returns (uint256);

    function unwrap(uint256 _wstETHAmount) external returns (uint256);

    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) external;

    function transfer(address recipient, uint256 amount) external;

    function getStETHByWstETH(
        uint256 _wstETHAmount
    ) external view returns (uint256);

    function getWstETHByStETH(
        uint256 _stETHAmount
    ) external view returns (uint256);

    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    function allowance(
        address _owner,
        address _spender
    ) external view returns (uint256);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

// 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();
        }
    }
}

Settings
{
  "remappings": [
    "@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
    "@openzeppelin/contracts-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable/",
    "forge-std/=node_modules/forge-std/src/",
    "ds-test/=node_modules/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "openzeppelin-contracts-v4.4/=lib/openzeppelin-contracts-v4.4/contracts/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 250
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "none",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "cancun",
  "viaIR": false
}

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"withdrawalAddress","type":"address"},{"internalType":"address","name":"module","type":"address"},{"internalType":"uint64","name":"slotsPerEpoch","type":"uint64"},{"internalType":"uint64","name":"slotsPerHistoricalRoot","type":"uint64"},{"components":[{"internalType":"GIndex","name":"gIFirstWithdrawalPrev","type":"bytes32"},{"internalType":"GIndex","name":"gIFirstWithdrawalCurr","type":"bytes32"},{"internalType":"GIndex","name":"gIFirstValidatorPrev","type":"bytes32"},{"internalType":"GIndex","name":"gIFirstValidatorCurr","type":"bytes32"},{"internalType":"GIndex","name":"gIFirstHistoricalSummaryPrev","type":"bytes32"},{"internalType":"GIndex","name":"gIFirstHistoricalSummaryCurr","type":"bytes32"},{"internalType":"GIndex","name":"gIFirstBlockRootInSummaryPrev","type":"bytes32"},{"internalType":"GIndex","name":"gIFirstBlockRootInSummaryCurr","type":"bytes32"}],"internalType":"struct ICSVerifier.GIndices","name":"gindices","type":"tuple"},{"internalType":"Slot","name":"firstSupportedSlot","type":"uint64"},{"internalType":"Slot","name":"pivotSlot","type":"uint64"},{"internalType":"Slot","name":"capellaSlot","type":"uint64"},{"internalType":"address","name":"admin","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AccessControlBadConfirmation","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bytes32","name":"neededRole","type":"bytes32"}],"name":"AccessControlUnauthorizedAccount","type":"error"},{"inputs":[],"name":"HistoricalSummaryDoesNotExist","type":"error"},{"inputs":[],"name":"IndexOutOfRange","type":"error"},{"inputs":[],"name":"InvalidBlockHeader","type":"error"},{"inputs":[],"name":"InvalidCapellaSlot","type":"error"},{"inputs":[],"name":"InvalidChainConfig","type":"error"},{"inputs":[],"name":"InvalidPivotSlot","type":"error"},{"inputs":[],"name":"InvalidWithdrawalAddress","type":"error"},{"inputs":[],"name":"PartialWithdrawal","type":"error"},{"inputs":[],"name":"PauseUntilMustBeInFuture","type":"error"},{"inputs":[],"name":"PausedExpected","type":"error"},{"inputs":[],"name":"ResumedExpected","type":"error"},{"inputs":[],"name":"RootNotFound","type":"error"},{"inputs":[{"internalType":"Slot","name":"slot","type":"uint64"}],"name":"UnsupportedSlot","type":"error"},{"inputs":[],"name":"ValidatorNotWithdrawn","type":"error"},{"inputs":[],"name":"ZeroAdminAddress","type":"error"},{"inputs":[],"name":"ZeroModuleAddress","type":"error"},{"inputs":[],"name":"ZeroPauseDuration","type":"error"},{"inputs":[],"name":"ZeroWithdrawalAddress","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"duration","type":"uint256"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[],"name":"Resumed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"inputs":[],"name":"BEACON_ROOTS","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"CAPELLA_SLOT","outputs":[{"internalType":"Slot","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"FIRST_SUPPORTED_SLOT","outputs":[{"internalType":"Slot","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"GI_FIRST_BLOCK_ROOT_IN_SUMMARY_CURR","outputs":[{"internalType":"GIndex","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"GI_FIRST_BLOCK_ROOT_IN_SUMMARY_PREV","outputs":[{"internalType":"GIndex","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"GI_FIRST_HISTORICAL_SUMMARY_CURR","outputs":[{"internalType":"GIndex","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"GI_FIRST_HISTORICAL_SUMMARY_PREV","outputs":[{"internalType":"GIndex","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"GI_FIRST_VALIDATOR_CURR","outputs":[{"internalType":"GIndex","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"GI_FIRST_VALIDATOR_PREV","outputs":[{"internalType":"GIndex","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"GI_FIRST_WITHDRAWAL_CURR","outputs":[{"internalType":"GIndex","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"GI_FIRST_WITHDRAWAL_PREV","outputs":[{"internalType":"GIndex","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MODULE","outputs":[{"internalType":"contract ICSModule","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PAUSE_INFINITELY","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PAUSE_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PIVOT_SLOT","outputs":[{"internalType":"Slot","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"RESUME_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SLOTS_PER_EPOCH","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SLOTS_PER_HISTORICAL_ROOT","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WITHDRAWAL_ADDRESS","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getResumeSinceTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getRoleMember","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleMemberCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"duration","type":"uint256"}],"name":"pauseFor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"components":[{"internalType":"Slot","name":"slot","type":"uint64"},{"internalType":"uint64","name":"proposerIndex","type":"uint64"},{"internalType":"bytes32","name":"parentRoot","type":"bytes32"},{"internalType":"bytes32","name":"stateRoot","type":"bytes32"},{"internalType":"bytes32","name":"bodyRoot","type":"bytes32"}],"internalType":"struct BeaconBlockHeader","name":"header","type":"tuple"},{"internalType":"uint64","name":"rootsTimestamp","type":"uint64"}],"internalType":"struct ICSVerifier.ProvableBeaconBlockHeader","name":"beaconBlock","type":"tuple"},{"components":[{"components":[{"internalType":"Slot","name":"slot","type":"uint64"},{"internalType":"uint64","name":"proposerIndex","type":"uint64"},{"internalType":"bytes32","name":"parentRoot","type":"bytes32"},{"internalType":"bytes32","name":"stateRoot","type":"bytes32"},{"internalType":"bytes32","name":"bodyRoot","type":"bytes32"}],"internalType":"struct BeaconBlockHeader","name":"header","type":"tuple"},{"internalType":"bytes32[]","name":"proof","type":"bytes32[]"}],"internalType":"struct ICSVerifier.HistoricalHeaderWitness","name":"oldBlock","type":"tuple"},{"components":[{"internalType":"uint8","name":"withdrawalOffset","type":"uint8"},{"internalType":"uint64","name":"withdrawalIndex","type":"uint64"},{"internalType":"uint64","name":"validatorIndex","type":"uint64"},{"internalType":"uint64","name":"amount","type":"uint64"},{"internalType":"bytes32","name":"withdrawalCredentials","type":"bytes32"},{"internalType":"uint64","name":"effectiveBalance","type":"uint64"},{"internalType":"bool","name":"slashed","type":"bool"},{"internalType":"uint64","name":"activationEligibilityEpoch","type":"uint64"},{"internalType":"uint64","name":"activationEpoch","type":"uint64"},{"internalType":"uint64","name":"exitEpoch","type":"uint64"},{"internalType":"uint64","name":"withdrawableEpoch","type":"uint64"},{"internalType":"bytes32[]","name":"withdrawalProof","type":"bytes32[]"},{"internalType":"bytes32[]","name":"validatorProof","type":"bytes32[]"}],"internalType":"struct ICSVerifier.WithdrawalWitness","name":"witness","type":"tuple"},{"internalType":"uint256","name":"nodeOperatorId","type":"uint256"},{"internalType":"uint256","name":"keyIndex","type":"uint256"}],"name":"processHistoricalWithdrawalProof","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"components":[{"internalType":"Slot","name":"slot","type":"uint64"},{"internalType":"uint64","name":"proposerIndex","type":"uint64"},{"internalType":"bytes32","name":"parentRoot","type":"bytes32"},{"internalType":"bytes32","name":"stateRoot","type":"bytes32"},{"internalType":"bytes32","name":"bodyRoot","type":"bytes32"}],"internalType":"struct BeaconBlockHeader","name":"header","type":"tuple"},{"internalType":"uint64","name":"rootsTimestamp","type":"uint64"}],"internalType":"struct ICSVerifier.ProvableBeaconBlockHeader","name":"beaconBlock","type":"tuple"},{"components":[{"internalType":"uint8","name":"withdrawalOffset","type":"uint8"},{"internalType":"uint64","name":"withdrawalIndex","type":"uint64"},{"internalType":"uint64","name":"validatorIndex","type":"uint64"},{"internalType":"uint64","name":"amount","type":"uint64"},{"internalType":"bytes32","name":"withdrawalCredentials","type":"bytes32"},{"internalType":"uint64","name":"effectiveBalance","type":"uint64"},{"internalType":"bool","name":"slashed","type":"bool"},{"internalType":"uint64","name":"activationEligibilityEpoch","type":"uint64"},{"internalType":"uint64","name":"activationEpoch","type":"uint64"},{"internalType":"uint64","name":"exitEpoch","type":"uint64"},{"internalType":"uint64","name":"withdrawableEpoch","type":"uint64"},{"internalType":"bytes32[]","name":"withdrawalProof","type":"bytes32[]"},{"internalType":"bytes32[]","name":"validatorProof","type":"bytes32[]"}],"internalType":"struct ICSVerifier.WithdrawalWitness","name":"witness","type":"tuple"},{"internalType":"uint256","name":"nodeOperatorId","type":"uint256"},{"internalType":"uint256","name":"keyIndex","type":"uint256"}],"name":"processWithdrawalProof","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"callerConfirmation","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"resume","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"}]

0x61026060405234801562000011575f80fd5b5060405162002c8b38038062002c8b833981016040819052620000349162000386565b6001600160a01b0389166200005c57604051631e2add6160e21b815260040160405180910390fd5b6001600160a01b03881662000084576040516378bc317d60e01b815260040160405180910390fd5b6001600160a01b038116620000ac57604051633ef39b8160e01b815260040160405180910390fd5b866001600160401b03165f03620000d65760405163fb305deb60e01b815260040160405180910390fd5b856001600160401b03165f03620001005760405163fb305deb60e01b815260040160405180910390fd5b6200010c8484620001f4565b156200012b576040516335a28bdb60e21b815260040160405180910390fd5b620001378285620001f4565b156200015657604051635a689a5760e11b815260040160405180910390fd5b6001600160a01b03808a16610220528816610240526001600160401b03808816608090815287821660a0908152875160c0908152602089015160e090815260408a01516101005260608a01516101205292890151610140529088015161016052870151610180528601516101a0528481166101c0528381166101e052821661020052620001e45f826200020a565b50505050505050505050620004d1565b6001600160401b03818116908316115b92915050565b5f8062000218848462000243565b905080156200023c575f8481526001602052604090206200023a9084620002ee565b505b9392505050565b5f828152602081815260408083206001600160a01b038516845290915281205460ff16620002e6575f838152602081815260408083206001600160a01b03861684529091529020805460ff191660011790556200029d3390565b6001600160a01b0316826001600160a01b0316847f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a450600162000204565b505f62000204565b5f6200023c836001600160a01b0384165f818152600183016020526040812054620002e657508154600181810184555f84815260208082209093018490558454848252828601909352604090209190915562000204565b80516001600160a01b03811681146200035c575f80fd5b919050565b6001600160401b038116811462000376575f80fd5b50565b80516200035c8162000361565b5f805f805f805f805f898b03610200811215620003a1575f80fd5b620003ac8b62000345565b9950620003bc60208c0162000345565b985060408b0151620003ce8162000361565b60608c0151909850620003e18162000361565b9650610100607f198201811315620003f7575f80fd5b60405191508082016001600160401b03811183821017156200042757634e487b7160e01b5f52604160045260245ffd5b806040525060808c0151825260a08c0151602083015260c08c0151604083015260e08c01516060830152808c01516080830152506101208b015160a08201526101408b015160c08201526101608b015160e0820152809550506200048f6101808b0162000379565b9350620004a06101a08b0162000379565b9250620004b16101c08b0162000379565b9150620004c26101e08b0162000345565b90509295985092959850929598565b60805160a05160c05160e05161010051610120516101405161016051610180516101a0516101c0516101e051610200516102205161024051612677620006145f395f818161026d01528181610794015281816108c501528181610aa40152610bca01525f818161031c0152610fbf01525f81816104da01526112a901525f8181610501015281816113ba0152818161144f015281816119df0152611c2601525f818161048c01526106b901525f81816102ac015261147a01525f81816104b301526114a001525f81816105d901526113e501525f81816102f5015261140b01525f81816103ca0152611a0a01525f81816104300152611a3001525f818161022e0152611c5101525f81816105780152611c7801525f81816103f1015281816112e501528181611312015261134501525f81816105b2015261183b01526126775ff3fe608060405234801561000f575f80fd5b50600436106101fd575f3560e01c8063589ff76c11610114578063a217fddf116100a9578063d461395311610079578063d461395314610573578063d547741f1461059a578063da30e279146105ad578063e9235bc7146105d4578063f3f449c7146105fb575f80fd5b8063a217fddf14610549578063a302ee3814610550578063b187bd2614610558578063ca15c87314610560575f80fd5b80638d0f1fc9116100e45780638d0f1fc9146104d55780638f60eab9146104fc5780639010d07c1461052357806391d1485414610536575f80fd5b8063589ff76c1461046c5780635922977b1461047457806376e2128d1461048757806382bcd3a0146104ae575f80fd5b80632de03aa111610195578063389ed26711610165578063389ed2671461039e5780633a5e31fe146103c557806349939d18146103ec578063562d7d671461042b57806356d7e8fd14610452575f80fd5b80632de03aa11461033e5780632f2ff15d14610365578063305c24eb1461037857806336568abe1461038b575f80fd5b806316e08ca1116101d057806316e08ca1146102a7578063248a9ca3146102ce57806325256d98146102f05780632601d3c714610317575f80fd5b806301ffc9a71461020157806303d9d98214610229578063046f7da21461025e578063094d3a3414610268575b5f80fd5b61021461020f36600461210e565b61060e565b60405190151581526020015b60405180910390f35b6102507f000000000000000000000000000000000000000000000000000000000000000081565b604051908152602001610220565b610266610638565b005b61028f7f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b039091168152602001610220565b6102507f000000000000000000000000000000000000000000000000000000000000000081565b6102506102dc366004612135565b5f9081526020819052604090206001015490565b6102507f000000000000000000000000000000000000000000000000000000000000000081565b61028f7f000000000000000000000000000000000000000000000000000000000000000081565b6102507f2fc10cc8ae19568712f7a176fb4978616a610650813c9d05326c34abb62749c781565b61026661037336600461214c565b61066d565b6102666103863660046121ac565b610697565b61026661039936600461214c565b610930565b6102507f139c2898040ef16910dc9f44dc697df79363da767d8bc92f2e310312b816e46d81565b6102507f000000000000000000000000000000000000000000000000000000000000000081565b6104137f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160401b039091168152602001610220565b6102507f000000000000000000000000000000000000000000000000000000000000000081565b61028f720f3df6d732807ef1319fb7b8bb8522d0beac0281565b610250610968565b610266610482366004612208565b610996565b6104137f000000000000000000000000000000000000000000000000000000000000000081565b6102507f000000000000000000000000000000000000000000000000000000000000000081565b6104137f000000000000000000000000000000000000000000000000000000000000000081565b6104137f000000000000000000000000000000000000000000000000000000000000000081565b61028f61053136600461228b565b610c36565b61021461054436600461214c565b610c54565b6102505f81565b6102505f1981565b610214610c7c565b61025061056e366004612135565b610cac565b6102507f000000000000000000000000000000000000000000000000000000000000000081565b6102666105a836600461214c565b610cc2565b6104137f000000000000000000000000000000000000000000000000000000000000000081565b6102507f000000000000000000000000000000000000000000000000000000000000000081565b610266610609366004612135565b610ce6565b5f6001600160e01b03198216635a05180f60e01b1480610632575061063282610d1d565b92915050565b7f2fc10cc8ae19568712f7a176fb4978616a610650813c9d05326c34abb62749c761066281610d51565b61066a610d5b565b50565b5f8281526020819052604090206001015461068781610d51565b6106918383610db0565b50505050565b61069f610de3565b6106e06106af60208601866122bf565b6001600160401b037f0000000000000000000000000000000000000000000000000000000000000000811691161090565b1561071c576106f260208501856122bf565b604051630a303f9760e31b81526001600160401b0390911660048201526024015b60405180910390fd5b5f61073561073060c0870160a088016122bf565b610e0b565b905061074e610749368790038701876122ee565b610edc565b811461076d576040516308c9b65f60e31b815260040160405180910390fd5b50604051632cf12e0960e11b81526004810183905260248101829052600160448201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906359e25c12906064015f60405180830381865afa1580156107e0573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610807919081019061238f565b90505f6108268561081b60208901896122bf565b606089013585610fb7565b6040805160018082528183019092529192505f9190816020015b61086160405180606001604052805f81526020015f81526020015f81525090565b815260200190600190039081610840579050509050604051806060016040528086815260200185815260200183815250815f815181106108a3576108a361242b565b6020908102919091010152604051639c963aef60e01b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690639c963aef906108fa90849060040161243f565b5f604051808303815f87803b158015610911575f80fd5b505af1158015610923573d5f803e3d5ffd5b5050505050505050505050565b6001600160a01b03811633146109595760405163334bd91960e11b815260040160405180910390fd5b6109638282611272565b505050565b5f6109917fe8b012900cb200ee5dfc3b895a32791b67d12891b09f117814f167a237783a025490565b905090565b61099e610de3565b6109ae6106af60208701876122bf565b156109c0576106f260208601866122bf565b6109d06106af60208601866122bf565b156109e2576106f260208501856122bf565b5f6109f661073060c0880160a089016122bf565b90505f610a0b610749368990038901896122ee565b9050808214610a2d576040516308c9b65f60e31b815260040160405180910390fd5b50610a7e9050610a4060a0860186612497565b6060880135610a57610749368a90038a018a6122ee565b610a79610a6760208c018c6122bf565b610a7460208c018c6122bf565b61129d565b6114e7565b604051632cf12e0960e11b81526004810183905260248101829052600160448201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906359e25c12906064015f60405180830381865afa158015610af0573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610b17919081019061238f565b90505f610b2b8561081b60208901896122bf565b6040805160018082528183019092529192505f9190816020015b610b6660405180606001604052805f81526020015f81526020015f81525090565b815260200190600190039081610b45579050509050604051806060016040528086815260200185815260200183815250815f81518110610ba857610ba861242b565b6020908102919091010152604051639c963aef60e01b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690639c963aef90610bff90849060040161243f565b5f604051808303815f87803b158015610c16575f80fd5b505af1158015610c28573d5f803e3d5ffd5b505050505050505050505050565b5f828152600160205260408120610c4d908361158b565b9392505050565b5f918252602082815260408084206001600160a01b0393909316845291905290205460ff1690565b5f610ca57fe8b012900cb200ee5dfc3b895a32791b67d12891b09f117814f167a237783a025490565b4210905090565b5f81815260016020526040812061063290611596565b5f82815260208190526040902060010154610cdc81610d51565b6106918383611272565b7f139c2898040ef16910dc9f44dc697df79363da767d8bc92f2e310312b816e46d610d1081610d51565b610d198261159f565b5050565b5f6001600160e01b03198216637965db0b60e01b148061063257506301ffc9a760e01b6001600160e01b0319831614610632565b61066a81336115ee565b610d63611627565b427fe8b012900cb200ee5dfc3b895a32791b67d12891b09f117814f167a237783a02556040517f62451d457bc659158be6e6247f56ec1df424a5c7597f71c20c2bc44e0965c8f9905f90a1565b5f80610dbc848461164c565b90508015610c4d575f848152600160205260409020610ddb90846116db565b509392505050565b610deb610c7c565b15610e0957604051630286f07360e31b815260040160405180910390fd5b565b604080516001600160401b03831660208201525f9182918291720f3df6d732807ef1319fb7b8bb8522d0beac02910160408051601f1981840301815290829052610e54916124e3565b5f60405180830381855afa9150503d805f8114610e8c576040519150601f19603f3d011682016040523d82523d5f602084013e610e91565b606091505b5091509150811580610ea257508051155b15610ec057604051633033b0ff60e01b815260040160405180910390fd5b80806020019051810190610ed491906124fe565b949350505050565b60408051610100810190915281515f9182918190610f02906001600160401b03166116ef565b8152602001610f1d85602001516001600160401b03166116ef565b81526020018460400151815260200184606001518152602001846080015181526020015f801b81526020015f801b81526020015f801b815250905060085b81828260051b81015b6040825f5e60205f60405f60025afa80610f7c575f80fd5b505f518352602083019250604082019150808210610f645750505060011c5f198101610fab575f519250610fb0565b610f5b565b5050919050565b5f60808501357f00000000000000000000000000000000000000000000000000000000000000006001600160a01b039081169082161461100a57604051634261081360e11b815260040160405180910390fd5b61101c610160870161014088016122bf565b6001600160401b031661102e86611835565b101561104d57604051631adfa87360e01b815260040160405180910390fd5b61105d60e0870160c08801612515565b1580156110885750676f05b59d3b2000006110866110816080890160608a016122bf565b611878565b105b156110a65760405163653f0b3960e01b815260040160405180910390fd5b6040805161010081018252848152608088013560208201525f9181016110d260c08a0160a08b016122bf565b6001600160401b031681526020016110f060e08a0160c08b01612515565b151581526020016111086101008a0160e08b016122bf565b6001600160401b031681526020016111286101208a016101008b016122bf565b6001600160401b031681526020016111486101408a016101208b016122bf565b6001600160401b031681526020016111686101608a016101408b016122bf565b6001600160401b0316905290506111b2611186610180890189612497565b8761119085611890565b610a796111a360608e0160408f016122bf565b6001600160401b03168c6119d3565b5f60405180608001604052808960200160208101906111d191906122bf565b6001600160401b031681526020016111ef60608b0160408c016122bf565b6001600160401b031681526001600160a01b038516602082015260400161121c60808b0160608c016122bf565b6001600160401b03169052905061125d61123a6101608a018a612497565b8861124485611a5c565b610a7961125460208f018f612534565b60ff168d611c1a565b61126681611ca1565b98975050505050505050565b5f8061127e8484611caf565b90508015610c4d575f848152600160205260409020610ddb9084611d18565b5f806001600160401b037f0000000000000000000000000000000000000000000000000000000000000000166001600160401b0384166112dd9190612568565b90505f61130a7f00000000000000000000000000000000000000000000000000000000000000008361259c565b90505f6113407f00000000000000000000000000000000000000000000000000000000000000006001600160401b0387166125c1565b90505f7f0000000000000000000000000000000000000000000000000000000000000000611377836001600160401b038916612568565b61138191906125e6565b90506001600160401b0380881690821611156113b05760405163e2c15c0760e01b815260040160405180910390fd5b6001600160401b037f0000000000000000000000000000000000000000000000000000000000000000811690881610611409577f000000000000000000000000000000000000000000000000000000000000000061142b565b7f00000000000000000000000000000000000000000000000000000000000000005b9450611440856001600160401b038516611d2c565b94506114c76001600160401b037f000000000000000000000000000000000000000000000000000000000000000081169083161061149e577f00000000000000000000000000000000000000000000000000000000000000006114c0565b7f00000000000000000000000000000000000000000000000000000000000000005b8690611d9e565b94506114dc856001600160401b038416611d2c565b979650505050505050565b5f6114f28260081c90565b905084611506576309bde3395f526004601cfd5b8460051b8601865b6001831660051b8360011c93508361152d57635849603f5f526004601cfd5b85815281356020918218525f60408160025afa80611549575f80fd5b505f51945060200181811061150e5750506001811461156f57631b6661c35f526004601cfd5b838314611583576309bde3395f526004601cfd5b505050505050565b5f610c4d8383611e1e565b5f610632825490565b6115a7610de3565b805f036115c75760405163ad58bfc760e01b815260040160405180910390fd5b5f5f1982036115d857505f196115e5565b6115e28242612606565b90505b610d1981611e44565b6115f88282610c54565b610d195760405163e2517d3f60e01b81526001600160a01b038216600482015260248101839052604401610713565b61162f610c7c565b610e095760405163b047186b60e01b815260040160405180910390fd5b5f6116578383610c54565b6116d4575f838152602081815260408083206001600160a01b03861684529091529020805460ff1916600117905561168c3390565b6001600160a01b0316826001600160a01b0316847f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a4506001610632565b505f610632565b5f610c4d836001600160a01b038416611ee6565b5f6008827eff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff16901b6008837fff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff0016901c1791506010827dffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff16901b6010837fffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff000016901c1791506020827bffffffff00000000ffffffff00000000ffffffff00000000ffffffff16901b6020837fffffffff00000000ffffffff00000000ffffffff00000000ffffffff0000000016901c17915060408277ffffffffffffffff0000000000000000ffffffffffffffff16901b60408377ffffffffffffffff0000000000000000ffffffffffffffff1916901c179150608082901b608083901c179150815f1b9050919050565b5f6118697f00000000000000000000000000000000000000000000000000000000000000006001600160401b03841661259c565b6001600160401b031692915050565b5f6106326001600160401b038316633b9aca00612619565b80515f908190603060208201835e506010606060305e60205f60405f60025afa806118b9575f80fd5b505f5190505f604051806101000160405280838152602001856020015181526020016118f186604001516001600160401b03166116ef565b81526020016119038660600151611f2b565b815260200161191e86608001516001600160401b03166116ef565b81526020016119398660a001516001600160401b03166116ef565b81526020016119548660c001516001600160401b03166116ef565b815260200161196f8660e001516001600160401b03166116ef565b9052905060085b81828260051b81015b6040825f5e60205f60405f60025afa80611997575f80fd5b505f51835260208301925060408201915080821061197f5750505060011c5f1981016119c6575f5193506119cb565b611976565b505050919050565b5f806001600160401b037f0000000000000000000000000000000000000000000000000000000000000000811690841610611a2e577f0000000000000000000000000000000000000000000000000000000000000000611a50565b7f00000000000000000000000000000000000000000000000000000000000000005b9050610ed48185611d2c565b5f600280611a75845f01516001600160401b03166116ef565b611a8b85602001516001600160401b03166116ef565b60408051602081019390935282015260600160408051601f1981840301815290829052611ab7916124e3565b602060405180830381855afa158015611ad2573d5f803e3d5ffd5b5050506040513d601f19601f82011682018060405250810190611af591906124fe565b6002846040015160601b5f60a01b611b1987606001516001600160401b03166116ef565b604080516bffffffffffffffffffffffff19909416602085015273ffffffffffffffffffffffffffffffffffffffff1990921660348401529082015260600160408051601f1981840301815290829052611b72916124e3565b602060405180830381855afa158015611b8d573d5f803e3d5ffd5b5050506040513d601f19601f82011682018060405250810190611bb091906124fe565b60408051602081019390935282015260600160408051601f1981840301815290829052611bdc916124e3565b602060405180830381855afa158015611bf7573d5f803e3d5ffd5b5050506040513d601f19601f8201168201806040525081019061063291906124fe565b5f806001600160401b037f0000000000000000000000000000000000000000000000000000000000000000811690841610611c75577f0000000000000000000000000000000000000000000000000000000000000000611a50565b507f0000000000000000000000000000000000000000000000000000000000000000610ed48185611d2c565b5f6106328260600151611878565b5f611cba8383610c54565b156116d4575f838152602081815260408083206001600160a01b0386168085529252808320805460ff1916905551339286917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a4506001610632565b5f610c4d836001600160a01b038416611f42565b5f80611d388460081c90565b90505f611d448561202c565b90508084611d528285612630565b611d5c9190612606565b10611d7a57604051631390f2a160e01b815260040160405180910390fd5b611d95611d878584612606565b611d9087612044565b61204b565b95945050505050565b5f80611daa8460081c90565b90505f611db78460081c90565b90505f611dc383612082565b90505f611dcf83612082565b905060f881611ddf846001612606565b611de99190612606565b1115611e0857604051631390f2a160e01b815260040160405180910390fd5b6114dc84821b6001831b851817611d9088612044565b5f825f018281548110611e3357611e3361242b565b905f5260205f200154905092915050565b611e6d7fe8b012900cb200ee5dfc3b895a32791b67d12891b09f117814f167a237783a02829055565b5f198103611ead576040515f1981527f32fb7c9891bc4f963c7de9f1186d2a7755c7d6e9f4604dabe1d8bb3027c2f49e906020015b60405180910390a150565b7f32fb7c9891bc4f963c7de9f1186d2a7755c7d6e9f4604dabe1d8bb3027c2f49e611ed84283612643565b604051908152602001611ea2565b5f8181526001830160205260408120546116d457508154600181810184555f848152602080822090930184905584548482528286019093526040902091909155610632565b5f81611f37575f610632565b600160f81b92915050565b5f818152600183016020526040812054801561201c575f611f64600183612643565b85549091505f90611f7790600190612643565b9050808214611fd6575f865f018281548110611f9557611f9561242b565b905f5260205f200154905080875f018481548110611fb557611fb561242b565b5f918252602080832090910192909255918252600188019052604090208390555b8554869080611fe757611fe7612656565b600190038181905f5260205f20015f90559055856001015f8681526020019081526020015f205f905560019350505050610632565b5f915050610632565b5092915050565b5f61203682612044565b60ff166001901b9050919050565b5f81610632565b5f6001600160f81b0383111561207457604051631390f2a160e01b815260040160405180910390fd5b5060ff1660089190911b1790565b7f0706060506020504060203020504030106050205030304010505030400000000601f6f8421084210842108cc6318c6db6d54be831560081b6fffffffffffffffffffffffffffffffff851160071b1784811c6001600160401b031060061b1784811c63ffffffff1060051b1784811c61ffff1060041b1784811c60ff1060031b1793841c1c161a1790565b5f6020828403121561211e575f80fd5b81356001600160e01b031981168114610c4d575f80fd5b5f60208284031215612145575f80fd5b5035919050565b5f806040838503121561215d575f80fd5b8235915060208301356001600160a01b038116811461217a575f80fd5b809150509250929050565b5f60c08284031215612195575f80fd5b50919050565b5f6101a08284031215612195575f80fd5b5f805f8061012085870312156121c0575f80fd5b6121ca8686612185565b935060c08501356001600160401b038111156121e4575f80fd5b6121f08782880161219b565b949794965050505060e0830135926101000135919050565b5f805f805f610140868803121561221d575f80fd5b6122278787612185565b945060c08601356001600160401b0380821115612242575f80fd5b61224e89838a01612185565b955060e0880135915080821115612263575f80fd5b506122708882890161219b565b95989497509495610100810135955061012001359392505050565b5f806040838503121561229c575f80fd5b50508035926020909101359150565b6001600160401b038116811461066a575f80fd5b5f602082840312156122cf575f80fd5b8135610c4d816122ab565b634e487b7160e01b5f52604160045260245ffd5b5f60a082840312156122fe575f80fd5b60405160a081018181106001600160401b0382111715612320576123206122da565b604052823561232e816122ab565b8152602083013561233e816122ab565b806020830152506040830135604082015260608301356060820152608083013560808201528091505092915050565b5f5b8381101561238757818101518382015260200161236f565b50505f910152565b5f6020828403121561239f575f80fd5b81516001600160401b03808211156123b5575f80fd5b818401915084601f8301126123c8575f80fd5b8151818111156123da576123da6122da565b604051601f8201601f19908116603f01168101908382118183101715612402576124026122da565b8160405282815287602084870101111561241a575f80fd5b6114dc83602083016020880161236d565b634e487b7160e01b5f52603260045260245ffd5b602080825282518282018190525f919060409081850190868401855b8281101561248a578151805185528681015187860152850151858501526060909301929085019060010161245b565b5091979650505050505050565b5f808335601e198436030181126124ac575f80fd5b8301803591506001600160401b038211156124c5575f80fd5b6020019150600581901b36038213156124dc575f80fd5b9250929050565b5f82516124f481846020870161236d565b9190910192915050565b5f6020828403121561250e575f80fd5b5051919050565b5f60208284031215612525575f80fd5b81358015158114610c4d575f80fd5b5f60208284031215612544575f80fd5b813560ff81168114610c4d575f80fd5b634e487b7160e01b5f52601160045260245ffd5b6001600160401b0382811682821603908082111561202557612025612554565b634e487b7160e01b5f52601260045260245ffd5b5f6001600160401b03808416806125b5576125b5612588565b92169190910492915050565b5f6001600160401b03808416806125da576125da612588565b92169190910692915050565b6001600160401b0381811683821601908082111561202557612025612554565b8082018082111561063257610632612554565b808202811582820484141761063257610632612554565b5f8261263e5761263e612588565b500690565b8181038181111561063257610632612554565b634e487b7160e01b5f52603160045260245ffdfea164736f6c6343000818000a0000000000000000000000004473dcddbf77679a643bdb654dbd86d67f8d32f200000000000000000000000079cef36d84743222f37765204bec41e92a93e59d00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000161c004000000000000000000000000000000000000000000000000000000000161c00400000000000000000000000000000000000000000000000000960000000000280000000000000000000000000000000000000000000000000096000000000028000000000000000000000000000000000000000000000000000000b600000018000000000000000000000000000000000000000000000000000000b600000018000000000000000000000000000000000000000000000000000000000040000d000000000000000000000000000000000000000000000000000000000040000d0000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008c92472e51efcf126f5bdbc39d7023b95c746c95

Deployed Bytecode

0x608060405234801561000f575f80fd5b50600436106101fd575f3560e01c8063589ff76c11610114578063a217fddf116100a9578063d461395311610079578063d461395314610573578063d547741f1461059a578063da30e279146105ad578063e9235bc7146105d4578063f3f449c7146105fb575f80fd5b8063a217fddf14610549578063a302ee3814610550578063b187bd2614610558578063ca15c87314610560575f80fd5b80638d0f1fc9116100e45780638d0f1fc9146104d55780638f60eab9146104fc5780639010d07c1461052357806391d1485414610536575f80fd5b8063589ff76c1461046c5780635922977b1461047457806376e2128d1461048757806382bcd3a0146104ae575f80fd5b80632de03aa111610195578063389ed26711610165578063389ed2671461039e5780633a5e31fe146103c557806349939d18146103ec578063562d7d671461042b57806356d7e8fd14610452575f80fd5b80632de03aa11461033e5780632f2ff15d14610365578063305c24eb1461037857806336568abe1461038b575f80fd5b806316e08ca1116101d057806316e08ca1146102a7578063248a9ca3146102ce57806325256d98146102f05780632601d3c714610317575f80fd5b806301ffc9a71461020157806303d9d98214610229578063046f7da21461025e578063094d3a3414610268575b5f80fd5b61021461020f36600461210e565b61060e565b60405190151581526020015b60405180910390f35b6102507f000000000000000000000000000000000000000000000000000000000161c00481565b604051908152602001610220565b610266610638565b005b61028f7f00000000000000000000000079cef36d84743222f37765204bec41e92a93e59d81565b6040516001600160a01b039091168152602001610220565b6102507f000000000000000000000000000000000000000000000000000000000040000d81565b6102506102dc366004612135565b5f9081526020819052604090206001015490565b6102507f000000000000000000000000000000000000000000000000000000b60000001881565b61028f7f0000000000000000000000004473dcddbf77679a643bdb654dbd86d67f8d32f281565b6102507f2fc10cc8ae19568712f7a176fb4978616a610650813c9d05326c34abb62749c781565b61026661037336600461214c565b61066d565b6102666103863660046121ac565b610697565b61026661039936600461214c565b610930565b6102507f139c2898040ef16910dc9f44dc697df79363da767d8bc92f2e310312b816e46d81565b6102507f000000000000000000000000000000000000000000000000009600000000002881565b6104137f000000000000000000000000000000000000000000000000000000000000200081565b6040516001600160401b039091168152602001610220565b6102507f000000000000000000000000000000000000000000000000009600000000002881565b61028f720f3df6d732807ef1319fb7b8bb8522d0beac0281565b610250610968565b610266610482366004612208565b610996565b6104137f000000000000000000000000000000000000000000000000000000000001000081565b6102507f000000000000000000000000000000000000000000000000000000000040000d81565b6104137f000000000000000000000000000000000000000000000000000000000000000081565b6104137f000000000000000000000000000000000000000000000000000000000001000081565b61028f61053136600461228b565b610c36565b61021461054436600461214c565b610c54565b6102505f81565b6102505f1981565b610214610c7c565b61025061056e366004612135565b610cac565b6102507f000000000000000000000000000000000000000000000000000000000161c00481565b6102666105a836600461214c565b610cc2565b6104137f000000000000000000000000000000000000000000000000000000000000002081565b6102507f000000000000000000000000000000000000000000000000000000b60000001881565b610266610609366004612135565b610ce6565b5f6001600160e01b03198216635a05180f60e01b1480610632575061063282610d1d565b92915050565b7f2fc10cc8ae19568712f7a176fb4978616a610650813c9d05326c34abb62749c761066281610d51565b61066a610d5b565b50565b5f8281526020819052604090206001015461068781610d51565b6106918383610db0565b50505050565b61069f610de3565b6106e06106af60208601866122bf565b6001600160401b037f0000000000000000000000000000000000000000000000000000000000010000811691161090565b1561071c576106f260208501856122bf565b604051630a303f9760e31b81526001600160401b0390911660048201526024015b60405180910390fd5b5f61073561073060c0870160a088016122bf565b610e0b565b905061074e610749368790038701876122ee565b610edc565b811461076d576040516308c9b65f60e31b815260040160405180910390fd5b50604051632cf12e0960e11b81526004810183905260248101829052600160448201525f907f00000000000000000000000079cef36d84743222f37765204bec41e92a93e59d6001600160a01b0316906359e25c12906064015f60405180830381865afa1580156107e0573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610807919081019061238f565b90505f6108268561081b60208901896122bf565b606089013585610fb7565b6040805160018082528183019092529192505f9190816020015b61086160405180606001604052805f81526020015f81526020015f81525090565b815260200190600190039081610840579050509050604051806060016040528086815260200185815260200183815250815f815181106108a3576108a361242b565b6020908102919091010152604051639c963aef60e01b81526001600160a01b037f00000000000000000000000079cef36d84743222f37765204bec41e92a93e59d1690639c963aef906108fa90849060040161243f565b5f604051808303815f87803b158015610911575f80fd5b505af1158015610923573d5f803e3d5ffd5b5050505050505050505050565b6001600160a01b03811633146109595760405163334bd91960e11b815260040160405180910390fd5b6109638282611272565b505050565b5f6109917fe8b012900cb200ee5dfc3b895a32791b67d12891b09f117814f167a237783a025490565b905090565b61099e610de3565b6109ae6106af60208701876122bf565b156109c0576106f260208601866122bf565b6109d06106af60208601866122bf565b156109e2576106f260208501856122bf565b5f6109f661073060c0880160a089016122bf565b90505f610a0b610749368990038901896122ee565b9050808214610a2d576040516308c9b65f60e31b815260040160405180910390fd5b50610a7e9050610a4060a0860186612497565b6060880135610a57610749368a90038a018a6122ee565b610a79610a6760208c018c6122bf565b610a7460208c018c6122bf565b61129d565b6114e7565b604051632cf12e0960e11b81526004810183905260248101829052600160448201525f907f00000000000000000000000079cef36d84743222f37765204bec41e92a93e59d6001600160a01b0316906359e25c12906064015f60405180830381865afa158015610af0573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610b17919081019061238f565b90505f610b2b8561081b60208901896122bf565b6040805160018082528183019092529192505f9190816020015b610b6660405180606001604052805f81526020015f81526020015f81525090565b815260200190600190039081610b45579050509050604051806060016040528086815260200185815260200183815250815f81518110610ba857610ba861242b565b6020908102919091010152604051639c963aef60e01b81526001600160a01b037f00000000000000000000000079cef36d84743222f37765204bec41e92a93e59d1690639c963aef90610bff90849060040161243f565b5f604051808303815f87803b158015610c16575f80fd5b505af1158015610c28573d5f803e3d5ffd5b505050505050505050505050565b5f828152600160205260408120610c4d908361158b565b9392505050565b5f918252602082815260408084206001600160a01b0393909316845291905290205460ff1690565b5f610ca57fe8b012900cb200ee5dfc3b895a32791b67d12891b09f117814f167a237783a025490565b4210905090565b5f81815260016020526040812061063290611596565b5f82815260208190526040902060010154610cdc81610d51565b6106918383611272565b7f139c2898040ef16910dc9f44dc697df79363da767d8bc92f2e310312b816e46d610d1081610d51565b610d198261159f565b5050565b5f6001600160e01b03198216637965db0b60e01b148061063257506301ffc9a760e01b6001600160e01b0319831614610632565b61066a81336115ee565b610d63611627565b427fe8b012900cb200ee5dfc3b895a32791b67d12891b09f117814f167a237783a02556040517f62451d457bc659158be6e6247f56ec1df424a5c7597f71c20c2bc44e0965c8f9905f90a1565b5f80610dbc848461164c565b90508015610c4d575f848152600160205260409020610ddb90846116db565b509392505050565b610deb610c7c565b15610e0957604051630286f07360e31b815260040160405180910390fd5b565b604080516001600160401b03831660208201525f9182918291720f3df6d732807ef1319fb7b8bb8522d0beac02910160408051601f1981840301815290829052610e54916124e3565b5f60405180830381855afa9150503d805f8114610e8c576040519150601f19603f3d011682016040523d82523d5f602084013e610e91565b606091505b5091509150811580610ea257508051155b15610ec057604051633033b0ff60e01b815260040160405180910390fd5b80806020019051810190610ed491906124fe565b949350505050565b60408051610100810190915281515f9182918190610f02906001600160401b03166116ef565b8152602001610f1d85602001516001600160401b03166116ef565b81526020018460400151815260200184606001518152602001846080015181526020015f801b81526020015f801b81526020015f801b815250905060085b81828260051b81015b6040825f5e60205f60405f60025afa80610f7c575f80fd5b505f518352602083019250604082019150808210610f645750505060011c5f198101610fab575f519250610fb0565b610f5b565b5050919050565b5f60808501357f0000000000000000000000004473dcddbf77679a643bdb654dbd86d67f8d32f26001600160a01b039081169082161461100a57604051634261081360e11b815260040160405180910390fd5b61101c610160870161014088016122bf565b6001600160401b031661102e86611835565b101561104d57604051631adfa87360e01b815260040160405180910390fd5b61105d60e0870160c08801612515565b1580156110885750676f05b59d3b2000006110866110816080890160608a016122bf565b611878565b105b156110a65760405163653f0b3960e01b815260040160405180910390fd5b6040805161010081018252848152608088013560208201525f9181016110d260c08a0160a08b016122bf565b6001600160401b031681526020016110f060e08a0160c08b01612515565b151581526020016111086101008a0160e08b016122bf565b6001600160401b031681526020016111286101208a016101008b016122bf565b6001600160401b031681526020016111486101408a016101208b016122bf565b6001600160401b031681526020016111686101608a016101408b016122bf565b6001600160401b0316905290506111b2611186610180890189612497565b8761119085611890565b610a796111a360608e0160408f016122bf565b6001600160401b03168c6119d3565b5f60405180608001604052808960200160208101906111d191906122bf565b6001600160401b031681526020016111ef60608b0160408c016122bf565b6001600160401b031681526001600160a01b038516602082015260400161121c60808b0160608c016122bf565b6001600160401b03169052905061125d61123a6101608a018a612497565b8861124485611a5c565b610a7961125460208f018f612534565b60ff168d611c1a565b61126681611ca1565b98975050505050505050565b5f8061127e8484611caf565b90508015610c4d575f848152600160205260409020610ddb9084611d18565b5f806001600160401b037f0000000000000000000000000000000000000000000000000000000000000000166001600160401b0384166112dd9190612568565b90505f61130a7f00000000000000000000000000000000000000000000000000000000000020008361259c565b90505f6113407f00000000000000000000000000000000000000000000000000000000000020006001600160401b0387166125c1565b90505f7f0000000000000000000000000000000000000000000000000000000000002000611377836001600160401b038916612568565b61138191906125e6565b90506001600160401b0380881690821611156113b05760405163e2c15c0760e01b815260040160405180910390fd5b6001600160401b037f0000000000000000000000000000000000000000000000000000000000010000811690881610611409577f000000000000000000000000000000000000000000000000000000b60000001861142b565b7f000000000000000000000000000000000000000000000000000000b6000000185b9450611440856001600160401b038516611d2c565b94506114c76001600160401b037f000000000000000000000000000000000000000000000000000000000001000081169083161061149e577f000000000000000000000000000000000000000000000000000000000040000d6114c0565b7f000000000000000000000000000000000000000000000000000000000040000d5b8690611d9e565b94506114dc856001600160401b038416611d2c565b979650505050505050565b5f6114f28260081c90565b905084611506576309bde3395f526004601cfd5b8460051b8601865b6001831660051b8360011c93508361152d57635849603f5f526004601cfd5b85815281356020918218525f60408160025afa80611549575f80fd5b505f51945060200181811061150e5750506001811461156f57631b6661c35f526004601cfd5b838314611583576309bde3395f526004601cfd5b505050505050565b5f610c4d8383611e1e565b5f610632825490565b6115a7610de3565b805f036115c75760405163ad58bfc760e01b815260040160405180910390fd5b5f5f1982036115d857505f196115e5565b6115e28242612606565b90505b610d1981611e44565b6115f88282610c54565b610d195760405163e2517d3f60e01b81526001600160a01b038216600482015260248101839052604401610713565b61162f610c7c565b610e095760405163b047186b60e01b815260040160405180910390fd5b5f6116578383610c54565b6116d4575f838152602081815260408083206001600160a01b03861684529091529020805460ff1916600117905561168c3390565b6001600160a01b0316826001600160a01b0316847f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a4506001610632565b505f610632565b5f610c4d836001600160a01b038416611ee6565b5f6008827eff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff16901b6008837fff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff0016901c1791506010827dffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff16901b6010837fffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff000016901c1791506020827bffffffff00000000ffffffff00000000ffffffff00000000ffffffff16901b6020837fffffffff00000000ffffffff00000000ffffffff00000000ffffffff0000000016901c17915060408277ffffffffffffffff0000000000000000ffffffffffffffff16901b60408377ffffffffffffffff0000000000000000ffffffffffffffff1916901c179150608082901b608083901c179150815f1b9050919050565b5f6118697f00000000000000000000000000000000000000000000000000000000000000206001600160401b03841661259c565b6001600160401b031692915050565b5f6106326001600160401b038316633b9aca00612619565b80515f908190603060208201835e506010606060305e60205f60405f60025afa806118b9575f80fd5b505f5190505f604051806101000160405280838152602001856020015181526020016118f186604001516001600160401b03166116ef565b81526020016119038660600151611f2b565b815260200161191e86608001516001600160401b03166116ef565b81526020016119398660a001516001600160401b03166116ef565b81526020016119548660c001516001600160401b03166116ef565b815260200161196f8660e001516001600160401b03166116ef565b9052905060085b81828260051b81015b6040825f5e60205f60405f60025afa80611997575f80fd5b505f51835260208301925060408201915080821061197f5750505060011c5f1981016119c6575f5193506119cb565b611976565b505050919050565b5f806001600160401b037f0000000000000000000000000000000000000000000000000000000000010000811690841610611a2e577f0000000000000000000000000000000000000000000000000096000000000028611a50565b7f00000000000000000000000000000000000000000000000000960000000000285b9050610ed48185611d2c565b5f600280611a75845f01516001600160401b03166116ef565b611a8b85602001516001600160401b03166116ef565b60408051602081019390935282015260600160408051601f1981840301815290829052611ab7916124e3565b602060405180830381855afa158015611ad2573d5f803e3d5ffd5b5050506040513d601f19601f82011682018060405250810190611af591906124fe565b6002846040015160601b5f60a01b611b1987606001516001600160401b03166116ef565b604080516bffffffffffffffffffffffff19909416602085015273ffffffffffffffffffffffffffffffffffffffff1990921660348401529082015260600160408051601f1981840301815290829052611b72916124e3565b602060405180830381855afa158015611b8d573d5f803e3d5ffd5b5050506040513d601f19601f82011682018060405250810190611bb091906124fe565b60408051602081019390935282015260600160408051601f1981840301815290829052611bdc916124e3565b602060405180830381855afa158015611bf7573d5f803e3d5ffd5b5050506040513d601f19601f8201168201806040525081019061063291906124fe565b5f806001600160401b037f0000000000000000000000000000000000000000000000000000000000010000811690841610611c75577f000000000000000000000000000000000000000000000000000000000161c004611a50565b507f000000000000000000000000000000000000000000000000000000000161c004610ed48185611d2c565b5f6106328260600151611878565b5f611cba8383610c54565b156116d4575f838152602081815260408083206001600160a01b0386168085529252808320805460ff1916905551339286917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a4506001610632565b5f610c4d836001600160a01b038416611f42565b5f80611d388460081c90565b90505f611d448561202c565b90508084611d528285612630565b611d5c9190612606565b10611d7a57604051631390f2a160e01b815260040160405180910390fd5b611d95611d878584612606565b611d9087612044565b61204b565b95945050505050565b5f80611daa8460081c90565b90505f611db78460081c90565b90505f611dc383612082565b90505f611dcf83612082565b905060f881611ddf846001612606565b611de99190612606565b1115611e0857604051631390f2a160e01b815260040160405180910390fd5b6114dc84821b6001831b851817611d9088612044565b5f825f018281548110611e3357611e3361242b565b905f5260205f200154905092915050565b611e6d7fe8b012900cb200ee5dfc3b895a32791b67d12891b09f117814f167a237783a02829055565b5f198103611ead576040515f1981527f32fb7c9891bc4f963c7de9f1186d2a7755c7d6e9f4604dabe1d8bb3027c2f49e906020015b60405180910390a150565b7f32fb7c9891bc4f963c7de9f1186d2a7755c7d6e9f4604dabe1d8bb3027c2f49e611ed84283612643565b604051908152602001611ea2565b5f8181526001830160205260408120546116d457508154600181810184555f848152602080822090930184905584548482528286019093526040902091909155610632565b5f81611f37575f610632565b600160f81b92915050565b5f818152600183016020526040812054801561201c575f611f64600183612643565b85549091505f90611f7790600190612643565b9050808214611fd6575f865f018281548110611f9557611f9561242b565b905f5260205f200154905080875f018481548110611fb557611fb561242b565b5f918252602080832090910192909255918252600188019052604090208390555b8554869080611fe757611fe7612656565b600190038181905f5260205f20015f90559055856001015f8681526020019081526020015f205f905560019350505050610632565b5f915050610632565b5092915050565b5f61203682612044565b60ff166001901b9050919050565b5f81610632565b5f6001600160f81b0383111561207457604051631390f2a160e01b815260040160405180910390fd5b5060ff1660089190911b1790565b7f0706060506020504060203020504030106050205030304010505030400000000601f6f8421084210842108cc6318c6db6d54be831560081b6fffffffffffffffffffffffffffffffff851160071b1784811c6001600160401b031060061b1784811c63ffffffff1060051b1784811c61ffff1060041b1784811c60ff1060031b1793841c1c161a1790565b5f6020828403121561211e575f80fd5b81356001600160e01b031981168114610c4d575f80fd5b5f60208284031215612145575f80fd5b5035919050565b5f806040838503121561215d575f80fd5b8235915060208301356001600160a01b038116811461217a575f80fd5b809150509250929050565b5f60c08284031215612195575f80fd5b50919050565b5f6101a08284031215612195575f80fd5b5f805f8061012085870312156121c0575f80fd5b6121ca8686612185565b935060c08501356001600160401b038111156121e4575f80fd5b6121f08782880161219b565b949794965050505060e0830135926101000135919050565b5f805f805f610140868803121561221d575f80fd5b6122278787612185565b945060c08601356001600160401b0380821115612242575f80fd5b61224e89838a01612185565b955060e0880135915080821115612263575f80fd5b506122708882890161219b565b95989497509495610100810135955061012001359392505050565b5f806040838503121561229c575f80fd5b50508035926020909101359150565b6001600160401b038116811461066a575f80fd5b5f602082840312156122cf575f80fd5b8135610c4d816122ab565b634e487b7160e01b5f52604160045260245ffd5b5f60a082840312156122fe575f80fd5b60405160a081018181106001600160401b0382111715612320576123206122da565b604052823561232e816122ab565b8152602083013561233e816122ab565b806020830152506040830135604082015260608301356060820152608083013560808201528091505092915050565b5f5b8381101561238757818101518382015260200161236f565b50505f910152565b5f6020828403121561239f575f80fd5b81516001600160401b03808211156123b5575f80fd5b818401915084601f8301126123c8575f80fd5b8151818111156123da576123da6122da565b604051601f8201601f19908116603f01168101908382118183101715612402576124026122da565b8160405282815287602084870101111561241a575f80fd5b6114dc83602083016020880161236d565b634e487b7160e01b5f52603260045260245ffd5b602080825282518282018190525f919060409081850190868401855b8281101561248a578151805185528681015187860152850151858501526060909301929085019060010161245b565b5091979650505050505050565b5f808335601e198436030181126124ac575f80fd5b8301803591506001600160401b038211156124c5575f80fd5b6020019150600581901b36038213156124dc575f80fd5b9250929050565b5f82516124f481846020870161236d565b9190910192915050565b5f6020828403121561250e575f80fd5b5051919050565b5f60208284031215612525575f80fd5b81358015158114610c4d575f80fd5b5f60208284031215612544575f80fd5b813560ff81168114610c4d575f80fd5b634e487b7160e01b5f52601160045260245ffd5b6001600160401b0382811682821603908082111561202557612025612554565b634e487b7160e01b5f52601260045260245ffd5b5f6001600160401b03808416806125b5576125b5612588565b92169190910492915050565b5f6001600160401b03808416806125da576125da612588565b92169190910692915050565b6001600160401b0381811683821601908082111561202557612025612554565b8082018082111561063257610632612554565b808202811582820484141761063257610632612554565b5f8261263e5761263e612588565b500690565b8181038181111561063257610632612554565b634e487b7160e01b5f52603160045260245ffdfea164736f6c6343000818000a

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
0xA41BaD16f59963A3ee0Bb38DB2c3eCEdaDaDca7d
Loading...
Loading
Loading...
Loading
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.