Skip to content
Verified contractExactMIT

ValidatorRewardRouter

Address0xaf2c9f416c4eae74dc4427331b74f64705d8473f
Balance

0 ETH

 

Transactions

2

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,362,766
Creation transaction
0x59eea06005…7be1596a57

src/ValidatorRewardRouter.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

import {Ownership} from "./access/Ownership.sol";
import {ReentrancyGuard} from "./access/ReentrancyGuard.sol";
import {SystemRequestLib} from "./lib/SystemRequestLib.sol";

/**
 * @title ValidatorRewardRouter
 * @notice Withdrawal address for one or more beacon-chain validators.
 *
 *         Two money flows are kept apart:
 *
 *         1. REWARDS - consensus-layer skimming and execution-layer tips that land
 *            here on their own, plus anything pulled with
 *            `requestRewardWithdrawal()` (needed for 0x02 compounding validators,
 *            which are never skimmed automatically). `distributeRewards()` checks
 *            how much actually arrived and splits it between the configured payees
 *            by basis points.
 *
 *         2. PRINCIPAL - staked ETH pulled back from a validator with an EIP-7002
 *            withdrawal request. `requestPartialWithdrawal()` asks the consensus
 *            layer for a given amount and books it as `pendingPrincipal`, which is
 *            excluded from reward distribution. Once the consensus layer credits
 *            this address (minutes to days later - it is never same-block),
 *            `claimPrincipal()` forwards it to `principalReceiver`.
 *
 * @dev Beacon-chain withdrawals credit the balance without executing code, so the
 *      contract can only ever observe `address(this).balance` growing - hence the
 *      explicit accounting instead of hooks.
 *
 *      Trust model: the owner is fully trusted. It sets the payees, the principal
 *      receiver and can reconcile `pendingPrincipal`, so it can redirect funds that
 *      have not been distributed yet. Use a multisig as owner, and keep the
 *      validator's withdrawal credentials pointing at this contract address.
 */
