Skip to content
Verified contractPartialGPL-3.0

CuratedDepositAllocator

Address0x691e8ba3dbf3e2e33a8c5641b15d4d24f3837f37
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.33

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.33+commit.64118f21
Language
solidity
Optimization
Yes, 150 runs
EVM version
osaka
License
GPL-3.0
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,385,524
Creation transaction
0xdce1809ef2…d6e71eebeb

47 files

src/lib/allocator/CuratedDepositAllocator.sol

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

pragma solidity 0.8.33;

import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { ICuratedModule } from "../../interfaces/ICuratedModule.sol";
import { IMetaRegistry } from "../../interfaces/IMetaRegistry.sol";
import { NodeOperator } from "../../interfaces/IBaseModule.sol";
import { ModuleLinearStorage } from "../../abstract/ModuleLinearStorage.sol";
import { AllocationState, DepositAllocatorGreedy } from "./DepositAllocatorGreedy.sol";
import { TransientUintUintMap, TransientUintUintMapLib } from "../TransientUintUintMapLib.sol";
import { ValidatorBalanceLimits } from "../ValidatorBalanceLimits.sol";
import { StakeTracker } from "../StakeTracker.sol";
import { TopUpAllocationLib } from "../TopUpAllocationLib.sol";

/// @notice Curated deposit allocation helpers.
/// @dev External deployment-linked library used by CuratedModule for bytecode savings.
///      Invariants assumed by this library:
///      - totalWithdrawnKeys <= totalDepositedKeys per operator.
///      - each operatorId < operatorsCount.
library CuratedDepositAllocator {
    struct DepositableOperatorsData {
        // Shared allocation arrays + totalCurrent — passed directly to the allocator.
        // During collection, alloc.sharesX96 temporarily stores raw weights
        // and is normalized in-place right before allocation.
        AllocationState alloc;
        uint256[] operatorIds; // Operator ids aligned with arrays above (compacted to operators included in allocation).
        uint256 count; // Number of operators included in allocation (filled entries in the arrays above).
        uint256 weightSum; // Sum of weights across eligible operators (for share calculation).
    }

    uint256 internal constant DEPOSIT_STEP = 1;
    uint256 internal constant TOP_UP_STEP = 2 ether;

    /// @notice Allocate new validator deposits across curated operators.
    /// @dev Input preparation and iteration behavior:
    ///      - Only operators with capacity > 0 and non-zero allocation weight are included.
    ///      - Current amounts are derived from deposited minus withdrawn keys (active keys).
    ///      - Operators that hit their capacity here will have capacity == 0 next call and
    ///        will be excluded; remaining operators’ shares increase.
    /// @dev Returns compact arrays containing only operators with non-zero allocations.
    /// @param nodeOperators Node operator storage mapping from the module.
    /// @param operatorsCount Total operators count in the module.
    /// @param depositsCount Number of validator deposits to allocate.
    /// @return allocated Number of deposits actually allocated.
    /// @return operatorIds Operator ids for allocated operators.
    /// @return allocations Per-operator allocations aligned to operatorIds.
    function allocateInitialDeposits(
        mapping(uint256 => NodeOperator) storage nodeOperators,
        uint256 operatorsCount,
        uint256 depositsCount
    ) external view returns (uint256 allocated, uint256[] memory operatorIds, uint256[] memory allocations) {
        if (depositsCount == 0) return (allocated, operatorIds, allocations);

        DepositableOperatorsData memory data = _collectDepositableOperatorsData(nodeOperators, operatorsCount);

        (allocated, allocations) = _computeAllocations({
            operatorsData: data,
            step: DEPOSIT_STEP,
            allocationAmount: depositsCount
        });

        (operatorIds, allocations) = _compactAllocations(data.operatorIds, allocations, data.count);
    }

    /// @dev Returns operator-level top-up allocations for the provided operators.
    ///      - Duplicated operator ids are not expected (caller guarantees uniqueness).
    ///      - Only operators with allocation enabled, non-zero allocation weight and usable top-up capacity are included.
    ///      - Shares are computed across all eligible operators in the module
    ///        (allocation enabled, non-zero weight, non-zero quantized top-up capacity),
    ///        so a subset cannot bias its share by omitting other eligible operators.
    ///      - Per-operator capacity is computed as:
    ///        `(active_validators * 2048 ETH) - current_operator_balance`, floored at zero.
    ///      - `current_operator_balance` here is the module's tracked stake view, not a live decrementing oracle value:
    ///        active balance decreases are intentionally reflected later via withdrawal reporting.
    /// @param $ Base module storage pointer.
    /// @param allocationAmount Total top-up amount in wei to allocate.
    /// @param operatorIds Unique operator ids to include in allocation.
    /// @return allocated Total allocated amount in wei.
    /// @return allocatedOperatorIds Operator ids for allocated operators.
    /// @return allocations Per-operator allocations aligned to allocatedOperatorIds.
    function allocateTopUps(
        ModuleLinearStorage.BaseModuleStorage storage $,
        uint256 allocationAmount,
        uint256[] calldata operatorIds
    ) external view returns (uint256 allocated, uint256[] memory allocatedOperatorIds, uint256[] memory allocations) {
        uint256[] memory operatorIdsCopy = operatorIds;
        return _allocateTopUps($, allocationAmount, operatorIdsCopy);
    }

    /// @dev Allocate top-ups across unique operators and immediately distribute them to keys.
    ///      - Raw operator ids may contain duplicates; they are deduplicated before operator-level allocation
    ///        to avoid overweighting operators that appear on multiple requested keys.
    ///      - Shares are computed across all eligible operators in the module
    ///        (allocation enabled, non-zero weight, non-zero quantized top-up capacity),
    ///        so a subset cannot bias its share by omitting other eligible operators.
    ///      - Per-operator capacity is computed as:
    ///        `(active_validators * 2048 ETH) - current_operator_balance`, floored at zero.
    ///      - `current_operator_balance` is intentionally based on tracked stake that preserves prior observed highs
    ///        until withdrawal settlement, so active slashing/leakage is accounted when penalties are finalized.
    ///      - Per-key top-up limits are not used as caps for operator-level allocation; they are
    ///        applied during key-level distribution and may leave unallocated remainder.
    function allocateAndDistributeTopUps(
        ModuleLinearStorage.BaseModuleStorage storage $,
        uint256 allocationAmount,
        uint256[] calldata operatorIds,
        uint256[] calldata topUpLimits
    ) external returns (uint256[] memory allocations) {
        uint256[] memory allocatedOperatorIds;
        uint256[] memory uniqueOperatorIds = _uniqueOperatorIds(operatorIds);
        uint256[] memory remainingOperatorAllocations;
        (, allocatedOperatorIds, remainingOperatorAllocations) = _allocateTopUps(
            $,
            allocationAmount,
            uniqueOperatorIds
        );
        if (allocatedOperatorIds.length == 0) return new uint256[](operatorIds.length);
        return
            _distributeAllocationsWithinLimits({
                operatorIds: operatorIds,
                topUpLimits: topUpLimits,
                allocatedOperatorIds: allocatedOperatorIds,
                remainingOperatorAllocations: remainingOperatorAllocations
            });
    }

    function _uniqueOperatorIds(uint256[] calldata operatorIds) private returns (uint256[] memory uniqueOperatorIds) {
        uniqueOperatorIds = new uint256[](operatorIds.length);
        TransientUintUintMap seen = TransientUintUintMapLib.create();
        uint256 count;
        for (uint256 i; i < operatorIds.length; ++i) {
            uint256 operatorId = operatorIds[i];
            if (seen.get(operatorId) != 0) continue;
            seen.set(operatorId, 1);
            uniqueOperatorIds[count] = operatorId;
            ++count;
        }

        if (count != operatorIds.length) {
            assembly ("memory-safe") {
                mstore(uniqueOperatorIds, count)
            }
        }
    }

    function _allocateTopUps(
        ModuleLinearStorage.BaseModuleStorage storage $,
        uint256 allocationAmount,
        uint256[] memory operatorIds
    ) private view returns (uint256 allocated, uint256[] memory allocatedOperatorIds, uint256[] memory allocations) {
        DepositableOperatorsData memory data = _collectTopUpEligibleOperatorsData($, operatorIds);
        if (data.count == 0) return (0, new uint256[](0), new uint256[](0));

        uint256[] memory eligibleAllocations;
        (allocated, eligibleAllocations) = _computeAllocations({
            operatorsData: data,
            step: TOP_UP_STEP,
            allocationAmount: allocationAmount
        });

        (allocatedOperatorIds, allocations) = _compactAllocations(data.operatorIds, eligibleAllocations, data.count);
    }

    /// @dev Collect eligible operators for deposit allocation.
    ///      Filters out zero capacity and zero-weight operators.
    function _collectDepositableOperatorsData(
        mapping(uint256 => NodeOperator) storage nodeOperators,
        uint256 operatorsCount
    ) private view returns (DepositableOperatorsData memory data) {
        data.alloc.sharesX96 = new uint256[](operatorsCount);
        data.alloc.currents = new uint256[](operatorsCount);
        data.alloc.capacities = new uint256[](operatorsCount);
        data.operatorIds = new uint256[](operatorsCount);

        IMetaRegistry metaRegistry = ICuratedModule(address(this)).META_REGISTRY();

        uint256 eligibleCount;
        for (uint256 i; i < operatorsCount; ++i) {
            NodeOperator storage no = nodeOperators[i];
            uint256 capacity = no.depositableValidatorsCount;
            if (capacity == 0) continue;

            (uint256 weight, uint256 externalStake) = metaRegistry.getNodeOperatorWeightAndExternalStake(i);
            if (weight == 0) continue;

            // NOTE: To determine the count of validators a node operator would have in the module we calculate
            // allocation for, we divide the external stake by the maximum stake a validator might have in this
            // module. Since the CuratedModule supports 0x02 validators, the maximum value is MAX_EFFECTIVE_BALANCE.
            unchecked {
                uint256 current = no.totalDepositedKeys - no.totalWithdrawnKeys;
                if (externalStake > 0) current += externalStake / ValidatorBalanceLimits.MAX_EFFECTIVE_BALANCE;

                data.alloc.sharesX96[eligibleCount] = weight;
                data.alloc.currents[eligibleCount] = current;
                data.alloc.capacities[eligibleCount] = capacity;
                data.operatorIds[eligibleCount] = i;
                data.weightSum += weight;
                data.alloc.totalCurrent += current;
                ++eligibleCount;
            }
        }

        data.count = eligibleCount;
        // Truncate arrays to the number of eligible operators collected.
        _truncateDepositable(data);
    }

    /// @dev Collect eligible operators for top-up allocation.
    ///      Duplicates in operatorIds are disallowed and must be filtered by the caller.
    function _collectTopUpEligibleOperatorsData(
        ModuleLinearStorage.BaseModuleStorage storage $,
        uint256[] memory operatorIds
    ) private view returns (DepositableOperatorsData memory data) {
        data.alloc.sharesX96 = new uint256[](operatorIds.length);
        data.alloc.currents = new uint256[](operatorIds.length);
        data.alloc.capacities = new uint256[](operatorIds.length);
        data.operatorIds = new uint256[](operatorIds.length);

        uint256[] memory weightsByOperatorId;
        uint256[] memory capacitiesByOperatorId;
        uint256[] memory currentStakeByOperatorId;
        (
            data.weightSum,
            data.alloc.totalCurrent,
            weightsByOperatorId,
            capacitiesByOperatorId,
            currentStakeByOperatorId
        ) = _collectTopUpGlobalBaseline($);

        uint256 eligibleCount;
        for (uint256 i; i < operatorIds.length; ++i) {
            uint256 operatorId = operatorIds[i];

            // Collect only requested operators; allocation still uses the global share baseline.
            uint256 capacity = capacitiesByOperatorId[operatorId];
            if (capacity == 0) continue;

            uint256 weight = weightsByOperatorId[operatorId];
            if (weight == 0) continue;

            data.alloc.sharesX96[eligibleCount] = weight;
            data.alloc.currents[eligibleCount] = currentStakeByOperatorId[operatorId];
            data.alloc.capacities[eligibleCount] = capacity;
            data.operatorIds[eligibleCount] = operatorId;
            ++eligibleCount;
        }

        data.count = eligibleCount;
        // Truncate arrays to the number of eligible operators collected.
        _truncateDepositable(data);
    }

    function _collectTopUpGlobalBaseline(
        ModuleLinearStorage.BaseModuleStorage storage $
    )
        private
        view
        returns (
            uint256 weightSum,
            uint256 totalCurrent,
            uint256[] memory weightsByOperatorId,
            uint256[] memory capacitiesByOperatorId,
            uint256[] memory currentStakeByOperatorId
        )
    {
        uint256 operatorsCount = $.nodeOperatorsCount;
        weightsByOperatorId = new uint256[](operatorsCount);
        capacitiesByOperatorId = new uint256[](operatorsCount);
        currentStakeByOperatorId = new uint256[](operatorsCount);

        IMetaRegistry metaRegistry = ICuratedModule(address(this)).META_REGISTRY();

        // Build the global share baseline across operators with allocation enabled, non-zero weight and usable capacity.
        for (uint256 i; i < operatorsCount; ++i) {
            if (!TopUpAllocationLib.isEnabled(i)) continue;

            uint256 balance = StakeTracker.getOperatorBalance($, i);
            uint256 capacity = quantizeForTopUp(_topUpCapacity($.nodeOperators[i], balance));
            if (capacity == 0) continue;
            capacitiesByOperatorId[i] = capacity;

            (uint256 weight, uint256 externalStake) = metaRegistry.getNodeOperatorWeightAndExternalStake(i);
            if (weight == 0) continue;
            weightsByOperatorId[i] = weight;
            weightSum += weight;

            // NOTE: Ongoing consolidation might lower the `currentStake` relative to the balance observed on CL. This
            // is because external stake is decreased as soon as a validator is reported as exited, but the operator
            // balance tracked by the module changes only when the consolidation from the exited validator lands on the
            // target validator and the balance change proof is delivered via the Verifier.
            uint256 currentStake = balance + externalStake;
            currentStakeByOperatorId[i] = currentStake;
            totalCurrent += currentStake;
        }
    }

    /// @dev Maximum top-up capacity for an operator:
    ///      (active validators * 2048 ETH) - current balance, floored at zero.
    function _topUpCapacity(NodeOperator storage no, uint256 balanceWei) internal view returns (uint256 capacity) {
        unchecked {
            uint256 maxTotal = (no.totalDepositedKeys - no.totalWithdrawnKeys) *
                ValidatorBalanceLimits.MAX_EFFECTIVE_BALANCE;
            if (maxTotal > balanceWei) capacity = maxTotal - balanceWei;
        }
    }

    /// @notice Returns current deposit allocation targets for all operators.
    /// @dev Target = totalCurrent * operatorWeight / totalWeight (in validator count).
    ///      Includes operators regardless of depositable capacity for informational purposes.
    ///      Actual allocation recalculates shares only across operators with usable capacity,
    ///      so real per-operator amounts may differ from the targets shown here.
    ///      Arrays are indexed by operator id; zero-weight operators have zero values.
    /// @param nodeOperators Node operator storage mapping from the module.
    /// @param operatorsCount Total operators count in the module.
    /// @return currentValidators Current active validator count per operator.
    /// @return targetValidators Target validator count per operator.
    function getDepositAllocationTargets(
        mapping(uint256 => NodeOperator) storage nodeOperators,
        uint256 operatorsCount
    ) external view returns (uint256[] memory currentValidators, uint256[] memory targetValidators) {
        if (operatorsCount == 0) return (currentValidators, targetValidators);

        currentValidators = new uint256[](operatorsCount);
        targetValidators = new uint256[](operatorsCount);

        IMetaRegistry metaRegistry = ICuratedModule(address(this)).META_REGISTRY();

        uint256 weightSum;
        uint256 totalCurrent;
        for (uint256 i; i < operatorsCount; ++i) {
            NodeOperator storage no = nodeOperators[i];
            (uint256 weight, uint256 externalStake) = metaRegistry.getNodeOperatorWeightAndExternalStake(i);
            if (weight == 0) continue;

            unchecked {
                uint256 current = no.totalDepositedKeys - no.totalWithdrawnKeys;
                if (externalStake > 0) current += externalStake / ValidatorBalanceLimits.MAX_EFFECTIVE_BALANCE;

                currentValidators[i] = current;
                // Temporarily store raw weight in targetValidators; will be converted below.
                targetValidators[i] = weight;
                weightSum += weight;
                totalCurrent += current;
            }
        }

        if (weightSum == 0) return (currentValidators, targetValidators);

        for (uint256 i; i < operatorsCount; ++i) {
            if (targetValidators[i] == 0) continue;
            targetValidators[i] = Math.mulDiv(totalCurrent, targetValidators[i], weightSum);
        }
    }

    /// @notice Returns current top-up allocation targets for all operators.
    /// @dev Target = totalCurrent * operatorWeight / totalWeight (in wei).
    ///      Includes operators regardless of top-up capacity or whether allocation is enabled for informational purposes.
    ///      Actual allocation recalculates shares only across operators with allocation enabled and usable capacity,
    ///      so real per-operator amounts may differ from the targets shown here.
    ///      Arrays are indexed by operator id; zero-weight operators have zero values.
    /// @param $ Base module storage pointer.
    /// @return currentAllocations Current operator stake in wei.
    /// @return targetAllocations Target operator stake in wei.
    function getTopUpAllocationTargets(
        ModuleLinearStorage.BaseModuleStorage storage $
    ) external view returns (uint256[] memory currentAllocations, uint256[] memory targetAllocations) {
        uint256 operatorsCount = $.nodeOperatorsCount;
        if (operatorsCount == 0) return (currentAllocations, targetAllocations);

        currentAllocations = new uint256[](operatorsCount);
        targetAllocations = new uint256[](operatorsCount);

        IMetaRegistry metaRegistry = ICuratedModule(address(this)).META_REGISTRY();

        uint256 weightSum;
        uint256 totalCurrent;
        for (uint256 i; i < operatorsCount; ++i) {
            (uint256 weight, uint256 externalStake) = metaRegistry.getNodeOperatorWeightAndExternalStake(i);
            if (weight == 0) continue;

            uint256 currentStake = StakeTracker.getOperatorBalance($, i) + externalStake;
            currentAllocations[i] = currentStake;
            // Temporarily store raw weight in targetAllocations; will be converted below.
            targetAllocations[i] = weight;
            weightSum += weight;
            totalCurrent += currentStake;
        }

        if (weightSum == 0) return (currentAllocations, targetAllocations);

        for (uint256 i; i < operatorsCount; ++i) {
            if (targetAllocations[i] == 0) continue;
            targetAllocations[i] = Math.mulDiv(totalCurrent, targetAllocations[i], weightSum);
        }
    }

    /// @dev Quantizes a value down to the nearest multiple of TOP_UP_STEP.
    function quantizeForTopUp(uint256 value) internal pure returns (uint256) {
        return DepositAllocatorGreedy._quantize(value, TOP_UP_STEP);
    }

    function _distributeAllocationsWithinLimits(
        uint256[] calldata operatorIds,
        uint256[] calldata topUpLimits,
        uint256[] memory allocatedOperatorIds,
        uint256[] memory remainingOperatorAllocations
    ) private returns (uint256[] memory allocations) {
        allocations = new uint256[](operatorIds.length);
        TransientUintUintMap operatorIndexes = TransientUintUintMapLib.create();

        for (uint256 i; i < allocatedOperatorIds.length; ++i) {
            operatorIndexes.set(allocatedOperatorIds[i], i + 1);
        }

        unchecked {
            for (uint256 i; i < operatorIds.length; ++i) {
                uint256 allocationIndex = operatorIndexes.get(operatorIds[i]);
                if (allocationIndex == 0) continue;
                --allocationIndex;

                uint256 remaining = remainingOperatorAllocations[allocationIndex];
                if (remaining == 0) continue;

                uint256 limit = quantizeForTopUp(topUpLimits[i]);
                if (limit == 0) continue;

                uint256 amount = Math.min(remaining, limit);
                allocations[i] = amount;
                remainingOperatorAllocations[allocationIndex] = remaining - amount;
            }
        }
    }

    /// @dev Normalizes raw weights into X96 shares and runs the allocator in-memory.
    ///      Expects operatorsData arrays already filtered/truncated to eligible operators.
    function _computeAllocations(
        DepositableOperatorsData memory operatorsData,
        uint256 step,
        uint256 allocationAmount
    ) private pure returns (uint256 allocated, uint256[] memory allocations) {
        // allocationAmount > 0 and step > 0 are guaranteed by the callers.

        _normalizeWeightsToShares(operatorsData);

        (allocated, allocations) = DepositAllocatorGreedy._allocate(operatorsData.alloc, allocationAmount, step);
    }

    function _compactAllocations(
        uint256[] memory operatorIds,
        uint256[] memory eligibleAllocations,
        uint256 count
    ) private pure returns (uint256[] memory compactIds, uint256[] memory allocations) {
        compactIds = new uint256[](count);
        allocations = new uint256[](count);
        uint256 compactIndex;
        for (uint256 i; i < count; ++i) {
            uint256 allocation = eligibleAllocations[i];
            if (allocation == 0) continue;
            compactIds[compactIndex] = operatorIds[i];
            allocations[compactIndex] = allocation;
            ++compactIndex;
        }
        if (compactIndex != count) {
            assembly ("memory-safe") {
                mstore(compactIds, compactIndex)
                mstore(allocations, compactIndex)
            }
        }
    }

    /// @dev Converts raw weights in alloc.sharesX96 to X96-scaled shares in-place.
    function _normalizeWeightsToShares(DepositableOperatorsData memory data) private pure {
        uint256[] memory sharesX96 = data.alloc.sharesX96;
        for (uint256 i; i < sharesX96.length; ++i) {
            // NOTE: no zero-check here. Collectors filter out zero weights and truncate
            //       arrays to eligible node operators count, so sharesX96 entries are non-zero.
            sharesX96[i] = Math.mulDiv(
                sharesX96[i],
                DepositAllocatorGreedy.S_SCALE,
                // weightSum > 0 is guaranteed by the collectors for any non-empty input.
                data.weightSum
            );
        }
    }

    /// @dev Shrinks eligible arrays to the collected eligible count.
    function _truncateDepositable(DepositableOperatorsData memory data) private pure {
        uint256 count = data.count;
        if (count == data.alloc.sharesX96.length) return;
        uint256[] memory sharesX96 = data.alloc.sharesX96;
        uint256[] memory currents = data.alloc.currents;
        uint256[] memory capacities = data.alloc.capacities;
        uint256[] memory operatorIds = data.operatorIds;
        assembly ("memory-safe") {
            mstore(sharesX96, count)
            mstore(currents, count)
            mstore(capacities, count)
            mstore(operatorIds, count)
        }
    }
}