contract ValidatorRewardRouter is Ownership, ReentrancyGuard {
    struct Payee {
        address account;
        uint16 shareBps;
    }

    uint16 public constant TOTAL_BPS = 10_000;
    uint256 public constant MAX_PAYEES = 20;
    /// @dev Bounds the damage a griefing payee can do; failed pushes become claimable.
    uint256 public constant PAYOUT_GAS_LIMIT = 100_000;
    uint256 private constant WEI_PER_GWEI = 1e9;
    /// @dev Max effective balance of a single compounding validator (EIP-7251).
    uint256 public constant DEFAULT_MAX_PENDING_PRINCIPAL = 2048 ether;

    /// @notice EIP-7002 withdrawal-request predeploy (injected so it can be mocked).
    address public immutable withdrawalRequestPredeploy;
    /// @notice EIP-7251 consolidation-request predeploy (injected so it can be mocked).
    address public immutable consolidationRequestPredeploy;

    Payee[] private _payees;

    /// @notice Destination for staked ETH pulled back from validators.
    address public principalReceiver;
    /// @notice Distribution is rejected below this amount, to avoid dust payouts.
    uint256 public minRewardPayout;
    /// @notice ETH (wei) expected back from, or already returned by, the consensus
    ///         layer that belongs to principal rather than to rewards.
    uint256 public pendingPrincipal;
    /// @notice Ceiling for `pendingPrincipal`. Bounds what a single operator request
    ///         can reserve away from reward distribution; raise it for several
    ///         validators sharing this withdrawal address.
    uint256 public maxPendingPrincipal;
    /// @notice Sum of all `unclaimed` balances, reserved from reward distribution.
    uint256 public totalUnclaimed;

    /// @notice Payouts that failed to push and can be pulled later.
    mapping(address account => uint256 amount) public unclaimed;

    event PayeesUpdated(Payee[] payees);
    event PrincipalReceiverUpdated(address indexed previousReceiver, address indexed newReceiver);
    event MinRewardPayoutUpdated(uint256 previousAmount, uint256 newAmount);
    event PendingPrincipalReconciled(uint256 previousAmount, uint256 newAmount);
    event MaxPendingPrincipalUpdated(uint256 previousAmount, uint256 newAmount);
    event RewardsDistributed(uint256 amount, address indexed caller);
    event PayeePaid(address indexed account, uint256 amount);
    event PayeePayoutFailed(address indexed account, uint256 amount);
    event UnclaimedWithdrawn(address indexed account, uint256 amount);
    event PartialWithdrawalRequested(bytes pubkey, uint64 amountGwei, uint256 feePaid);
    event RewardWithdrawalRequested(bytes pubkey, uint64 amountGwei, uint256 feePaid);
    event ConsolidationRequested(bytes sourcePubkey, bytes targetPubkey, uint256 feePaid);
    event FullExitRequested(bytes pubkey, uint64 expectedPrincipalGwei, uint256 feePaid);
    event PrincipalClaimed(address indexed receiver, uint256 amount, uint256 pendingPrincipalLeft);

    error InvalidPayeeCount(uint256 count);
    error ZeroShare(address account);
    error SharesMustSumToTotal(uint256 total);
    error PayeesNotConfigured();
    error RewardsBelowMinimum(uint256 available, uint256 minimum);
    error ZeroAmount();
    error FeeNotCovered(uint256 provided, uint256 required);
    error NothingToClaim();
    error PendingPrincipalCapExceeded(uint256 requested, uint256 cap);
    error NothingUnclaimed(address account);
    error TransferFailed(address account, uint256 amount);

    constructor(
        address initialOwner,
        address withdrawalPredeploy,
        address consolidationPredeploy,
        address initialPrincipalReceiver
    ) Ownership(initialOwner) {
        if (
            withdrawalPredeploy == address(0) || consolidationPredeploy == address(0)
                || initialPrincipalReceiver == address(0)
        ) revert ZeroAddress();

        // Fail at deployment rather than at the first request if an address does not
        // answer the fee getter: both are immutable and cannot be fixed later.
        SystemRequestLib.currentFee(withdrawalPredeploy);
        SystemRequestLib.currentFee(consolidationPredeploy);

        withdrawalRequestPredeploy = withdrawalPredeploy;
        consolidationRequestPredeploy = consolidationPredeploy;
        principalReceiver = initialPrincipalReceiver;
        maxPendingPrincipal = DEFAULT_MAX_PENDING_PRINCIPAL;

        emit PrincipalReceiverUpdated(address(0), initialPrincipalReceiver);
        emit MaxPendingPrincipalUpdated(0, DEFAULT_MAX_PENDING_PRINCIPAL);
    }

    /// @dev Accepts execution-layer tips and manual top-ups. Consensus-layer
    ///      withdrawals land without touching this function.
    receive() external payable {}

    // ---------------------------------------------------------------- rewards

    /// @notice Rewards that have actually arrived and may be split right now.
    function distributableRewards() public view returns (uint256) {
        uint256 reserved = pendingPrincipal + totalUnclaimed;
        uint256 balance = address(this).balance;
        return balance > reserved ? balance - reserved : 0;
    }

    /// @notice Splits the arrived rewards between the payees by their shares.
    /// @dev Permissionless on purpose: funds can only move to configured payees,
    ///      so a keeper bot can trigger it. Rounding dust goes to the last payee.
    function distributeRewards() external nonReentrant returns (uint256 amount) {
        uint256 count = _payees.length;
        if (count == 0) revert PayeesNotConfigured();

        amount = distributableRewards();
        if (amount == 0 || amount < minRewardPayout) revert RewardsBelowMinimum(amount, minRewardPayout);

        uint256 remainder = amount;
        for (uint256 i; i + 1 < count; ++i) {
            Payee memory payee = _payees[i];
            uint256 share = (amount * payee.shareBps) / TOTAL_BPS;
            remainder -= share;
            _payout(payee.account, share);
        }
        _payout(_payees[count - 1].account, remainder);

        emit RewardsDistributed(amount, msg.sender);
    }

    /// @notice Pulls a payout that previously failed to push.
    /// @dev Permissionless like `distributeRewards()`: the credited amount can only
    ///      ever be sent to `account` itself, so a keeper may unblock it.
    function withdrawUnclaimed(address account) external nonReentrant returns (uint256 amount) {
        amount = unclaimed[account];
        if (amount == 0) revert NothingUnclaimed(account);

        unclaimed[account] = 0;
        totalUnclaimed -= amount;

        (bool ok,) = account.call{value: amount}("");
        if (!ok) revert TransferFailed(account, amount);

        emit UnclaimedWithdrawn(account, amount);
    }

    // -------------------------------------------------------------- principal

    /// @notice Asks the consensus layer to move `amountGwei` of a validator's stake
    ///         to this withdrawal address, and books it as principal.
    /// @dev The caller sends the EIP-7002 fee as msg.value so that reward balances are
    ///      never touched; the surplus is refunded.
    ///
    ///      The consensus layer honours the request only for 0x02 (compounding)
    ///      credentials whose execution address is this contract, and caps the payout
    ///      at `balance - 32 ETH - already queued`. A request can therefore deliver
    ///      less than requested, or nothing at all (unknown pubkey, validator active
    ///      for less than 256 epochs, exit already initiated, full partial-withdrawal
    ///      queue) - while the fee is consumed either way. `pendingPrincipal` is
    ///      booked optimistically at the requested amount, so an over-booked request
    ///      keeps rewards reserved until the owner corrects it with
    ///      `setPendingPrincipal()`.
    function requestPartialWithdrawal(bytes calldata pubkey, uint64 amountGwei)
        external
        payable
        onlyOperator
        nonReentrant
    {
        if (amountGwei == 0) revert ZeroAmount();

        uint256 feePaid = _submit(
            withdrawalRequestPredeploy, SystemRequestLib.withdrawalPayload(pubkey, amountGwei)
        );
        _bookPrincipal(uint256(amountGwei) * WEI_PER_GWEI);

        emit PartialWithdrawalRequested(pubkey, amountGwei, feePaid);
    }

    /// @notice Same EIP-7002 request, but the pulled amount is treated as reward
    ///         income instead of principal, so it is split between the payees by
    ///         `distributeRewards()` once it arrives.
    /// @dev This is the way to harvest income from a 0x02 (compounding) validator:
    ///      such validators are not skimmed automatically, their balance keeps
    ///      growing, so the accrued rewards have to be pulled explicitly. Nothing is
    ///      booked as principal here.
    function requestRewardWithdrawal(bytes calldata pubkey, uint64 amountGwei)
        external
        payable
        onlyOperator
        nonReentrant
    {
        if (amountGwei == 0) revert ZeroAmount();

        uint256 feePaid = _submit(
            withdrawalRequestPredeploy, SystemRequestLib.withdrawalPayload(pubkey, amountGwei)
        );

        emit RewardWithdrawalRequested(pubkey, amountGwei, feePaid);
    }

    /// @notice Requests a full validator exit (`amount == 0` in EIP-7002 terms).
    /// @param expectedPrincipalGwei Amount booked as pending principal. The exact
    ///        returned balance is only known on the consensus layer, so reconcile
    ///        with `setPendingPrincipal()` once the real amount has landed.
    function requestFullExit(bytes calldata pubkey, uint64 expectedPrincipalGwei)
        external
        payable
        onlyOperator
        nonReentrant
    {
        uint256 feePaid = _submit(withdrawalRequestPredeploy, SystemRequestLib.withdrawalPayload(pubkey, 0));
        _bookPrincipal(uint256(expectedPrincipalGwei) * WEI_PER_GWEI);

        emit FullExitRequested(pubkey, expectedPrincipalGwei, feePaid);
    }

    /// @notice Sends an EIP-7251 consolidation request on behalf of a validator.
    /// @dev Passing the same pubkey twice is a self-consolidation: it upgrades
    ///      0x01 withdrawal credentials to 0x02 (compounding), which is what makes
    ///      `requestPartialWithdrawal` usable for a pre-Pectra validator. Owner-only,
    ///      because it permanently changes the validator's credential type.
    function requestConsolidation(bytes calldata sourcePubkey, bytes calldata targetPubkey)
        external
        payable
        onlyOwner
        nonReentrant
    {
        uint256 feePaid = _submit(
            consolidationRequestPredeploy, SystemRequestLib.consolidationPayload(sourcePubkey, targetPubkey)
        );

        emit ConsolidationRequested(sourcePubkey, targetPubkey, feePaid);
    }

    /// @notice Principal that has arrived and can be forwarded right now.
    function principalClaimable() public view returns (uint256) {
        uint256 balance = address(this).balance;
        uint256 available = balance > totalUnclaimed ? balance - totalUnclaimed : 0;
        return available < pendingPrincipal ? available : pendingPrincipal;
    }

    /// @notice Forwards the returned stake to `principalReceiver`.
    function claimPrincipal() external onlyOperator nonReentrant returns (uint256 amount) {
        address receiver = principalReceiver;

        amount = principalClaimable();
        if (amount == 0) revert NothingToClaim();

        pendingPrincipal -= amount;

        (bool ok,) = receiver.call{value: amount}("");
        if (!ok) revert TransferFailed(receiver, amount);

        emit PrincipalClaimed(receiver, amount, pendingPrincipal);
    }

    /// @notice Current EIP-7002 fee, to be passed as msg.value by operators.
    function withdrawalRequestFee() external view returns (uint256) {
        return SystemRequestLib.currentFee(withdrawalRequestPredeploy);
    }

    /// @notice Current EIP-7251 fee, to be passed as msg.value by the owner.
    function consolidationRequestFee() external view returns (uint256) {
        return SystemRequestLib.currentFee(consolidationRequestPredeploy);
    }

    // ------------------------------------------------------------------ admin

    /// @notice Replaces the payee set; shares must sum to 10_000 bps.
    function setPayees(Payee[] calldata newPayees) external onlyOwner {
        uint256 count = newPayees.length;
        if (count == 0 || count > MAX_PAYEES) revert InvalidPayeeCount(count);

        delete _payees;

        uint256 total;
        for (uint256 i; i < count; ++i) {
            Payee calldata payee = newPayees[i];
            if (payee.account == address(0)) revert ZeroAddress();
            if (payee.shareBps == 0) revert ZeroShare(payee.account);

            total += payee.shareBps;
            _payees.push(payee);
        }
        if (total != TOTAL_BPS) revert SharesMustSumToTotal(total);

        emit PayeesUpdated(newPayees);
    }

    function setPrincipalReceiver(address receiver) external onlyOwner {
        if (receiver == address(0)) revert ZeroAddress();

        emit PrincipalReceiverUpdated(principalReceiver, receiver);
        principalReceiver = receiver;
    }

    function setMinRewardPayout(uint256 amount) external onlyOwner {
        emit MinRewardPayoutUpdated(minRewardPayout, amount);
        minRewardPayout = amount;
    }

    /// @notice Corrects the principal book-keeping. Required whenever the consensus
    ///         layer returned a different amount than booked - a capped partial
    ///         withdrawal, a full exit that differed from the estimate, or a request
    ///         that was ignored entirely. Until it is corrected, the difference stays
    ///         reserved and is excluded from reward distribution.
    function setPendingPrincipal(uint256 amount) external onlyOwner {
        if (amount > maxPendingPrincipal) revert PendingPrincipalCapExceeded(amount, maxPendingPrincipal);

        emit PendingPrincipalReconciled(pendingPrincipal, amount);
        pendingPrincipal = amount;
    }

    /// @notice Raises or lowers the ceiling on reserved principal. Set it to the
    ///         combined stake of the validators pointing at this address; the lower
    ///         it is, the less a mistyped or malicious withdrawal request can hold
    ///         back from reward distribution.
    function setMaxPendingPrincipal(uint256 amount) external onlyOwner {
        emit MaxPendingPrincipalUpdated(maxPendingPrincipal, amount);
        maxPendingPrincipal = amount;
    }

    // ------------------------------------------------------------------ views

    function payees() external view returns (Payee[] memory) {
        return _payees;
    }

    function payeeCount() external view returns (uint256) {
        return _payees.length;
    }

    // --------------------------------------------------------------- internal

    /// @dev Pays the request fee out of `msg.value` only, so that reward and
    ///      principal balances held by the router are never spent on fees.
    function _submit(address predeploy, bytes memory payload) private returns (uint256 feeWei) {
        feeWei = SystemRequestLib.currentFee(predeploy);
        if (msg.value < feeWei) revert FeeNotCovered(msg.value, feeWei);

        SystemRequestLib.submit(predeploy, payload, feeWei);

        uint256 refund = msg.value - feeWei;
        if (refund != 0) {
            (bool ok,) = msg.sender.call{value: refund}("");
            if (!ok) revert TransferFailed(msg.sender, refund);
        }
    }

    /// @dev Reserving principal is capped so that a mistyped amount (or an operator
    ///      key acting outside its intent) cannot reserve the whole balance away from
    ///      the payees and freeze reward distribution.
    function _bookPrincipal(uint256 amountWei) private {
        uint256 updated = pendingPrincipal + amountWei;
        if (updated > maxPendingPrincipal) revert PendingPrincipalCapExceeded(updated, maxPendingPrincipal);

        pendingPrincipal = updated;
    }

    function _payout(address account, uint256 amount) private {
        if (amount == 0) return;

        (bool ok,) = account.call{value: amount, gas: PAYOUT_GAS_LIMIT}("");
        if (ok) {
            emit PayeePaid(account, amount);
            return;
        }

        unclaimed[account] += amount;
        totalUnclaimed += amount;
        emit PayeePayoutFailed(account, amount);
    }
}