node_modules/@openzeppelin/contracts/access/IAccessControl.sol

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

pragma solidity >=0.8.4;

/**
 * @dev External interface of AccessControl declared to support ERC-165 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 to signal 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. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    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;
}

node_modules/@openzeppelin/contracts/access/extensions/IAccessControlEnumerable.sol

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

pragma solidity >=0.8.4;

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

/**
 * @dev External interface of AccessControlEnumerable declared to support ERC-165 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);
}

node_modules/@openzeppelin/contracts/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

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

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

node_modules/@openzeppelin/contracts/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

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

node_modules/@openzeppelin/contracts/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

import {IERC20} from "../token/ERC20/IERC20.sol";

node_modules/@openzeppelin/contracts/token/ERC1155/IERC1155.sol

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

pragma solidity >=0.6.2;

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

/**
 * @dev Required interface of an ERC-1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[ERC].
 */
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`.
     */
    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 zero address.
     */
    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 {IERC1155Receiver-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 {IERC1155Receiver-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;
}

node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol

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

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
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);
}

node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 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 {
    /**
     * @dev An operation with an ERC-20 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 Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    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 Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            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 silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

node_modules/@openzeppelin/contracts/token/ERC721/IERC721.sol

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

pragma solidity >=0.6.2;

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

/**
 * @dev Required interface of an ERC-721 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 ERC-721 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 ERC-721
     * 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);
}

node_modules/@openzeppelin/contracts/utils/Panic.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

node_modules/@openzeppelin/contracts/utils/SlotDerivation.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Library for computing storage (and transient storage) locations from namespaces and deriving slots
 * corresponding to standard patterns. The derivation method for array and mapping matches the storage layout used by
 * the solidity language / compiler.
 *
 * See https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays[Solidity docs for mappings and dynamic arrays.].
 *
 * Example usage:
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using StorageSlot for bytes32;
 *     using SlotDerivation for bytes32;
 *
 *     // Declare a namespace
 *     string private constant _NAMESPACE = "<namespace>"; // eg. OpenZeppelin.Slot
 *
 *     function setValueInNamespace(uint256 key, address newValue) internal {
 *         _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value = newValue;
 *     }
 *
 *     function getValueInNamespace(uint256 key) internal view returns (address) {
 *         return _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {StorageSlot}.
 *
 * NOTE: This library provides a way to manipulate storage locations in a non-standard way. Tooling for checking
 * upgrade safety will ignore the slots accessed through this library.
 *
 * _Available since v5.1._
 */
library SlotDerivation {
    /**
     * @dev Derive an ERC-7201 slot from a string (namespace).
     */
    function erc7201Slot(string memory namespace) internal pure returns (bytes32 slot) {
        assembly ("memory-safe") {
            mstore(0x00, sub(keccak256(add(namespace, 0x20), mload(namespace)), 1))
            slot := and(keccak256(0x00, 0x20), not(0xff))
        }
    }

    /**
     * @dev Add an offset to a slot to get the n-th element of a structure or an array.
     */
    function offset(bytes32 slot, uint256 pos) internal pure returns (bytes32 result) {
        unchecked {
            return bytes32(uint256(slot) + pos);
        }
    }

    /**
     * @dev Derive the location of the first element in an array from the slot where the length is stored.
     */
    function deriveArray(bytes32 slot) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, slot)
            result := keccak256(0x00, 0x20)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, address key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, and(key, shr(96, not(0))))
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bool key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, iszero(iszero(key)))
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bytes32 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, uint256 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, int256 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, string memory key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            let length := mload(key)
            let begin := add(key, 0x20)
            let end := add(begin, length)
            let cache := mload(end)
            mstore(end, slot)
            result := keccak256(begin, add(length, 0x20))
            mstore(end, cache)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bytes memory key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            let length := mload(key)
            let begin := add(key, 0x20)
            let end := add(begin, length)
            let cache := mload(end)
            mstore(end, slot)
            result := keccak256(begin, add(length, 0x20))
            mstore(end, cache)
        }
    }
}

node_modules/@openzeppelin/contracts/utils/TransientSlot.sol

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

pragma solidity ^0.8.24;

/**
 * @dev Library for reading and writing value-types to specific transient storage slots.
 *
 * Transient slots are often used to store temporary values that are removed after the current transaction.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 *  * Example reading and writing values using transient storage:
 * ```solidity
 * contract Lock {
 *     using TransientSlot for *;
 *
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
 *
 *     modifier locked() {
 *         require(!_LOCK_SLOT.asBoolean().tload());
 *
 *         _LOCK_SLOT.asBoolean().tstore(true);
 *         _;
 *         _LOCK_SLOT.asBoolean().tstore(false);
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library TransientSlot {
    /**
     * @dev UDVT that represents a slot holding an address.
     */
    type AddressSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a AddressSlot.
     */
    function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
        return AddressSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bool.
     */
    type BooleanSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a BooleanSlot.
     */
    function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
        return BooleanSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bytes32.
     */
    type Bytes32Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Bytes32Slot.
     */
    function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
        return Bytes32Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a uint256.
     */
    type Uint256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Uint256Slot.
     */
    function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
        return Uint256Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a int256.
     */
    type Int256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Int256Slot.
     */
    function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
        return Int256Slot.wrap(slot);
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(AddressSlot slot) internal view returns (address value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(AddressSlot slot, address value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(BooleanSlot slot) internal view returns (bool value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(BooleanSlot slot, bool value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Bytes32Slot slot, bytes32 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Uint256Slot slot) internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Uint256Slot slot, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Int256Slot slot) internal view returns (int256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Int256Slot slot, int256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }
}

node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol

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

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * 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[ERC 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);
}

node_modules/@openzeppelin/contracts/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from high into low.
            low |= high * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

node_modules/@openzeppelin/contracts/utils/math/SafeCast.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

src/abstract/ModuleLinearStorage.sol

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

pragma solidity 0.8.33;

import { NodeOperator } from "../interfaces/IBaseModule.sol";

import { DepositQueueLib } from "../lib/DepositQueueLib.sol";

abstract contract ModuleLinearStorage {
    /// @dev Linear storage layout of the module. All state lives in a single struct
    ///      accessed via `_baseStorage()` at slot 0.
    struct BaseModuleStorage {
        /// @dev Having this mapping here to preserve the current layout of the storage of the CSModule.
        /* 0 */ mapping(uint256 priority => DepositQueueLib.Queue queue) depositQueueByPriority;
        /// @dev Total number of withdrawn validators reported for the module.
        /* 1 */ uint256 totalWithdrawnValidators;
        /* 2 */ uint256 upToDateOperatorDepositInfoCount; /// XXX: the slot was used as a mapping in CSM v1 and v2.
        /* 3 */ mapping(uint256 noKeyIndexPacked => uint256) keyAllocatedBalance;
        /* 4 */ mapping(uint256 noKeyIndexPacked => uint256) keyConfirmedBalance;
        /* 5 */ uint256 nonce;
        /* 6 */ mapping(uint256 nodeOperatorId => NodeOperator) nodeOperators;
        /// @dev see KeyPointerLib.keyPointer function for details of noKeyIndexPacked structure
        /* 7 */ mapping(uint256 noKeyIndexPacked => bool) isValidatorWithdrawn;
        /* 8 */ mapping(uint256 noKeyIndexPacked => bool) isValidatorSlashed;
        /* 9 */ uint64 totalDepositedValidators;
        /* 9 */ uint64 totalExitedValidators;
        /* 9 */ uint64 depositableValidatorsCount;
        /* 9 */ uint64 nodeOperatorsCount;
        /* 10 */ mapping(uint256 nodeOperatorId => uint256 extraBalance) operatorBalances;
        /* 11 */ uint256 totalExtraStake;
    }

    function _baseStorage() internal pure returns (BaseModuleStorage storage $) {
        assembly ("memory-safe") {
            // ModuleLinearStorage starts at slot 0 in the current inheritance layout.
            $.slot := 0
        }
    }
}

src/interfaces/IAccounting.sol

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

pragma solidity 0.8.33;

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

import { IBondCore } from "./IBondCore.sol";
import { IBondCurve } from "./IBondCurve.sol";
import { IBondLock } from "./IBondLock.sol";
import { IFeeDistributor } from "./IFeeDistributor.sol";
import { IFeeSplits } from "./IFeeSplits.sol";
import { IBaseModule } from "./IBaseModule.sol";

interface IAccounting is IBondCore, IBondCurve, IBondLock, IFeeSplits, IAssetRecovererLib {
    struct PermitInput {
        uint256 value;
        uint256 deadline;
        uint8 v;
        bytes32 r;
        bytes32 s;
    }

    struct NodeOperatorBondInfo {
        uint256 currentBond;
        uint256 requiredBond;
        uint256 lockedBond;
        uint256 bondDebt;
        uint256 pendingSharesToSplit;
    }

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

    error SenderIsNotModule();
    error SenderIsNotEligible();
    error ZeroModuleAddress();
    error ZeroAdminAddress();
    error ZeroFeeDistributorAddress();
    error ZeroChargePenaltyRecipientAddress();
    error InvalidChargePenaltyRecipientAddress();
    error NodeOperatorDoesNotExist();
    error SameAddress();
    error InvalidBondLockNonce();

    function MANAGE_BOND_CURVES_ROLE() external view returns (bytes32);

    function SET_BOND_CURVE_ROLE() external view returns (bytes32);

    function MODULE() external view returns (IBaseModule);

    function FEE_DISTRIBUTOR() external view returns (IFeeDistributor);

    function chargePenaltyRecipient() external view returns (address);

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

    /// @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 Set fee splits for the given Node Operator
    /// @param nodeOperatorId ID of the Node Operator
    /// @param feeSplits Array of FeeSplit structs defining recipients and their shares in basis points
    ///                  Total shares must be <= 10_000 (100%). Remainder goes to the Node Operator's bond
    /// @param cumulativeFeeShares Cumulative fee stETH shares for the Node Operator. Optional
    /// @param rewardsProof Merkle proof of the rewards. Optional
    /// @dev FeeSplits can be updated either when there are no splits currently or when there are splits now,
    ///      provided all node operator rewards are distributed and split. It is possible to set splits while
    ///      there are undistributed node operator rewards and no splits are currently set.
    ///      This will result in all undistributed node operator rewards being split.
    ///      If a node operator has never received any node operator rewards, they can set initial splits.
    ///      However, further change will be possible only after getting and splitting the first rewards.
    function updateFeeSplits(
        uint256 nodeOperatorId,
        FeeSplit[] calldata feeSplits,
        uint256 cumulativeFeeShares,
        bytes32[] calldata rewardsProof
    ) 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 staking module might be required to ensure that the keys pointers are consistent.
    ///      Note that node operators might face unbonded keys due to changes to bond requirements.
    /// @param curveId Bond curve ID to update
    /// @param bondCurve Bond curve definition
    function updateBondCurve(uint256 curveId, BondCurveIntervalInput[] calldata bondCurve) external;

    /// @notice Set custom rewards claimer for the given Node Operator. This address will be able to claim rewards on behalf of the Node Operator.
    ///         The rewards will be transferred to the Node Operator's reward address as usual.
    /// @param nodeOperatorId ID of the Node Operator
    /// @param rewardsClaimer Address allowed to claim rewards on behalf of the Node Operator
    function setCustomRewardsClaimer(uint256 nodeOperatorId, address rewardsClaimer) external;

    /// @notice Get the custom rewards claimer for the given Node Operator. This address is allowed to claim rewards on behalf of the Node Operator.
    ///         The rewards are still transferred to the Node Operator's reward address as usual.
    /// @param nodeOperatorId ID of the Node Operator
    /// @return Address allowed to claim rewards on behalf of the Node Operator
    function getCustomRewardsClaimer(uint256 nodeOperatorId) external view returns (address);

    /// @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 for the given 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 `compensateLockedBond` 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 all bond-related info for the given Node Operator in one call
    /// @param nodeOperatorId ID of the Node Operator
    /// @return info Bond info containing current bond, required bond, locked bond,
    ///         bond debt, and pending shares to split
    function getNodeOperatorBondInfo(uint256 nodeOperatorId) external view returns (NodeOperatorBondInfo memory info);

    /// @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 staking module exclusively. Staking module 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 staking module exclusively. Staking module 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 staking module exclusively. Staking module 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 leaves.
    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 leaves.
    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 stETH 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 leaves.
    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 staking module exclusively
    /// @param nodeOperatorId ID of the Node Operator
    /// @param amount Amount to lock in ETH (stETH)
    function lockBond(uint256 nodeOperatorId, uint256 amount) external;

    /// @notice Release locked bond in ETH for the given Node Operator
    /// @dev Called by staking module exclusively
    /// @param nodeOperatorId ID of the Node Operator
    /// @param amount Amount to release in ETH (stETH)
    /// @return True if the bond was released, false if the lock was expired and bond was unlocked instead
    function releaseLockedBond(uint256 nodeOperatorId, uint256 amount) external returns (bool);

    /// @notice Unlock expired locked bond for the given Node Operator
    /// @param nodeOperatorId ID of the Node Operator
    function unlockExpiredLock(uint256 nodeOperatorId) external;

    /// @notice Settle locked bond ETH for the given Node Operator
    /// @dev Called by staking module exclusively
    /// @param nodeOperatorId ID of the Node Operator
    /// @param bondLockNonce Bond lock nonce
    /// @return amountSettled Amount settled in ETH (stETH)
    function settleLockedBond(uint256 nodeOperatorId, uint256 bondLockNonce) external returns (uint256 amountSettled);

    /// @notice Compensate locked bond ETH for the given Node Operator
    /// @dev Called by staking module exclusively
    /// @param nodeOperatorId ID of the Node Operator
    /// @return compensatedAmount Amount compensated in ETH (stETH)
    function compensateLockedBond(uint256 nodeOperatorId) external returns (uint256 compensatedAmount);

    /// @notice Set the bond curve for the given Node Operator
    /// @dev Updates depositable validators count in staking module 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)
    /// @return penaltyCovered True if the penalty was fully covered by bond burn, false otherwise
    function penalize(uint256 nodeOperatorId, uint256 amount) external returns (bool penaltyCovered);

    /// @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)
    /// @return Whether any shares were actually transferred
    function chargeFee(uint256 nodeOperatorId, uint256 amount) external returns (bool);

    /// @notice Pull fees (if proof provided) from FeeDistributor to the Node Operator's bond and split according to configured fee splits.
    /// @dev Reverts while Accounting is paused.
    ///      Previously reward pulling during pause was useful for emergency penalty handling.
    ///      Now penalties can create bond debt while paused, and later rewards can repay it after resume.
    ///      So this method is paused together with the rest of the reward-handling flows.
    /// @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 pullAndSplitFeeRewards(
        uint256 nodeOperatorId,
        uint256 cumulativeFeeShares,
        bytes32[] calldata rewardsProof
    ) external;
}

src/interfaces/IBaseModule.sol

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

pragma solidity 0.8.33;

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

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

import { IAccounting } from "./IAccounting.sol";
import { IExitPenalties } from "./IExitPenalties.sol";
import { ILidoLocator } from "./ILidoLocator.sol";
import { IParametersRegistry } from "./IParametersRegistry.sol";
import { IStakingModule } from "./IStakingModule.sol";
import { IStETH } from "./IStETH.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; // @dev no longer used, left for the storage layout compatibility
}

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

struct WithdrawnValidatorInfo {
    uint256 nodeOperatorId;
    // Index of the withdrawn key in the Node Operator's keys storage.
    uint256 keyIndex;
    // Balance to be used to calculate penalties. For a regular withdrawal of a validator it's the withdrawal amount.
    // For a slashed validator it's its balance before slashing if slashing penalty is provided explicitly, otherwise it's the balance after slashing to calculate penalty using a less precise on-chain fallback.
    // The balance will be used to scale incurred penalties and calculate penalties due to offline or slashing penalties via the shortcut mechanism.
    uint256 exitBalance;
    // Amount of ETH/stETH to penalize Node Operator due to slashing.
    uint256 slashingPenalty;
    // Whether the validator has been slashed.
    bool isSlashed;
}

/// @notice Base module interface for repository modules such as `ICSModule` and `ICuratedModule`.
interface IBaseModule is IStakingModule, IAccessControlEnumerable, IAssetRecovererLib {
    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 ValidatorWithdrawn(
        uint256 indexed nodeOperatorId,
        uint256 keyIndex,
        uint256 exitBalance,
        uint256 slashingPenalty,
        bytes pubkey
    );
    event TotalWithdrawnValidatorsRebuilt(uint256 totalWithdrawnValidators);
    event NodeOperatorBalanceUpdated(uint256 indexed operatorId, uint256 balanceWei);
    event ValidatorSlashingReported(uint256 indexed nodeOperatorId, uint256 keyIndex, bytes pubkey);
    event KeyAllocatedBalanceChanged(uint256 indexed nodeOperatorId, uint256 indexed keyIndex, uint256 newTotal);
    event KeyConfirmedBalanceChanged(uint256 indexed nodeOperatorId, uint256 indexed keyIndex, uint256 newBalance);
    event KeyRemovalChargeApplied(uint256 indexed nodeOperatorId);

    event GeneralDelayedPenaltyReported(
        uint256 indexed nodeOperatorId,
        bytes32 indexed penaltyType,
        uint256 amount,
        uint256 additionalFine,
        string details
    );
    event GeneralDelayedPenaltyCancelled(uint256 indexed nodeOperatorId, uint256 amount);
    event GeneralDelayedPenaltyCompensated(uint256 indexed nodeOperatorId, uint256 amount);
    event GeneralDelayedPenaltySettled(uint256 indexed nodeOperatorId, uint256 amount);
    event NodeOperatorDepositInfoFullyUpdated();
    event FullDepositInfoUpdateRequested();

    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 CannotAddKeys();
    error NodeOperatorDoesNotExist();
    error SenderIsNotEligible();
    error InvalidVetKeysPointer();
    error ZeroExitBalance();
    error SlashingPenaltyIsNotApplicable();
    error ValidatorSlashingAlreadyReported();
    error InvalidWithdrawnValidatorInfo();

    error InvalidAmount();
    error InvalidInput();
    error NotEnoughKeys();

    error KeysLimitExceeded();
    error SigningKeysInvalidOffset();
    error DepositableKeysWithUnsupportedWithdrawalCredentials();

    error ZeroLocatorAddress();
    error ZeroAccountingAddress();
    error ZeroExitPenaltiesAddress();
    error ZeroAdminAddress();
    error ZeroSenderAddress();
    error ZeroParametersRegistryAddress();
    error ZeroModuleType();
    error ZeroPenaltyType();
    error DepositInfoIsNotUpToDate();
    error UnreportableBalance();

    error InvalidManagerAddress();
    error InvalidRewardAddress();

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

    function STAKING_ROUTER_ROLE() external view returns (bytes32);

    function REPORT_GENERAL_DELAYED_PENALTY_ROLE() external view returns (bytes32);

    function SETTLE_GENERAL_DELAYED_PENALTY_ROLE() external view returns (bytes32);

    function VERIFIER_ROLE() external view returns (bytes32);

    function REPORT_REGULAR_WITHDRAWN_VALIDATORS_ROLE() external view returns (bytes32);

    function REPORT_SLASHED_WITHDRAWN_VALIDATORS_ROLE() external view returns (bytes32);

    function CREATE_NODE_OPERATOR_ROLE() external view returns (bytes32);

    function OPERATOR_ADDRESSES_ADMIN_ROLE() external view returns (bytes32);

    function LIDO_LOCATOR() external view returns (ILidoLocator);

    function STETH() external view returns (IStETH);

    function PARAMETERS_REGISTRY() external view returns (IParametersRegistry);

    function ACCOUNTING() external view returns (IAccounting);

    function EXIT_PENALTIES() external view returns (IExitPenalties);

    function FEE_DISTRIBUTOR() external view returns (address);

    /// @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
    /// @dev Any excess msg.value will be sent to the bond and can be claimed from there. This behaviour is intentional
    /// and protects users from key upload transaction front runs rendering the user transaction invalid due to changes
    /// in the required bond amount.
    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,
        IAccounting.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,
        IAccounting.PermitInput memory permit
    ) external;

    /// @notice Report general delayed penalty for the given Node Operator
    /// @notice Increases locked bond by `amount + additionalFine` for this report
    /// @param nodeOperatorId ID of the Node Operator
    /// @param penaltyType Type of the penalty
    /// @param amount Penalty amount in ETH
    /// @param details Additional details about the penalty
    function reportGeneralDelayedPenalty(
        uint256 nodeOperatorId,
        bytes32 penaltyType,
        uint256 amount,
        string calldata details
    ) external;

    /// @notice Compensate general delayed penalty (locked bond) for the given Node Operator from Node Operator's bond
    /// @dev Can only be called by the Node Operator manager
    /// @param nodeOperatorId ID of the Node Operator
    function compensateGeneralDelayedPenalty(uint256 nodeOperatorId) external;

    /// @notice Cancel previously reported and not settled general delayed 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 cancelGeneralDelayedPenalty(uint256 nodeOperatorId, uint256 amount) external;

    /// @notice Settles locked bond for eligible Node Operators
    /// @dev SETTLE_GENERAL_DELAYED_PENALTY_ROLE role is expected to be assigned to Easy Track
    /// @param nodeOperatorIds IDs of the Node Operators
    /// @param bondLockNonces Bond lock nonces for each Node Operator
    function settleGeneralDelayedPenalty(uint256[] memory nodeOperatorIds, uint256[] memory bondLockNonces) external;

    /// @notice Propose a new manager address for the Node Operator.
    /// @dev Passing address(0) clears the pending proposal without changing the current manager address.
    /// @param nodeOperatorId ID of the Node Operator
    /// @param proposedAddress Proposed manager address, or address(0) to cancel the current proposal
    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.
    /// @dev Passing address(0) clears the pending proposal without changing the current reward address.
    /// @param nodeOperatorId ID of the Node Operator
    /// @param proposedAddress Proposed reward address, or address(0) to cancel the current proposal
    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 Change both reward and manager addresses of a node operator. An emergency method.
    /// @dev Only privileged role member can call this method if the role is assigned.
    /// @param nodeOperatorId ID of the Node Operator
    /// @param newManagerAddress New manager address
    /// @param newRewardAddress New reward address
    function changeNodeOperatorAddresses(
        uint256 nodeOperatorId,
        address newManagerAddress,
        address newRewardAddress
    ) external;

    /// @notice Update depositable validators data for the given Node Operator.
    /// @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;

    /// @notice Update deposit info for the given Node Operator.
    /// @param nodeOperatorId ID of the Node Operator
    function updateDepositInfo(uint256 nodeOperatorId) external;

    /// @notice Request a full update of deposit info for all node operators.
    ///         Should be called after external changes that can affect deposit info such as bond curve change or parameters update.
    function requestFullDepositInfoUpdate() external;

    /// @notice Request a batch update of deposit info for node operators.
    ///         If `requestFullDepositInfoUpdate` was called before, the update will start from the first operator.
    ///         Otherwise, it will continue from the next operator after the last updated one.
    /// @param maxCount Maximum number of operators to update in this batch
    /// @return operatorsLeft Number of operators left to update
    function batchDepositInfoUpdate(uint256 maxCount) external returns (uint256 operatorsLeft);

    /// @notice Get the number of Node Operators with outdated deposit info that requires update.
    function getNodeOperatorDepositInfoToUpdateCount() external view returns (uint256 count);

    /// @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 Returns tracked operator balance (active validator base stake plus tracked extra).
    /// @dev The tracked extra is intentionally monotonic for active validators and is reduced on withdrawal reporting,
    ///      not on intermediate balance decreases, so the value serves both top-up allocation and withdrawal penalty accounting.
    /// @param nodeOperatorId ID of the Node Operator
    function getNodeOperatorBalance(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 key as slashed.
    /// @notice Called by `Verifier` contract. See `Verifier.processSlashedProof`.
    /// @param nodeOperatorId The ID of the Node Operator
    /// @param keyIndex Index of the key in the Node Operator's keys storage
    function reportValidatorSlashing(uint256 nodeOperatorId, uint256 keyIndex) external;

    /// @notice Update verified on-chain balance for a key.
    /// @dev The function stores balance relative to MIN_ACTIVATION_BALANCE.
    /// @param nodeOperatorId ID of the Node Operator
    /// @param keyIndex Index of the key in the Node Operator's keys storage
    /// @param currentBalanceWei Proven current validator balance in wei
    function reportValidatorBalance(uint256 nodeOperatorId, uint256 keyIndex, uint256 currentBalanceWei) external;

    /// @notice Get cumulative top-up amounts allocated to Node Operator keys (above MIN_ACTIVATION_BALANCE)
    /// @param nodeOperatorId ID of the Node Operator
    /// @param startIndex Index of the first key
    /// @param keysCount Count of keys to get
    /// @return balances Allocated balances above MIN_ACTIVATION_BALANCE (wei)
    function getKeyAllocatedBalances(
        uint256 nodeOperatorId,
        uint256 startIndex,
        uint256 keysCount
    ) external view returns (uint256[] memory balances);

    /// @notice Get verifier-confirmed balances for Node Operator keys (above MIN_ACTIVATION_BALANCE)
    /// @param nodeOperatorId ID of the Node Operator
    /// @param startIndex Index of the first key
    /// @param keysCount Count of keys to get
    /// @return balances Confirmed balances above MIN_ACTIVATION_BALANCE (wei)
    function getKeyConfirmedBalances(
        uint256 nodeOperatorId,
        uint256 startIndex,
        uint256 keysCount
    ) external view returns (uint256[] memory balances);

    /// @notice Report Node Operator's keys as withdrawn and charge penalties associated with exit if any.
    ///         A validator is considered withdrawn in the following cases:
    ///         - if it's an exit of a non-slashed validator, when a withdrawal of the validator is included in a beacon
    ///           block;
    ///         - if it's an exit of a slashed validator, when the committee reports such a validator as withdrawn; note
    ///           that it can happen earlier than the actual withdrawal is included on the beacon chain if the committee
    ///           decides it can account for all penalties in advance;
    ///         - if it's a consolidated validator, when the corresponding pending consolidation is processed and the
    ///           balance of the validator has been moved to another validator.
    /// @notice Called by `Verifier` contract.
    /// @param validatorInfos An array of WithdrawnValidatorInfo structs
    function reportRegularWithdrawnValidators(WithdrawnValidatorInfo[] calldata validatorInfos) external;

    /// @notice Report withdrawn validators that have been slashed.
    /// @notice Called by the Easy Track EVM script executor via a motion started by the dedicated committee.
    /// @param validatorInfos An array of WithdrawnValidatorInfo structs
    function reportSlashedWithdrawnValidators(WithdrawnValidatorInfo[] calldata validatorInfos) external;

    /// @notice Checks if a validator was reported as slashed
    /// @param nodeOperatorId The ID of the node operator
    /// @param keyIndex Index of the key in the Node Operator's keys storage
    /// @return True if a validator was reported as slashed
    function isValidatorSlashed(uint256 nodeOperatorId, uint256 keyIndex) external view returns (bool);

    /// @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 in the Node Operator's keys storage
    /// @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. Charging is module-specific (e.g., CSM applies a per-key fee).
    ///         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;
}

src/interfaces/IBondCore.sol

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

pragma solidity 0.8.33;

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

interface IBondCore {
    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 burnedAmount);
    event BondCharged(uint256 indexed nodeOperatorId, uint256 amountToCharge, uint256 chargedAmount);
    event BondDebtIncreased(uint256 indexed nodeOperatorId, uint256 amount);
    event BondDebtCovered(uint256 indexed nodeOperatorId, uint256 amount);

    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);

    /// @notice Get bond debt in ETH for the given Node Operator.
    ///         Bond debt can occur when Node Operator's bond is not enough to cover the penalties.
    ///         Any bond debt will be covered as soon as the Node Operator deposits more bond or receives rewards.
    /// @param nodeOperatorId ID of the Node Operator
    /// @return Bond debt in ETH
    function getBondDebt(uint256 nodeOperatorId) external view returns (uint256);
}