src/access/Ownership.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

/// @notice Two-step ownership transfer plus an operator set for day-to-day calls.
/// @dev The owner configures the router; operators only trigger validator
///      withdrawal requests and principal forwarding.
abstract contract Ownership {
    address public owner;
    address public pendingOwner;

    mapping(address account => bool allowed) public isOperator;

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
    event OperatorSet(address indexed account, bool allowed);

    error NotOwner(address caller);
    error NotPendingOwner(address caller);
    error NotOperator(address caller);
    error ZeroAddress();

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner(msg.sender);
        _;
    }

    /// @dev The owner is always allowed to act as an operator.
    modifier onlyOperator() {
        if (msg.sender != owner && !isOperator[msg.sender]) revert NotOperator(msg.sender);
        _;
    }

    constructor(address initialOwner) {
        if (initialOwner == address(0)) revert ZeroAddress();
        owner = initialOwner;
        emit OwnershipTransferred(address(0), initialOwner);
    }

    function transferOwnership(address newOwner) external onlyOwner {
        if (newOwner == address(0)) revert ZeroAddress();
        pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner, newOwner);
    }

    function acceptOwnership() external {
        if (msg.sender != pendingOwner) revert NotPendingOwner(msg.sender);

        address previousOwner = owner;
        owner = msg.sender;
        pendingOwner = address(0);
        emit OwnershipTransferred(previousOwner, msg.sender);
    }

    function setOperator(address account, bool allowed) external onlyOwner {
        if (account == address(0)) revert ZeroAddress();
        isOperator[account] = allowed;
        emit OperatorSet(account, allowed);
    }
}