src/interfaces/IBondCurve.sol

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

pragma solidity 0.8.33;

interface IBondCurve {
    /// @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 BondCurveData {
        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, address indexed setter);

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

    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 (BondCurveData 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 (BondCurveData 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 the given 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 the given 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);
}

src/interfaces/IBondLock.sol

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

pragma solidity 0.8.33;

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

    event BondLockChanged(uint256 indexed nodeOperatorId, uint256 newAmount, uint256 until);
    event BondLockRemoved(uint256 indexed nodeOperatorId);
    event BondLockPeriodChanged(uint256 period);
    event BondLockNonceIncremented(uint256 indexed nodeOperatorId, uint256 newNonce);

    error InvalidBondLockPeriod();
    error InvalidBondLockAmount();
    error BondLockNotExpired();
    error NoBondLocked();

    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 (BondLockData 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 getLockedBond(uint256 nodeOperatorId) external view returns (uint256);

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

    /// @notice Check if the bond lock for the given Node Operator has expired
    /// @param nodeOperatorId ID of the Node Operator
    /// @return True if the bond lock has expired, false otherwise
    function isLockExpired(uint256 nodeOperatorId) external view returns (bool);
}

src/interfaces/ICuratedModule.sol

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

pragma solidity 0.8.33;

import { IBaseModule } from "./IBaseModule.sol";
import { IStakingModuleV2 } from "./IStakingModule.sol";
import { IMetaRegistry } from "./IMetaRegistry.sol";

interface ICuratedModule is IBaseModule, IStakingModuleV2 {
    event TopUpAllocationEnabled(uint256 indexed nodeOperatorId);
    event TopUpAllocationDisabled(uint256 indexed nodeOperatorId);

    error ZeroMetaRegistryAddress();
    error SenderIsNotMetaRegistry();

    /// @notice Role allowed to enable top-up allocation for node operators.
    function ENABLE_TOP_UP_ALLOCATION_ROLE() external view returns (bytes32);

    /// @notice Initializes the contract.
    /// @param admin An address to grant the DEFAULT_ADMIN_ROLE to.
    function initialize(address admin) external;

    /// @notice Finalizes the upgrade from version 1 to version 2.
    /// @dev Must be called atomically with the proxy upgrade. Fresh deployments use initialize instead.
    ///      Enables top-up allocation for existing operators with totalDepositedKeys > totalWithdrawnKeys.
    function finalizeUpgradeV2() external;

    /// @notice Enables top-up allocation for a node operator.
    /// @param nodeOperatorId ID of the node operator.
    function enableTopUpAllocation(uint256 nodeOperatorId) external;

    /// @notice Disables top-up allocation for a node operator. Only callable by its owner.
    /// @dev Excludes the operator's weight and stake from the executable top-up allocation baseline.
    /// @param nodeOperatorId ID of the node operator.
    function disableTopUpAllocation(uint256 nodeOperatorId) external;