src/access/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

/// @notice Minimal non-reentrancy guard for the ETH-moving entry points.
abstract contract ReentrancyGuard {
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status = NOT_ENTERED;

    error Reentrancy();

    modifier nonReentrant() {
        if (_status == ENTERED) revert Reentrancy();
        _status = ENTERED;
        _;
        _status = NOT_ENTERED;
    }
}

src/lib/SystemRequestLib.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

/// @notice Shared wrapper around the Pectra request predeploys, which both expose
///         the same interface: empty calldata reads the current fee, a request is
///         raw calldata paid for with `msg.value`.
/// @dev Mainnet addresses:
///      - EIP-7002 withdrawal requests:    0x00000961Ef480Eb55e80D19ad83579A64c007002
///      - EIP-7251 consolidation requests: 0x0000BBdDc7CE488642fb579F8B00f3a590007251
///      The consensus layer only honours a request whose source address equals the
///      execution address in the validator's withdrawal credentials, so the caller
///      must be the contract those credentials point at.
library SystemRequestLib {
    uint256 internal constant PUBKEY_LENGTH = 48;

    error InvalidPubkeyLength(uint256 length);
    error FeeQueryFailed();
    error RequestRejected();

    /// @notice Reads the current per-request fee (empty calldata = fee getter).
    function currentFee(address predeploy) internal view returns (uint256 feeWei) {
        (bool ok, bytes memory data) = predeploy.staticcall("");
        if (!ok || data.length != 32) revert FeeQueryFailed();
        feeWei = abi.decode(data, (uint256));
    }

    /// @dev Sends exactly `feeWei`; the predeploy keeps the whole value, so any
    ///      excess would be burned. Callers must pass the fee they just read.
    function submit(address predeploy, bytes memory payload, uint256 feeWei) internal {
        (bool ok,) = predeploy.call{value: feeWei}(payload);
        if (!ok) revert RequestRejected();
    }

    /// @notice 48-byte pubkey + 8-byte big-endian amount in gwei (0 = full exit).
    function withdrawalPayload(bytes calldata pubkey, uint64 amountGwei) internal pure returns (bytes memory) {
        _checkPubkey(pubkey);
        return abi.encodePacked(pubkey, amountGwei);
    }

    /// @notice 48-byte source pubkey + 48-byte target pubkey.
    /// @dev source == target is a self-consolidation, which upgrades 0x01
    ///      withdrawal credentials to 0x02 (compounding) and is what unlocks
    ///      partial withdrawals for an existing validator.
    function consolidationPayload(bytes calldata sourcePubkey, bytes calldata targetPubkey)
        internal
        pure
        returns (bytes memory)
    {
        _checkPubkey(sourcePubkey);
        _checkPubkey(targetPubkey);
        return abi.encodePacked(sourcePubkey, targetPubkey);
    }

    function _checkPubkey(bytes calldata pubkey) private pure {
        if (pubkey.length != PUBKEY_LENGTH) revert InvalidPubkeyLength(pubkey.length);
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.