    /// @notice Returns whether top-up allocation is enabled for a node operator.
    /// @param nodeOperatorId ID of the node operator.
    /// @return enabled Whether top-up allocation is enabled.
    function isTopUpAllocationEnabled(uint256 nodeOperatorId) external view returns (bool enabled);

    /// @notice Notifies the module about the weight change of a node operator.
    /// @param nodeOperatorId ID of the Node Operator
    /// @param oldWeight The old weight of the node operator.
    /// @param newWeight The new weight of the node operator.
    function notifyNodeOperatorWeightChange(uint256 nodeOperatorId, uint256 oldWeight, uint256 newWeight) external;

    /// @notice Returns operator weights used for operator-level allocations in the module.
    /// @dev Provides weights from the on-chain allocation strategy used by the module.
    /// @param operatorIds Node operator IDs to query.
    /// @return operatorWeights Weights aligned with operatorIds.
    function getOperatorWeights(
        uint256[] calldata operatorIds
    ) external view returns (uint256[] memory operatorWeights);

    /// @notice Returns effective weight and external stake for a node operator.
    /// @dev Reverts until the module deposit info cache is fully refreshed.
    /// @param nodeOperatorId Node operator ID to query.
    /// @return weight Effective allocation weight.
    /// @return externalStake External stake amount in wei.
    function getNodeOperatorWeightAndExternalStake(
        uint256 nodeOperatorId
    ) external view returns (uint256 weight, uint256 externalStake);

    /// @notice Returns current deposit allocation targets for all operators.
    /// @dev Target = totalCurrent * operatorWeight / totalWeight (in validator count).
    ///      Includes operators regardless of depositable capacity for informational purposes.
    ///      Actual allocation recalculates shares only across operators with usable capacity,
    ///      so real per-operator amounts may differ from the targets shown here.
    ///      Arrays are indexed by operator id; zero-weight operators have zero values.
    /// @return currentValidators Current active validator count per operator.
    /// @return targetValidators Target validator count per operator.
    function getDepositAllocationTargets()
        external
        view
        returns (uint256[] memory currentValidators, uint256[] memory targetValidators);

    /// @notice Returns current top-up allocation targets for all operators.
    /// @dev `target = totalCurrent * operatorWeight / totalWeight` (in wei).
    ///      Includes operators regardless of top-up capacity or whether allocation is enabled for informational purposes.
    ///      Actual allocation recalculates shares only across operators with allocation enabled and usable capacity,
    ///      so real per-operator amounts may differ from the targets shown here.
    ///      Arrays are indexed by operator id; zero-weight operators have zero values.
    /// @return currentAllocations Current operator stake in wei.
    /// @return targetAllocations Target operator stake in wei.
    function getTopUpAllocationTargets()
        external
        view
        returns (uint256[] memory currentAllocations, uint256[] memory targetAllocations);

    /// @notice  Method to get list of operators and amount of Eth that can be topped up to operator from depositAmount
    /// @param depositAmount Amount of Eth that can be deposited to module
    function getDepositsAllocation(
        uint256 depositAmount
    ) external view returns (uint256 allocated, uint256[] memory operatorIds, uint256[] memory allocations);

    /// @notice Returns current meta registry.
    function META_REGISTRY() external view returns (IMetaRegistry);
}

src/interfaces/IERC20Permit.sol

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

pragma solidity 0.8.33;

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

/**
 * @title Interface defining ERC20-compatible token
 */
interface IERC20Permit is IERC2612 {
    function balanceOf(address _account) external view returns (uint256);

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

    /**
     * @notice Moves `_amount` 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 allowance(address _owner, address _spender) external view returns (uint256);
}

src/interfaces/IERC2612.sol

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

pragma solidity 0.8.33;

interface IERC2612 {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     * 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}).
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;
}

src/interfaces/IExitPenalties.sol

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

pragma solidity 0.8.33;

import { IAccounting } from "./IAccounting.sol";
import { IParametersRegistry } from "./IParametersRegistry.sol";
import { IBaseModule } from "./IBaseModule.sol";
import { IExitTypes } from "./IExitTypes.sol";

struct MarkedUint248 {
    uint248 value;
    bool isValue;
}

struct ExitPenaltyInfo {
    MarkedUint248 delayFee;
    MarkedUint248 strikesPenalty;
    MarkedUint248 elWithdrawalRequestFee;
}

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

    event ValidatorExitDelayProcessed(uint256 indexed nodeOperatorId, bytes pubkey, uint256 delayFee);
    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 (IBaseModule);

    function ACCOUNTING() external view returns (IAccounting);

    function PARAMETERS_REGISTRY() external view returns (IParametersRegistry);

    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 elWithdrawalRequestFeePaid The fee paid for the withdrawal request
    /// @param exitType The type of the exit; only `VOLUNTARY_EXIT_TYPE_ID` skips recording EL withdrawal request fee
    function processTriggeredExit(
        uint256 nodeOperatorId,
        bytes calldata publicKey,
        uint256 elWithdrawalRequestFeePaid,
        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 an effect on the Node Operator.
    /// @dev called only by the module
    /// @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 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);
}

src/interfaces/IExitTypes.sol

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

pragma solidity 0.8.33;

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

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

src/interfaces/IFeeDistributor.sol

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

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

pragma solidity 0.8.33;

interface IFeeDistributor 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 InvalidRebateRecipientAddress();
    error SameRebateRecipientAddress();
    error SenderIsNotAccounting();
    error SenderIsNotOracle();

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

    function STETH() external view returns (IStETH);

    function ACCOUNTING() external view returns (address);

    function ORACLE() external view returns (address);

    /// @notice The latest Merkle Tree root
    function treeRoot() external view returns (bytes32);

    /// @notice CID of the last published Merkle tree
    function treeCid() external view returns (string calldata);

    /// @notice CID of the file with log for the last frame reported
    function logCid() external view returns (string calldata);

    /// @notice Amount of stETH shares sent to the Accounting in favor of the NO
    function distributedShares(uint256) external view returns (uint256);

    /// @notice Total Amount of stETH shares available for claiming by NOs
    function totalClaimableShares() external view returns (uint256);

    /// @notice The number of records retrievable via `getHistoricalDistributionData`
    function distributionDataHistoryCount() external view returns (uint256);

    /// @notice The address to transfer rebate to
    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 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 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 IPFS CID of the tree
    /// @param _logCid IPFS CID of the log
    /// @param distributed Amount of the distributed shares
    /// @param rebate Amount of the rebate shares
    /// @param refSlot Reference slot 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 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);
}

src/interfaces/IFeeSplits.sol

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

pragma solidity 0.8.33;

interface IFeeSplits {
    struct FeeSplit {
        address recipient;
        uint256 share; // in basis points
    }

    struct SplitTransfer {
        address recipient;
        uint256 shares;
    }

    event FeeSplitsSet(uint256 indexed nodeOperatorId, FeeSplit[] feeSplits);
    event PendingSharesToSplitChanged(uint256 indexed nodeOperatorId, uint256 pendingSharesToSplit);

    error PendingSharesExist();
    error FeeSplitsChangeWithUndistributedRewards();
    error TooManySplits();
    error TooManySplitShares();
    error ZeroSplitRecipient();
    error InvalidSplitRecipient();
    error ZeroSplitShare();

    /// @notice Get fee splits for the given Node Operator
    /// @param nodeOperatorId ID of the Node Operator
    /// @return Array of FeeSplit structs defining recipients and their shares in basis points
    function getFeeSplits(uint256 nodeOperatorId) external view returns (FeeSplit[] memory);

    /// @notice Get the number of the pending shares to be split for the given Node Operator
    function getPendingSharesToSplit(uint256 nodeOperatorId) external view returns (uint256);

    /// @notice Check if the given Node Operator has fee splits
    function hasSplits(uint256 nodeOperatorId) external view returns (bool);

    /// @notice Calculate fee split transfers for the given Node Operator
    /// @param nodeOperatorId ID of the Node Operator
    /// @param splittableShares Shares amount that can be split according to the current state of the Node Operator rewards and pending shares to split
    ///                         getPendingSharesToSplit() + FeeDistributor.getFeesToDistribute()
    /// @return transfers Shares amounts to transfer to each split recipient
    function getFeeSplitTransfers(
        uint256 nodeOperatorId,
        uint256 splittableShares
    ) external view returns (SplitTransfer[] memory transfers);
}

src/interfaces/ILido.sol

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

pragma solidity 0.8.33;

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 getDepositableEther() external view returns (uint256);

    function removeStakingLimit() external;

    function kernel() external returns (address);

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

src/interfaces/ILidoLocator.sol

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

pragma solidity 0.8.33;

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

src/interfaces/IMetaRegistry.sol

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

pragma solidity 0.8.33;

import { IAccounting } from "./IAccounting.sol";
import { ICuratedModule } from "./ICuratedModule.sol";

/// @notice Stored operator metadata.
struct OperatorMetadata {
    string name;
    string description;
    bool ownerEditsRestricted;
}

/// @notice Meta registry for curated node operator groups.
interface IMetaRegistry {
    struct SubNodeOperator {
        uint64 nodeOperatorId;
        uint16 share;
    }

    struct ExternalOperator {
        bytes data;
    }

    struct OperatorGroup {
        string name;
        SubNodeOperator[] subNodeOperators;
        ExternalOperator[] externalOperators;
    }

    event OperatorGroupCreated(uint256 indexed groupId, OperatorGroup groupInfo);
    event OperatorGroupUpdated(uint256 indexed groupId, OperatorGroup groupInfo);
    event OperatorGroupCleared(uint256 indexed groupId);
    event BondCurveWeightSet(uint256 indexed curveId, uint256 weight);
    event OperatorMetadataSet(uint256 indexed nodeOperatorId, OperatorMetadata metadata);
    event NodeOperatorEffectiveWeightChanged(uint256 indexed nodeOperatorId, uint256 oldWeight, uint256 newWeight);

    error ZeroModuleAddress();
    error ZeroAdminAddress();
    error InvalidOperatorGroup();
    error InvalidSubNodeOperatorShares();
    error InvalidOperatorGroupId();
    error InvalidOperatorGroupName();
    error NodeOperatorDoesNotExist();
    error NodeOperatorAlreadyInGroup(uint256 nodeOperatorId);
    error AlreadyUsedAsExternalOperator();
    error SenderIsNotEligible();
    error OwnerEditsRestricted();
    error SameBondCurveWeight();
    error InvalidBondCurveWeight();
    error ModuleAddressNotCached();
    error OperatorNameTooLong();
    error OperatorDescriptionTooLong();

    /// @notice Role allowed to manage operator groups.
    function MANAGE_OPERATOR_GROUPS_ROLE() external view returns (bytes32);

    /// @notice Sentinel value representing no operator group.
    function NO_GROUP_ID() external view returns (uint256);

    /// @notice Role allowed to set operator metadata.
    function SET_OPERATOR_INFO_ROLE() external view returns (bytes32);

    /// @notice Role allowed to set bond curve weights.
    function SET_BOND_CURVE_WEIGHT_ROLE() external view returns (bytes32);

    /// @notice Curated module allowed to call module-only hooks.
    function MODULE() external view returns (ICuratedModule);

    /// @notice Accounting contract used for bond curve lookups.
    function ACCOUNTING() external view returns (IAccounting);

    /// @notice Initialize the registry.
    /// @param admin Address to receive DEFAULT_ADMIN_ROLE.
    function initialize(address admin) external;

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

    /// @notice Set or update metadata for a node operator (callable by SET_OPERATOR_INFO_ROLE).
    /// @param nodeOperatorId Node operator ID.
    /// @param metadata Metadata payload to persist.
    function setOperatorMetadataAsAdmin(uint256 nodeOperatorId, OperatorMetadata calldata metadata) external;

    /// @notice Set or update metadata by the node operator owner.
    /// @param nodeOperatorId Node operator ID.
    /// @param name Display name.
    /// @param description Long description.
    /// @dev Reverts if module does not support IBaseModule interface.
    function setOperatorMetadataAsOwner(
        uint256 nodeOperatorId,
        string calldata name,
        string calldata description
    ) external;

    /// @notice Get metadata for a node operator.
    /// @param nodeOperatorId Node operator ID.
    /// @return metadata Stored metadata struct.
    function getOperatorMetadata(uint256 nodeOperatorId) external view returns (OperatorMetadata memory metadata);

    /// @notice Create a new operator group or update an existing one.
    /// @param groupId Group ID to update, or NO_GROUP_ID to create.
    /// @param groupInfo Group definition.
    /// @dev Creating is allowed only when groupId == NO_GROUP_ID.
    /// @dev To clear a group pass empty subNodeOperators, empty externalOperators, and empty name.
    function createOrUpdateOperatorGroup(uint256 groupId, OperatorGroup calldata groupInfo) external;

    /// @notice Fetch an operator group by ID.
    /// @param groupId Group ID to fetch.
    /// @return groupInfo Group definition.
    function getOperatorGroup(uint256 groupId) external view returns (OperatorGroup memory groupInfo);

    /// @notice Returns total operator groups count.
    function getOperatorGroupsCount() external view returns (uint256 count);

    /// @notice Get Node Operator group ID (returns NO_GROUP_ID if the operator is not in any group).
    /// @param nodeOperatorId Node operator ID to query.
    /// @return operatorGroupId Group ID.
    function getNodeOperatorGroupId(uint256 nodeOperatorId) external view returns (uint256 operatorGroupId);

    /// @notice Get External Operator group ID (returns NO_GROUP_ID if the operator is not in any group).
    /// @param op External operator.
    /// @return operatorGroupId Group ID.
    function getExternalOperatorGroupId(ExternalOperator calldata op) external view returns (uint256 operatorGroupId);

    /// @notice Returns base weight for the bond curve ID.
    /// @param curveId Bond curve ID.
    /// @return weight Base allocation weight.
    function getBondCurveWeight(uint256 curveId) external view returns (uint256 weight);

    /// @notice Set base weight for the bond curve ID (callable by SET_BOND_CURVE_WEIGHT_ROLE).
    /// @dev Effective weights for operators using the curve will not be updated automatically.
    ///      refreshOperatorWeight() must be called for the affected operators to update their effective weights.
    /// @param curveId Bond curve ID.
    /// @param weight Base allocation weight.
    function setBondCurveWeight(uint256 curveId, uint256 weight) external;

    /// @notice Returns effective weight for the node operator.
    /// @param nodeOperatorId Node operator ID to query.
    /// @return weight Effective allocation weight.
    /// @dev Returns the cached effective weight.
    /// @dev Operators outside any group are expected to have zero cached weight.
    function getNodeOperatorWeight(uint256 nodeOperatorId) external view returns (uint256 weight);

    /// @notice Returns effective weight and external stake for the node operator.
    /// @param nodeOperatorId Node operator ID to query.
    /// @return weight Effective allocation weight.
    /// @return externalStake External stake amount in wei.
    /// @dev Returns (0, 0) if the operator is not in a group.
    /// @dev During partial deposit info refreshes, cached weights may be updated only for a subset
    ///      of operators, so direct reads can transiently reflect mixed-state group totals.
    ///      Integrations that require a fully refreshed view should prefer the curated module getter.
    function getNodeOperatorWeightAndExternalStake(
        uint256 nodeOperatorId
    ) external view returns (uint256 weight, uint256 externalStake);

    /// @notice Returns allocation weights for the given node operators.
    /// @param nodeOperatorIds Node operator IDs to query.
    /// @return operatorWeights Weights aligned with nodeOperatorIds.
    function getOperatorWeights(
        uint256[] calldata nodeOperatorIds
    ) external view returns (uint256[] memory operatorWeights);

    /// @notice Trigger the operator weight update routine in the registry.
    /// @param nodeOperatorId Node operator ID to trigger the update for.
    function refreshOperatorWeight(uint256 nodeOperatorId) external;
}

src/interfaces/IParametersRegistry.sol

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

pragma solidity 0.8.33;

interface IParametersRegistry {
    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;
    }

    /// @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;
    }

    struct InitializationData {
        uint256 defaultKeyRemovalCharge;
        uint256 defaultGeneralDelayedPenaltyAdditionalFine;
        uint256 defaultKeysLimit;
        uint256 defaultRewardShare;
        uint256 defaultPerformanceLeeway;
        uint256 defaultStrikesLifetime;
        uint256 defaultStrikesThreshold;
        uint256 defaultQueuePriority;
        uint256 defaultQueueMaxDeposits;
        uint256 defaultBadPerformancePenalty;
        uint256 defaultAttestationsWeight;
        uint256 defaultBlocksWeight;
        uint256 defaultSyncWeight;
        uint256 defaultAllowedExitDelay;
        uint256 defaultExitDelayFee;
        uint256 defaultMaxElWithdrawalRequestFee;
    }

    struct CurveParameters {
        uint256 keyRemovalCharge;
        uint256 generalDelayedPenaltyAdditionalFine;
        uint256 keysLimit;
        uint32 queuePriority;
        uint32 queueMaxDeposits;
        KeyNumberValueInterval[] rewardShareData;
        KeyNumberValueInterval[] performanceLeewayData;
        uint256 strikesLifetime;
        uint256 strikesThreshold;
        uint256 badPerformancePenalty;
        uint256 attestationsWeight;
        uint256 blocksWeight;
        uint256 syncWeight;
        uint256 allowedExitDelay;
        uint256 exitDelayFee;
        uint256 maxElWithdrawalRequestFee;
    }

    event DefaultKeyRemovalChargeSet(uint256 value);
    event DefaultGeneralDelayedPenaltyAdditionalFineSet(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 DefaultExitDelayFeeSet(uint256 penalty);
    event DefaultMaxElWithdrawalRequestFeeSet(uint256 fee);

    event KeyRemovalChargeSet(uint256 indexed curveId, uint256 keyRemovalCharge);
    event GeneralDelayedPenaltyAdditionalFineSet(uint256 indexed curveId, uint256 fine);
    event KeysLimitSet(uint256 indexed curveId, uint256 limit);
    event QueueConfigSet(uint256 indexed curveId, uint256 priority, uint256 maxDeposits);
    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 AllowedExitDelaySet(uint256 indexed curveId, uint256 delay);
    event ExitDelayFeeSet(uint256 indexed curveId, uint256 penalty);
    event MaxElWithdrawalRequestFeeSet(uint256 indexed curveId, uint256 fee);

    event KeyRemovalChargeUnset(uint256 indexed curveId);
    event GeneralDelayedPenaltyAdditionalFineUnset(uint256 indexed curveId);
    event KeysLimitUnset(uint256 indexed curveId);
    event QueueConfigUnset(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 AllowedExitDelayUnset(uint256 indexed curveId);
    event ExitDelayFeeUnset(uint256 indexed curveId);
    event MaxElWithdrawalRequestFeeUnset(uint256 indexed curveId);

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

    /// @notice Role to manage general penalties and charges parameters: key removal charge and general delayed penalty additional fine
    function MANAGE_GENERAL_PENALTIES_AND_CHARGES_ROLE() external view returns (bytes32);

    /// @notice Role to manage keys limit parameter
    function MANAGE_KEYS_LIMIT_ROLE() external view returns (bytes32);

    /// @notice Role to manage queue config
    function MANAGE_QUEUE_CONFIG_ROLE() external view returns (bytes32);

    /// @notice Role to manage performance parameters: performance leeway, strikes params, bad performance penalty, performance coefficients
    function MANAGE_PERFORMANCE_PARAMETERS_ROLE() external view returns (bytes32);

    /// @notice Role to manage reward share parameters
    function MANAGE_REWARD_SHARE_ROLE() external view returns (bytes32);

    /// @notice Role to manage validator exit related parameters: allowed exit delay, exit delay fee, EL max withdrawal request fee
    function MANAGE_VALIDATOR_EXIT_PARAMETERS_ROLE() external view returns (bytes32);

    /// @notice Role to manage per-curve parameters (setters and unsetters only)
    function MANAGE_CURVE_PARAMETERS_ROLE() external view returns (bytes32);

    /// @notice The lowest priority a deposit queue can be assigned with. This constant is not used in Curated Module
    function QUEUE_LOWEST_PRIORITY() external view returns (uint256);

    /// @notice Get default value for the key removal charge. This parameter is not used in Curated Module
    function defaultKeyRemovalCharge() external returns (uint256);

    /// @notice Get default value for the general delayed penalty additional fine
    function defaultGeneralDelayedPenaltyAdditionalFine() external returns (uint256);

    /// @notice Get default value for the keys limit
    function defaultKeysLimit() external returns (uint256);

    /// @notice Get default value for QueueConfig. This parameter is not used in Curated Module
    /// @return priority Default queue priority
    /// @return maxDeposits Default maximum number of the first deposits a Node Operator can get via the priority queue
    function defaultQueueConfig() external returns (uint32 priority, uint32 maxDeposits);

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

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

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

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

    /// @notice Get default value for the performance coefficients
    /// @return attestationsWeight Attestations effectiveness weight
    /// @return blocksWeight Block proposals effectiveness weight
    /// @return syncWeight Sync participation effectiveness weight
    function defaultPerformanceCoefficients()
        external
        returns (uint32 attestationsWeight, uint32 blocksWeight, uint32 syncWeight);

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

    /// @notice Get default value for exit delay penalty
    function defaultExitDelayFee() external returns (uint256);

    /// @notice Get default value for max EL withdrawal request fee
    function defaultMaxElWithdrawalRequestFee() external 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. This parameter is not used in Curated Module
    /// @param keyRemovalCharge Value to be set as default for the key removal charge
    function setDefaultKeyRemovalCharge(uint256 keyRemovalCharge) external;

    /// @notice Set default value for the general delayed penalty 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 general delayed penalty additional fine
    function setDefaultGeneralDelayedPenaltyAdditionalFine(uint256 fine) external;

    /// @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 Set default value for QueueConfig. Default value is used if a specific value is not set for the curveId. This parameter is not used in Curated Module
    /// @param priority Queue priority.
    /// @param maxDeposits Maximum number of the first 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 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 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 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 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 Set the default value for the bad performance penalty for a single 32 ether validator
    /// This 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 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 set default value for the allowed 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 the default value for exit delay penalty for a single 32 ether validator
    /// This value is used if a specific value is not set for the curveId
    /// @param fee The value to be set as default for the exit delay fee
    function setDefaultExitDelayFee(uint256 fee) external;

    /// @notice set default value for max EL 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 EL withdrawal request fee
    function setDefaultMaxElWithdrawalRequestFee(uint256 fee) external;

    /// @notice Set key removal charge for the curveId. This parameter is not used in Curated Module
    /// @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. This parameter is not used in Curated Module
    /// @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 the module. This parameter is not used in Curated Module
    /// @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 general delayed penalty additional fine for the curveId.
    /// @param curveId Curve Id to associate general delayed penalty additional fine limit with
    /// @param fine General delayed penalty additional fine
    function setGeneralDelayedPenaltyAdditionalFine(uint256 curveId, uint256 fine) external;

    /// @notice Unset general delayed penalty additional fine for the curveId
    /// @param curveId Curve Id to unset custom general delayed penalty additional fine for
    function unsetGeneralDelayedPenaltyAdditionalFine(uint256 curveId) external;

    /// @notice Get general delayed penalty additional fine by the curveId. Additional fine is added to the general delayed penalty by CSM
    /// @dev `defaultGeneralDelayedPenaltyAdditionalFine` is returned if the value is not set for the given curveId.
    /// @param curveId Curve Id to get general delayed penalty additional fine for
    /// @return fine General delayed penalty additional fine
    function getGeneralDelayedPenaltyAdditionalFine(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 keys limit for the curveId
    /// @param curveId Curve Id to unset custom keys limit for
    function unsetKeysLimit(uint256 curveId) external;

    /// @notice Get keys limit by the curveId. A limit indicates the maximal amount of the non-withdrawn 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 Sets the provided config to the given curve. This parameter is not used in Curated Module
    /// @param curveId Curve Id to set the config.
    /// @param priority Queue priority.
    /// @param maxDeposits Maximum number of the first 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. This parameter is not used in Curated Module
    /// @param curveId Curve Id to unset custom config.
    function unsetQueueConfig(uint256 curveId) external;

    /// @notice Get the queue config for the given curve. This parameter is not used in Curated Module
    /// @param curveId Curve Id to get the queue config for.
    /// @return priority Queue priority.
    /// @return maxDeposits Maximum number of the first 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 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
    /// @return 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 performance leeway parameters for the 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
    /// @return 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 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 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 the bad performance penalty for the curveId for a single 32 ether validator
    /// @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 for a single 32 ether validator 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 allowed exit 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 the exit delay penalty for a single 32 ether validator for the given curveId
    /// @param curveId Curve Id to associate exit delay penalty with
    /// @param fee Exit delay fee
    function setExitDelayFee(uint256 curveId, uint256 fee) external;

    /// @notice Unset exit delay penalty for the curveId
    /// @param curveId The curve ID for unsetting the exit delay fee
    function unsetExitDelayFee(uint256 curveId) external;

    /// @notice Get exit delay penalty for a single 32 ether validator by the curveId
    /// @dev `defaultExitDelayFee` is returned if the value is not set for the given curveId.
    /// @param curveId Curve ID to get the exit delay fee for
    function getExitDelayFee(uint256 curveId) external view returns (uint256 penalty);

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

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

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

    /// @notice Get all parameters resolved for the given curveId in one call
    /// @dev Per-curve values are returned where set, otherwise defaults are used
    /// @param curveId Curve Id to get all parameters for
    /// @return params All resolved parameters for the given curveId
    function getCurveParameters(uint256 curveId) external view returns (CurveParameters memory params);

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

src/interfaces/IStETH.sol

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

pragma solidity 0.8.33;

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

/**
 * @title Interface defining ERC20-compatible StETH token
 */
interface IStETH is IERC20Permit {
    /**
     * @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);

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

src/interfaces/IStakingModule.sol

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

pragma solidity 0.8.33;

/// @dev Target limit mode id for forced mode.
uint8 constant FORCED_TARGET_LIMIT_MODE_ID = 2;

/// @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 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 Packed array of the node operators id
    /// @param exitedValidatorsCounts 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
    /// @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;
}

interface IStakingModuleV2 {
    /// @notice Returns the total tracked stake of the module in wei.
    /// @dev This is the sum of the activation base for active validators and tracked extra stake.
    ///      The tracked extra is intentionally reduced on withdrawal reporting rather than on intermediate validator balance decreases.
    function getTotalModuleStake() external view returns (uint256 totalModuleStakeWei);

    /// @notice Validates that provided keys belong to the corresponding operators in the module and calculates deposit allocations for top-up
    /// @dev Reverts if any key doesn't belong to the module or data is invalid
    /// @param maxDepositAmount Total ether amount available for top-up (must be multiple of 1 gwei)
    /// @param pubkeys List of validator public keys to top up
    /// @param keyIndices Indices of keys within their respective operators
    /// @param operatorIds Node operator IDs that own the keys
    /// @param topUpLimits Maximum amount that can be deposited per key based on CL data and SR internal logic.
    /// @return allocations Amount to deposit to each key
    /// @dev Values depositAmount, topUpLimits, allocations are denominated in wei
    /// @dev allocations list can contain zero values
    /// @dev sum of allocations can be less or equal to maxDepositAmount
    function allocateDeposits(
        uint256 maxDepositAmount,
        bytes[] calldata pubkeys,
        uint256[] calldata keyIndices,
        uint256[] calldata operatorIds,
        uint256[] calldata topUpLimits
    ) external returns (uint256[] memory allocations);
}

src/interfaces/IWithdrawalQueue.sol

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

pragma solidity 0.8.33;

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;
}

src/interfaces/IWstETH.sol

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

pragma solidity 0.8.33;

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

interface IWstETH is IERC20Permit {
    function wrap(uint256 _stETHAmount) external returns (uint256);

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

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

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

src/lib/AssetRecovererLib.sol

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

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.
 * External deployment-linked library used by multiple production contracts.
 */
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);
    }
}

src/lib/DepositQueueLib.sol

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

// 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 ("memory-safe") {
        n := shr(192, self)
    }
}

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

function next(Batch self) pure returns (uint128 n) {
    uint256 mask = type(uint128).max;
    assembly ("memory-safe") {
        n := and(self, mask)
    }
}

/// @dev keys count cast is unsafe
function setKeys(Batch self, uint256 keysCount) pure returns (Batch) {
    assembly ("memory-safe") {
        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 ("memory-safe") {
        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) {
    // Queue slots reserve 64 bits for node operator IDs; upstream module numbers are capped well
    // below that limit, so truncation cannot occur.
    // forge-lint: disable-next-line(unsafe-typecast)
    nodeOperatorId = uint64(nodeOperatorId);
    // Keys per batch are also capped by module key pointers (uint32), so they comfortably fit 64 bits.
    // forge-lint: disable-next-line(unsafe-typecast)
    keysCount = uint64(keysCount);

    assembly ("memory-safe") {
        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 DepositQueueLib for DepositQueueLib.Queue;

/// @dev Helps expose the errors to the ICSModule interface.
interface IDepositQueueLib {
    error DepositQueueIsEmpty();
}

/// @author madlabman
library DepositQueueLib {
    struct Queue {
        // Pointer to the item to be dequeued.
        uint128 head;
        // Tracks the index to enqueue an item to.
        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
    //////

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

        assembly ("memory-safe") {
            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 IDepositQueueLib.DepositQueueIsEmpty();

        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];
    }
}

src/lib/KeyPointerLib.sol

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

library KeyPointerLib {
    function keyPointer(uint256 nodeOperatorId, bytes calldata publicKey) internal pure returns (bytes32) {
        return keccak256(abi.encode(nodeOperatorId, publicKey));
    }

    function keyPointer(uint256 nodeOperatorId, uint256 keyIndex) internal pure returns (uint256) {
        return (nodeOperatorId << 128) | keyIndex;
    }
}

src/lib/StakeTracker.sol

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

pragma solidity 0.8.33;

import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";

import { IBaseModule, NodeOperator } from "../interfaces/IBaseModule.sol";
import { ModuleLinearStorage } from "../abstract/ModuleLinearStorage.sol";
import { ValidatorBalanceLimits } from "./ValidatorBalanceLimits.sol";
import { KeyPointerLib } from "./KeyPointerLib.sol";
import { TransientUintUintMap, TransientUintUintMapLib } from "./TransientUintUintMapLib.sol";

/// @dev Centralizes tracked stake updates for operator extra balances, total extra stake, and key balance transitions.
///      External deployment-linked library used by BaseModule-compatible modules.
library StakeTracker {
    using TransientUintUintMapLib for TransientUintUintMap;

    /// @dev Increases tracked operator extra balance and total extra stake by the given delta.
    function increaseOperatorBalance(
        ModuleLinearStorage.BaseModuleStorage storage $,
        uint256 operatorId,
        uint256 incrementWei
    ) internal {
        if (incrementWei == 0) return;

        _setOperatorBalance($, operatorId, $.operatorBalances[operatorId] + incrementWei);
        $.totalExtraStake += incrementWei;
    }

    /// @dev Decreases tracked operator extra balance and total extra stake by the given delta.
    function decreaseOperatorBalance(
        ModuleLinearStorage.BaseModuleStorage storage $,
        uint256 operatorId,
        uint256 decrementWei
    ) internal {
        if (decrementWei == 0) return;

        _setOperatorBalance($, operatorId, $.operatorBalances[operatorId] - decrementWei);
        $.totalExtraStake -= decrementWei;
    }

    /// @dev Applies per-key top-up allocations, updates key allocated balances, and aggregates stake deltas per operator.
    function increaseKeyBalances(
        ModuleLinearStorage.BaseModuleStorage storage $,
        uint256[] calldata operatorIds,
        uint256[] calldata keyIndices,
        uint256[] calldata allocations
    ) external {
        uint256[] memory allocatedOperatorIds = new uint256[](operatorIds.length);
        uint256[] memory increments = new uint256[](operatorIds.length);
        TransientUintUintMap operatorIndexes = TransientUintUintMapLib.create();
        uint256 touchedOperatorsCount;

        for (uint256 i; i < allocations.length; ++i) {
            uint256 allocationWei = allocations[i];
            if (allocationWei == 0) continue;
            // Current allocators cap per-key top-ups before they reach StakeTracker, so a partial
            // application here is a defensive safeguard for unreachable-by-design inputs.
            uint256 appliedIncrementWei = _increaseKeyAllocatedBalance(
                $.keyAllocatedBalance,
                operatorIds[i],
                keyIndices[i],
                allocationWei
            );
            if (appliedIncrementWei == 0) continue;

            uint256 operatorIndex = operatorIndexes.get(operatorIds[i]);
            if (operatorIndex == 0) {
                operatorIndex = touchedOperatorsCount;
                allocatedOperatorIds[operatorIndex] = operatorIds[i];
                increments[operatorIndex] = appliedIncrementWei;
                unchecked {
                    ++touchedOperatorsCount;
                }
                // Store index + 1 so zero can remain the "not seen yet" sentinel in the transient map.
                operatorIndexes.set(operatorIds[i], touchedOperatorsCount);
            } else {
                unchecked {
                    increments[operatorIndex - 1] += appliedIncrementWei;
                }
            }
        }

        for (uint256 i; i < touchedOperatorsCount; ++i) {
            increaseOperatorBalance($, allocatedOperatorIds[i], increments[i]);
        }
    }

    /// @dev Returns the total tracked stake for the given operator: base 32 ETH per active validator plus stored extra.
    function getOperatorBalance(
        ModuleLinearStorage.BaseModuleStorage storage $,
        uint256 operatorId
    ) internal view returns (uint256) {
        return
            _activeValidatorsCount($.nodeOperators[operatorId]) *
            ValidatorBalanceLimits.MIN_ACTIVATION_BALANCE +
            $.operatorBalances[operatorId];
    }

    /// @dev Returns the total tracked module stake: base 32 ETH per active validator plus stored extra.
    function getTotalModuleStake(ModuleLinearStorage.BaseModuleStorage storage $) internal view returns (uint256) {
        unchecked {
            return _activeModuleValidatorsCount($) * ValidatorBalanceLimits.MIN_ACTIVATION_BALANCE + $.totalExtraStake;
        }
    }

    /// @dev Raises confirmed key balance and also raises allocated balance when the confirmed value overtakes it.
    ///      Returns the implied operator/module stake delta via the internal helper path.
    ///      Decreases for active validators are intentionally not applied here: the tracked extra stays at the
    ///      highest observed level until withdrawal reporting settles any loss for penalty accounting.
    function reportValidatorBalance(
        ModuleLinearStorage.BaseModuleStorage storage $,
        uint256 nodeOperatorId,
        uint256 keyIndex,
        uint256 newConfirmed
    ) internal {
        uint256 pointer = KeyPointerLib.keyPointer(nodeOperatorId, keyIndex);
        if ($.isValidatorWithdrawn[pointer]) revert IBaseModule.UnreportableBalance();

        uint256 oldConfirmed = $.keyConfirmedBalance[pointer];
        if (newConfirmed <= oldConfirmed) revert IBaseModule.UnreportableBalance();

        uint256 allocatedIncrementWei;
        uint256 oldAllocated = $.keyAllocatedBalance[pointer];
        if (oldAllocated < newConfirmed) {
            allocatedIncrementWei = newConfirmed - oldAllocated;
            $.keyAllocatedBalance[pointer] = newConfirmed;
            emit IBaseModule.KeyAllocatedBalanceChanged(nodeOperatorId, keyIndex, newConfirmed);
        }

        $.keyConfirmedBalance[pointer] = newConfirmed;
        emit IBaseModule.KeyConfirmedBalanceChanged(nodeOperatorId, keyIndex, newConfirmed);

        increaseOperatorBalance($, nodeOperatorId, allocatedIncrementWei);
    }

    function _setOperatorBalance(
        ModuleLinearStorage.BaseModuleStorage storage $,
        uint256 operatorId,
        uint256 balanceWei
    ) private {
        if ($.operatorBalances[operatorId] == balanceWei) return;
        $.operatorBalances[operatorId] = balanceWei;
        emit IBaseModule.NodeOperatorBalanceUpdated(operatorId, getOperatorBalance($, operatorId));
    }

    function _increaseKeyAllocatedBalance(
        mapping(uint256 => uint256) storage keyAllocatedBalance,
        uint256 nodeOperatorId,
        uint256 keyIndex,
        uint256 incrementWei
    ) private returns (uint256 appliedIncrementWei) {
        uint256 pointer = KeyPointerLib.keyPointer(nodeOperatorId, keyIndex);
        uint256 oldAllocated = keyAllocatedBalance[pointer];
        uint256 updated = Math.min(
            ValidatorBalanceLimits.MAX_EFFECTIVE_BALANCE - ValidatorBalanceLimits.MIN_ACTIVATION_BALANCE,
            oldAllocated + incrementWei
        );
        unchecked {
            appliedIncrementWei = updated - oldAllocated;
        }
        if (appliedIncrementWei > 0) {
            keyAllocatedBalance[pointer] = updated;
            emit IBaseModule.KeyAllocatedBalanceChanged(nodeOperatorId, keyIndex, updated);
        }
    }

    function _activeValidatorsCount(NodeOperator storage no) private view returns (uint256) {
        unchecked {
            return no.totalDepositedKeys - no.totalWithdrawnKeys;
        }
    }

    function _activeModuleValidatorsCount(
        ModuleLinearStorage.BaseModuleStorage storage $
    ) private view returns (uint256) {
        unchecked {
            return uint256($.totalDepositedValidators) - $.totalWithdrawnValidators;
        }
    }
}

src/lib/TopUpAllocationLib.sol

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

pragma solidity 0.8.33;

library TopUpAllocationLib {
    bytes32 private constant TOP_UP_ALLOCATION_ENABLED_POSITION =
        keccak256("lido.CuratedModule.topUpAllocationEnabled");

    error TopUpAllocationStateUnchanged();

    function setState(uint256 nodeOperatorId, bool enabled) internal {
        mapping(uint256 => bool) storage enabledByOperator = _enabledByOperator();
        if (enabledByOperator[nodeOperatorId] == enabled) revert TopUpAllocationStateUnchanged();
        enabledByOperator[nodeOperatorId] = enabled;
    }

    function isEnabled(uint256 nodeOperatorId) internal view returns (bool) {
        return _enabledByOperator()[nodeOperatorId];
    }

    function _enabledByOperator() private pure returns (mapping(uint256 => bool) storage m) {
        bytes32 position = TOP_UP_ALLOCATION_ENABLED_POSITION;
        assembly ("memory-safe") {
            // Anchor the mapping at the fixed position; entries land at keccak256(abi.encode(id, position)).
            m.slot := position
        }
    }
}

src/lib/TransientUintUintMapLib.sol

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

pragma solidity 0.8.33;

import { SlotDerivation } from "@openzeppelin/contracts/utils/SlotDerivation.sol";
import { TransientSlot } from "@openzeppelin/contracts/utils/TransientSlot.sol";

type TransientUintUintMap is bytes32;

using TransientUintUintMapLib for TransientUintUintMap global;

library TransientUintUintMapLib {
    using SlotDerivation for bytes32;
    using TransientSlot for bytes32;
    using TransientSlot for TransientSlot.Uint256Slot;

    // SlotDerivation.erc7201Slot("TransientUintUintMap")
    bytes32 private constant ANCHOR = 0x6e38e7eaa4307e6ee6c66720337876ca65012869fbef035f57219354c1728400;

    function create() internal returns (TransientUintUintMap self) {
        // `ANCHOR` slot in the transient storage tracks the base of the last created object.
        // The next base is derived as a mapping slot from `ANCHOR` keyed by `prev`.
        TransientSlot.Uint256Slot anchor = ANCHOR.asUint256();
        uint256 prev = anchor.tload();
        self = TransientUintUintMap.wrap(ANCHOR.deriveMapping(prev));
        anchor.tstore(uint256(TransientUintUintMap.unwrap(self)));
    }

    function add(TransientUintUintMap self, uint256 key, uint256 value) internal {
        TransientSlot.Uint256Slot slot = _slot(self, key).asUint256();
        // NOTE: Here's no overflow check.
        unchecked {
            slot.tstore(slot.tload() + value);
        }
    }

    function set(TransientUintUintMap self, uint256 key, uint256 value) internal {
        _slot(self, key).asUint256().tstore(value);
    }

    function get(TransientUintUintMap self, uint256 key) internal view returns (uint256) {
        return _slot(self, key).asUint256().tload();
    }

    function load(bytes32 tslot) internal pure returns (TransientUintUintMap) {
        return TransientUintUintMap.wrap(tslot);
    }

    function _slot(TransientUintUintMap self, uint256 key) internal pure returns (bytes32) {
        // Derives a transient storage slot following Solidity mapping layout.
        return TransientUintUintMap.unwrap(self).deriveMapping(key);
    }
}

src/lib/ValidatorBalanceLimits.sol

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

pragma solidity 0.8.33;

library ValidatorBalanceLimits {
    uint256 internal constant MIN_ACTIVATION_BALANCE = 32 ether;
    uint256 internal constant MAX_EFFECTIVE_BALANCE = 2048 ether;
}

src/lib/allocator/DepositAllocatorGreedy.sol

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

import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { PackedSortKey, PackedSortKeyLib } from "./PackedSortKeyLib.sol";
import { PackedSortKeyMaxHeapLib } from "./PackedSortKeyMaxHeapLib.sol";

/// @dev Helper struct for input allocation state.
struct AllocationState {
    /// @dev Target share per operator scaled by S_SCALE (X96).
    uint256[] sharesX96;
    /// @dev Current allocated amount per operator.
    uint256[] currents;
    /// @dev Remaining capacity per operator (max allocatable).
    uint256[] capacities;
    /// @dev Sum of current amounts across all operators.
    uint256 totalCurrent;
}

/// @notice Greedy imbalance math with the same entrypoints as DepositPouringMath.
library DepositAllocatorGreedy {
    using PackedSortKeyLib for PackedSortKey;
    using PackedSortKeyMaxHeapLib for PackedSortKey[];

    // Fixed-point scale (2^96) for share ratios to represent fractional shares as integers.
    uint256 internal constant S_SCALE = uint256(1) << 96;

    /// @dev Expected input invariants:
    ///      - state.capacities[i] > 0
    ///      - state.sharesX96[i] > 0
    ///      - step > 0
    ///      - all arrays in state have the same length n, and entries correspond to the same operators across arrays.
    ///      for i in [0..n).
    function _allocate(
        AllocationState memory state,
        uint256 allocationAmount,
        uint256 step
    ) internal pure returns (uint256 allocated, uint256[] memory allocations) {
        uint256 n = state.sharesX96.length;
        allocations = new uint256[](n);

        PackedSortKey[] memory heap = _maxHeapKeysByImbalanceDesc(state, allocationAmount, step);
        uint256 heapSize = heap.length;

        allocationAmount = _quantize(allocationAmount, step);
        uint256 remainder = allocationAmount;

        while (heapSize > 0 && remainder > 0) {
            PackedSortKey key = heap.popMax(heapSize);
            unchecked {
                --heapSize;
            }
            uint256 opIdx = key.unpackIndex();
            uint256 possible = Math.min(key.unpackImbalance(), _quantize(state.capacities[opIdx], step));
            if (possible == 0) continue;

            uint256 toGive = Math.min(possible, remainder);
            allocations[opIdx] = toGive;
            unchecked {
                remainder -= toGive;
            }
        }

        unchecked {
            allocated = allocationAmount - remainder;
        }
    }

    function _quantize(uint256 value, uint256 step) internal pure returns (uint256) {
        if (step < 2 || value == 0) return value;
        unchecked {
            return value - (value % step);
        }
    }

    function _maxHeapKeysByImbalanceDesc(
        AllocationState memory state,
        uint256 allocationAmount,
        uint256 step
    ) internal pure returns (PackedSortKey[] memory heap) {
        uint256 n = state.sharesX96.length;
        heap = new PackedSortKey[](n);
        uint256 targetTotal = state.totalCurrent + allocationAmount;

        unchecked {
            for (uint256 i; i < n; ++i) {
                uint256 imbalance;
                uint256 target = Math.mulDiv(state.sharesX96[i], targetTotal, S_SCALE, Math.Rounding.Ceil);
                uint256 current = state.currents[i];
                if (target > current) {
                    imbalance = _quantize(target - current, step);
                }
                heap[i] = PackedSortKeyLib.pack(imbalance, i);
            }
        }

        heap.heapify();
    }
}

src/lib/allocator/PackedSortKeyLib.sol

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

/// @notice Packed sort key used for ordering operators by imbalance.
/// @dev Layout:
///      - high 224 bits: imbalance
///      - low 32 bits: reversed index (`INDEX_MASK - idx`) so lower original index wins ties.
///      Assumes `idx <= type(uint32).max`.
///      The packed representation can be compared directly as `uint256`, which makes it reusable across
///      full sorts, insertion sorts and max-heaps without custom comparator logic.
type PackedSortKey is uint256;

/// @notice Helper functions to pack and unpack `PackedSortKey`.
library PackedSortKeyLib {
    uint256 internal constant INDEX_BITS = 32;
    uint256 internal constant INDEX_MASK = type(uint32).max;

    /// @notice Packs imbalance and index into a single sortable key.
    /// @dev Sorting packed keys in descending order produces:
    ///      - imbalance descending
    ///      - index ascending on equal imbalance.
    /// @param imbalance Operator imbalance value.
    /// @param idx Operator index in the source arrays.
    /// @return key Packed key.
    function pack(uint256 imbalance, uint256 idx) internal pure returns (PackedSortKey key) {
        key = PackedSortKey.wrap((imbalance << INDEX_BITS) | (INDEX_MASK - idx));
    }

    /// @notice Unpacks the original operator index from a packed key.
    /// @param key Packed key.
    /// @return idx Original operator index.
    function unpackIndex(PackedSortKey key) internal pure returns (uint256 idx) {
        idx = INDEX_MASK - (PackedSortKey.unwrap(key) & INDEX_MASK);
    }

    /// @notice Unpacks imbalance from a packed key.
    /// @param key Packed key.
    /// @return imbalance Imbalance value.
    function unpackImbalance(PackedSortKey key) internal pure returns (uint256 imbalance) {
        imbalance = PackedSortKey.unwrap(key) >> INDEX_BITS;
    }

    /// @notice Reinterprets a packed key array as uint256[].
    /// @dev `PackedSortKey` wraps `uint256`, so both arrays have identical in-memory layout.
    ///      Useful for passing keys to helpers that accept `uint256[]` (e.g. `Arrays.sort`).
    /// @param keys Packed key array.
    /// @return out Same array viewed as uint256[].
    function asUint256Array(PackedSortKey[] memory keys) internal pure returns (uint256[] memory out) {
        assembly ("memory-safe") {
            out := keys
        }
    }
}

src/lib/allocator/PackedSortKeyMaxHeapLib.sol

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

import { PackedSortKey } from "./PackedSortKeyLib.sol";

/// @notice In-place max-heap helpers for `PackedSortKey[]`.
/// @dev This is a memory-only priority queue primitive specialized for `PackedSortKey`.
///      `PackedSortKey` already encodes the full descending order as a single `uint256`,
///      so heap operations only need plain key comparisons to preserve both priority and tie-break rules.
///
///      A heap is represented as a flat array, but interpreted as a binary tree:
///      - node `i`
///      - left child `2 * i + 1`
///      - right child `2 * i + 2`
///      - parent `(i - 1) / 2`
///
///      Example array:
///      `[9, 5, 7, 1, 2]`
///
///      Tree view:
///      ```text
///              9(0)
///            /      \
///         5(1)      7(2)
///         /  \
///      1(3)  2(4)
///      ```
///
///      Heap property:
///      every parent is greater than or equal to its children.
///      This guarantees that the maximum key is always at index `0`.
///
///      `heapify` does not fully sort the array. It only rearranges it enough so that
///      repeated `popMax` calls return keys in descending order.
///
///      Expected complexity:
///      - `heapify`: O(n)
///      - `popMax`: O(log n)
///      - repeated extraction of `m` elements after `heapify`: O(n + m log n)
library PackedSortKeyMaxHeapLib {
    /// @notice Reorders keys in place into a max-heap.
    /// @dev This is the standard bottom-up heap construction:
    ///      start from the last internal node and repeatedly sift it down until
    ///      every subtree satisfies the heap property.
    ///
    ///      Example:
    ///      `[2, 9, 7, 1, 5]`
    ///
    ///      becomes a valid max-heap such as:
    ///      `[9, 5, 7, 1, 2]`
    ///
    ///      Note that the result is not fully sorted. The only guarantee is that
    ///      the largest key is at the root and every subtree is itself a valid heap.
    /// @param heap Array to reinterpret as a max-heap.
    function heapify(PackedSortKey[] memory heap) internal pure {
        uint256 n = heap.length;
        if (n < 2) return;

        unchecked {
            for (uint256 i = n / 2; i > 0; --i) {
                _siftDown(heap, i - 1, n);
            }
        }
    }

    /// @notice Removes and returns the maximum key from a max-heap prefix.
    /// @dev The heap is assumed to occupy `heap[0:heapSize)`.
    ///      The operation is:
    ///      1. take the root at `heap[0]`
    ///      2. move the last active element to the root
    ///      3. sift the new root down until the heap property is restored
    ///
    ///      Example:
    ///      active heap `[9, 5, 7, 1, 2]`
    ///      - returned key: `9`
    ///      - move `2` to root -> `[2, 5, 7, 1, 2]`
    ///      - sift down -> `[7, 5, 2, 1, 2]`
    ///
    ///      After the call, callers are expected to shrink the active heap by one,
    ///      e.g. by decrementing `heapSize`.
    /// @param heap Heap array.
    /// @param heapSize Current heap size.
    /// @return key Maximum key at the heap root.
    function popMax(PackedSortKey[] memory heap, uint256 heapSize) internal pure returns (PackedSortKey key) {
        key = heap[0];
        if (heapSize < 2) return key;

        unchecked {
            heap[0] = heap[heapSize - 1];
            _siftDown(heap, 0, heapSize - 1);
        }
    }

    /// @dev Restores the heap property starting at `root` and moving toward the leaves.
    ///      The active heap occupies `heap[0:heapSize)`.
    ///
    ///      At each step:
    ///      - compare the current node with its children
    ///      - swap with the larger child if needed
    ///      - continue from the child's position
    ///
    ///      Example:
    ///      if the current subtree is:
    ///      ```text
    ///          2
    ///         / \
    ///        9   7
    ///      ```
    ///      then `2` is swapped with `9`, because the parent must stay greater than
    ///      both children in a max-heap.
    function _siftDown(PackedSortKey[] memory heap, uint256 root, uint256 heapSize) private pure {
        unchecked {
            while (true) {
                uint256 left = 2 * root + 1;
                if (left >= heapSize) return;

                uint256 best = root;
                if (_gt(heap[left], heap[best])) best = left;

                uint256 right = left + 1;
                if (right < heapSize && _gt(heap[right], heap[best])) best = right;
                if (best == root) return;

                PackedSortKey tmp = heap[root];
                heap[root] = heap[best];
                heap[best] = tmp;
                root = best;
            }
        }
    }

    function _gt(PackedSortKey lhs, PackedSortKey rhs) private pure returns (bool) {
        return PackedSortKey.unwrap(lhs) > PackedSortKey.unwrap(rhs);
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 150,
    "enabled": true
  },
  "evmVersion": "osaka",
  "remappings": [
    "@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
    "@openzeppelin/contracts-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable/",
    "forge-std/=node_modules/forge-std/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.