编译器
0.8.13+commit.abaa5c0e
文件 1 的 22:Address.sol
pragma solidity ^0.8.1;
library Address {
function isContract(address account) internal view returns (bool) {
return account.code.length > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
文件 2 的 22:AuthorizedFeeRecipient.sol
pragma solidity >=0.8.10;
import "./interfaces/IFeeDispatcher.sol";
import "./libs/DispatchersStorageLib.sol";
import "./interfaces/IFeeRecipient.sol";
contract AuthorizedFeeRecipient is IFeeRecipient {
bool internal initialized;
IFeeDispatcher internal dispatcher;
bytes32 internal publicKeyRoot;
address internal stakingContract;
error AlreadyInitialized();
error Unauthorized();
function init(address _dispatcher, bytes32 _publicKeyRoot) external {
if (initialized) {
revert AlreadyInitialized();
}
initialized = true;
dispatcher = IFeeDispatcher(_dispatcher);
publicKeyRoot = _publicKeyRoot;
stakingContract = msg.sender;
}
receive() external payable {}
fallback() external payable {}
function withdraw() external {
if (msg.sender != stakingContract) {
revert Unauthorized();
}
dispatcher.dispatch{value: address(this).balance}(publicKeyRoot);
}
function getPublicKeyRoot() external view returns (bytes32) {
return publicKeyRoot;
}
function getWithdrawer() external view returns (address) {
return dispatcher.getWithdrawer(publicKeyRoot);
}
}
文件 3 的 22:BytesLib.sol
pragma solidity >=0.8.10;
library BytesLib {
function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) {
bytes memory tempBytes;
assembly {
tempBytes := mload(0x40)
let length := mload(_preBytes)
mstore(tempBytes, length)
let mc := add(tempBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
mc := end
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(
0x40,
and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31)
)
)
}
return tempBytes;
}
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
tempBytes := mload(0x40)
let lengthmod := and(_length, 31)
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
mstore(0x40, and(add(mc, 31), not(31)))
}
default {
tempBytes := mload(0x40)
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
}
文件 4 的 22:Clones.sol
pragma solidity ^0.8.0;
library Clones {
function clone(address implementation) internal returns (address instance) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
function predictDeterministicAddress(
address implementation,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
function predictDeterministicAddress(address implementation, bytes32 salt)
internal
view
returns (address predicted)
{
return predictDeterministicAddress(implementation, salt, address(this));
}
}
文件 5 的 22:ConsensusLayerFeeDispatcher.sol
pragma solidity >=0.8.10;
import "./libs/DispatchersStorageLib.sol";
import "./interfaces/IStakingContractFeeDetails.sol";
import "./interfaces/IFeeDispatcher.sol";
contract ConsensusLayerFeeDispatcher is IFeeDispatcher {
using DispatchersStorageLib for bytes32;
event Withdrawal(
address indexed withdrawer,
address indexed feeRecipient,
bytes32 pubKeyRoot,
uint256 rewards,
uint256 nodeOperatorFee,
uint256 treasuryFee
);
error TreasuryReceiveError(bytes errorData);
error FeeRecipientReceiveError(bytes errorData);
error WithdrawerReceiveError(bytes errorData);
error ZeroBalanceWithdrawal();
error AlreadyInitialized();
error InvalidCall();
bytes32 internal constant STAKING_CONTRACT_ADDRESS_SLOT =
keccak256("ConsensusLayerFeeRecipient.stakingContractAddress");
uint256 internal constant BASIS_POINTS = 10_000;
bytes32 internal constant VERSION_SLOT = keccak256("ConsensusLayerFeeRecipient.version");
modifier init(uint256 _version) {
if (_version != VERSION_SLOT.getUint256() + 1) {
revert AlreadyInitialized();
}
VERSION_SLOT.setUint256(_version);
_;
}
constructor(uint256 _version) {
VERSION_SLOT.setUint256(_version);
}
function initCLD(address _stakingContract) external init(1) {
STAKING_CONTRACT_ADDRESS_SLOT.setAddress(_stakingContract);
}
function dispatch(bytes32 _publicKeyRoot) external payable {
IStakingContractFeeDetails stakingContract = IStakingContractFeeDetails(
STAKING_CONTRACT_ADDRESS_SLOT.getAddress()
);
uint256 balance = address(this).balance;
if (balance == 0) {
revert ZeroBalanceWithdrawal();
}
bool exitRequested = stakingContract.getExitRequestedFromRoot(_publicKeyRoot);
bool withdrawn = stakingContract.getWithdrawnFromPublicKeyRoot(_publicKeyRoot);
uint256 nonExemptBalance = balance;
if (exitRequested && balance >= 31 ether && !withdrawn) {
uint256 exemption = nonExemptBalance > 32 ether ? 32 ether : nonExemptBalance;
nonExemptBalance -= exemption;
stakingContract.toggleWithdrawnFromPublicKeyRoot(_publicKeyRoot);
}
uint256 globalFee = (nonExemptBalance * stakingContract.getGlobalFee()) / BASIS_POINTS;
uint256 operatorFee = (globalFee * stakingContract.getOperatorFee()) / BASIS_POINTS;
address operator = stakingContract.getOperatorFeeRecipient(_publicKeyRoot);
address treasury = stakingContract.getTreasury();
address withdrawer = stakingContract.getWithdrawerFromPublicKeyRoot(_publicKeyRoot);
(bool status, bytes memory data) = withdrawer.call{value: balance - globalFee}("");
if (status == false) {
revert WithdrawerReceiveError(data);
}
if (globalFee > 0) {
(status, data) = treasury.call{value: globalFee - operatorFee}("");
if (status == false) {
revert TreasuryReceiveError(data);
}
}
if (operatorFee > 0) {
(status, data) = operator.call{value: operatorFee}("");
if (status == false) {
revert FeeRecipientReceiveError(data);
}
}
emit Withdrawal(
withdrawer,
operator,
_publicKeyRoot,
balance - globalFee,
operatorFee,
globalFee - operatorFee
);
}
function getStakingContract() external view returns (address) {
return STAKING_CONTRACT_ADDRESS_SLOT.getAddress();
}
function getWithdrawer(bytes32 _publicKeyRoot) external view returns (address) {
IStakingContractFeeDetails stakingContract = IStakingContractFeeDetails(
STAKING_CONTRACT_ADDRESS_SLOT.getAddress()
);
return stakingContract.getWithdrawerFromPublicKeyRoot(_publicKeyRoot);
}
receive() external payable {
revert InvalidCall();
}
fallback() external payable {
revert InvalidCall();
}
}
文件 6 的 22:DispatchersStorageLib.sol
pragma solidity >=0.8.10;
library DispatchersStorageLib {
function getUint256(bytes32 position) internal view returns (uint256 data) {
assembly {
data := sload(position)
}
}
function setUint256(bytes32 position, uint256 data) internal {
assembly {
sstore(position, data)
}
}
function getAddress(bytes32 position) internal view returns (address data) {
assembly {
data := sload(position)
}
}
function setAddress(bytes32 position, address data) internal {
assembly {
sstore(position, data)
}
}
}
文件 7 的 22:ERC1967Proxy.sol
pragma solidity ^0.8.0;
import "../Proxy.sol";
import "./ERC1967Upgrade.sol";
contract ERC1967Proxy is Proxy, ERC1967Upgrade {
constructor(address _logic, bytes memory _data) payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_upgradeToAndCall(_logic, _data, false);
}
function _implementation() internal view virtual override returns (address impl) {
return ERC1967Upgrade._getImplementation();
}
}
文件 8 的 22:ERC1967Upgrade.sol
pragma solidity ^0.8.2;
import "../beacon/IBeacon.sol";
import "../../interfaces/draft-IERC1822.sol";
import "../../utils/Address.sol";
import "../../utils/StorageSlot.sol";
abstract contract ERC1967Upgrade {
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
event Upgraded(address indexed implementation);
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
function _upgradeToAndCallUUPS(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
event AdminChanged(address previousAdmin, address newAdmin);
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
event BeaconUpgraded(address indexed beacon);
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
function _setBeacon(address newBeacon) private {
require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
文件 9 的 22:ExecutionLayerFeeDispatcher.sol
pragma solidity >=0.8.10;
import "./libs/DispatchersStorageLib.sol";
import "./interfaces/IStakingContractFeeDetails.sol";
import "./interfaces/IFeeDispatcher.sol";
contract ExecutionLayerFeeDispatcher is IFeeDispatcher {
using DispatchersStorageLib for bytes32;
event Withdrawal(
address indexed withdrawer,
address indexed feeRecipient,
bytes32 pubKeyRoot,
uint256 rewards,
uint256 nodeOperatorFee,
uint256 treasuryFee
);
error TreasuryReceiveError(bytes errorData);
error FeeRecipientReceiveError(bytes errorData);
error WithdrawerReceiveError(bytes errorData);
error ZeroBalanceWithdrawal();
error AlreadyInitialized();
error InvalidCall();
bytes32 internal constant STAKING_CONTRACT_ADDRESS_SLOT =
keccak256("ExecutionLayerFeeRecipient.stakingContractAddress");
uint256 internal constant BASIS_POINTS = 10_000;
bytes32 internal constant VERSION_SLOT = keccak256("ExecutionLayerFeeRecipient.version");
modifier init(uint256 _version) {
if (_version != VERSION_SLOT.getUint256() + 1) {
revert AlreadyInitialized();
}
VERSION_SLOT.setUint256(_version);
_;
}
constructor(uint256 _version) {
VERSION_SLOT.setUint256(_version);
}
function initELD(address _stakingContract) external init(1) {
STAKING_CONTRACT_ADDRESS_SLOT.setAddress(_stakingContract);
}
function dispatch(bytes32 _publicKeyRoot) external payable {
uint256 balance = address(this).balance;
if (balance == 0) {
revert ZeroBalanceWithdrawal();
}
IStakingContractFeeDetails stakingContract = IStakingContractFeeDetails(
STAKING_CONTRACT_ADDRESS_SLOT.getAddress()
);
address withdrawer = stakingContract.getWithdrawerFromPublicKeyRoot(_publicKeyRoot);
address operator = stakingContract.getOperatorFeeRecipient(_publicKeyRoot);
address treasury = stakingContract.getTreasury();
uint256 globalFee = (balance * stakingContract.getGlobalFee()) / BASIS_POINTS;
uint256 operatorFee = (globalFee * stakingContract.getOperatorFee()) / BASIS_POINTS;
(bool status, bytes memory data) = withdrawer.call{value: balance - globalFee}("");
if (status == false) {
revert WithdrawerReceiveError(data);
}
if (globalFee > 0) {
(status, data) = treasury.call{value: globalFee - operatorFee}("");
if (status == false) {
revert TreasuryReceiveError(data);
}
}
if (operatorFee > 0) {
(status, data) = operator.call{value: operatorFee}("");
if (status == false) {
revert FeeRecipientReceiveError(data);
}
}
emit Withdrawal(
withdrawer,
operator,
_publicKeyRoot,
balance - globalFee,
operatorFee,
globalFee - operatorFee
);
}
function getStakingContract() external view returns (address) {
return STAKING_CONTRACT_ADDRESS_SLOT.getAddress();
}
function getWithdrawer(bytes32 _publicKeyRoot) external view returns (address) {
IStakingContractFeeDetails stakingContract = IStakingContractFeeDetails(
STAKING_CONTRACT_ADDRESS_SLOT.getAddress()
);
return stakingContract.getWithdrawerFromPublicKeyRoot(_publicKeyRoot);
}
receive() external payable {
revert InvalidCall();
}
fallback() external payable {
revert InvalidCall();
}
}
文件 10 的 22:FeeRecipient.sol
pragma solidity >=0.8.10;
import "./interfaces/IFeeDispatcher.sol";
contract FeeRecipient {
bool internal initialized;
IFeeDispatcher internal dispatcher;
bytes32 internal publicKeyRoot;
error AlreadyInitialized();
function init(address _dispatcher, bytes32 _publicKeyRoot) external {
if (initialized) {
revert AlreadyInitialized();
}
initialized = true;
dispatcher = IFeeDispatcher(_dispatcher);
publicKeyRoot = _publicKeyRoot;
}
receive() external payable {}
fallback() external payable {}
function withdraw() external {
dispatcher.dispatch{value: address(this).balance}(publicKeyRoot);
}
function getPublicKeyRoot() external view returns (bytes32) {
return publicKeyRoot;
}
function getWithdrawer() external view returns (address) {
return dispatcher.getWithdrawer(publicKeyRoot);
}
}
文件 11 的 22:IBeacon.sol
pragma solidity ^0.8.0;
interface IBeacon {
function implementation() external view returns (address);
}
文件 12 的 22:IDepositContract.sol
pragma solidity >=0.8.10;
interface IDepositContract {
function deposit(
bytes calldata pubkey,
bytes calldata withdrawalCredentials,
bytes calldata signature,
bytes32 depositDataRoot
) external payable;
}
文件 13 的 22:IFeeDispatcher.sol
pragma solidity >=0.8.10;
interface IFeeDispatcher {
function dispatch(bytes32 _publicKeyRoot) external payable;
function getWithdrawer(bytes32 _publicKeyRoot) external view returns (address);
}
文件 14 的 22:IFeeRecipient.sol
pragma solidity >=0.8.10;
interface IFeeRecipient {
function init(address _dispatcher, bytes32 _publicKeyRoot) external;
function withdraw() external;
}
文件 15 的 22:IStakingContractFeeDetails.sol
pragma solidity >=0.8.10;
interface IStakingContractFeeDetails {
function getWithdrawerFromPublicKeyRoot(bytes32 _publicKeyRoot) external view returns (address);
function getTreasury() external view returns (address);
function getOperatorFeeRecipient(bytes32 pubKeyRoot) external view returns (address);
function getGlobalFee() external view returns (uint256);
function getOperatorFee() external view returns (uint256);
function getExitRequestedFromRoot(bytes32 _publicKeyRoot) external view returns (bool);
function getWithdrawnFromPublicKeyRoot(bytes32 _publicKeyRoot) external view returns (bool);
function toggleWithdrawnFromPublicKeyRoot(bytes32 _publicKeyRoot) external;
}
文件 16 的 22:Proxy.sol
pragma solidity ^0.8.0;
abstract contract Proxy {
function _delegate(address implementation) internal virtual {
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
function _implementation() internal view virtual returns (address);
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
fallback() external payable virtual {
_fallback();
}
receive() external payable virtual {
_fallback();
}
function _beforeFallback() internal virtual {}
}
文件 17 的 22:StakingContract.sol
pragma solidity >=0.8.10;
import "./libs/BytesLib.sol";
import "./interfaces/IFeeRecipient.sol";
import "./interfaces/IDepositContract.sol";
import "./libs/StakingContractStorageLib.sol";
import "@openzeppelin/contracts/proxy/Clones.sol";
contract StakingContract {
using StakingContractStorageLib for bytes32;
uint256 internal constant EXECUTION_LAYER_SALT_PREFIX = 0;
uint256 internal constant CONSENSUS_LAYER_SALT_PREFIX = 1;
uint256 public constant SIGNATURE_LENGTH = 96;
uint256 public constant PUBLIC_KEY_LENGTH = 48;
uint256 public constant DEPOSIT_SIZE = 32 ether;
uint256 constant DEPOSIT_SIZE_AMOUNT_LITTLEENDIAN64 =
0x0040597307000000000000000000000000000000000000000000000000000000;
uint256 internal constant BASIS_POINTS = 10_000;
uint256 internal constant WITHDRAWAL_CREDENTIAL_PREFIX_01 =
0x0100000000000000000000000000000000000000000000000000000000000000;
error Forbidden();
error InvalidFee();
error Deactivated();
error NoOperators();
error InvalidCall();
error Unauthorized();
error DepositFailure();
error DepositsStopped();
error InvalidArgument();
error UnsortedIndexes();
error InvalidPublicKeys();
error InvalidSignatures();
error InvalidWithdrawer();
error InvalidZeroAddress();
error AlreadyInitialized();
error InvalidDepositValue();
error NotEnoughValidators();
error InvalidValidatorCount();
error DuplicateValidatorKey(bytes);
error FundedValidatorDeletionAttempt();
error OperatorLimitTooHigh(uint256 limit, uint256 keyCount);
error MaximumOperatorCountAlreadyReached();
error LastEditAfterSnapshot();
error PublicKeyNotInContract();
struct ValidatorAllocationCache {
bool used;
uint8 operatorIndex;
uint32 funded;
uint32 toDeposit;
uint32 available;
}
event Deposit(address indexed caller, address indexed withdrawer, bytes publicKey, bytes signature);
event ValidatorKeysAdded(uint256 indexed operatorIndex, bytes publicKeys, bytes signatures);
event ValidatorKeyRemoved(uint256 indexed operatorIndex, bytes publicKey);
event ChangedWithdrawer(bytes publicKey, address newWithdrawer);
event ChangedOperatorLimit(uint256 operatorIndex, uint256 limit);
event ChangedTreasury(address newTreasury);
event ChangedGlobalFee(uint256 newGlobalFee);
event ChangedOperatorFee(uint256 newOperatorFee);
event ChangedAdmin(address newAdmin);
event ChangedDepositsStopped(bool isStopped);
event NewOperator(address operatorAddress, address feeRecipientAddress, uint256 index);
event ChangedOperatorAddresses(uint256 operatorIndex, address operatorAddress, address feeRecipientAddress);
event DeactivatedOperator(uint256 _operatorIndex);
event ActivatedOperator(uint256 _operatorIndex);
event SetWithdrawerCustomizationStatus(bool _status);
event ExitRequest(address caller, bytes pubkey);
event ValidatorsEdited(uint256 blockNumber);
modifier init(uint256 _version) {
if (_version != StakingContractStorageLib.getVersion() + 1) {
revert AlreadyInitialized();
}
StakingContractStorageLib.setVersion(_version);
_;
}
modifier onlyAdmin() {
if (msg.sender != StakingContractStorageLib.getAdmin()) {
revert Unauthorized();
}
_;
}
modifier onlyActiveOperatorOrAdmin(uint256 _operatorIndex) {
if (msg.sender == StakingContractStorageLib.getAdmin()) {
_;
} else {
_onlyActiveOperator(_operatorIndex);
_;
}
}
modifier onlyActiveOperator(uint256 _operatorIndex) {
_onlyActiveOperator(_operatorIndex);
_;
}
modifier onlyActiveOperatorFeeRecipient(uint256 _operatorIndex) {
StakingContractStorageLib.OperatorInfo storage operatorInfo = StakingContractStorageLib.getOperators().value[
_operatorIndex
];
if (operatorInfo.deactivated) {
revert Deactivated();
}
if (msg.sender != operatorInfo.feeRecipient) {
revert Unauthorized();
}
_;
}
function deposit() external payable {
_deposit();
}
receive() external payable {
_deposit();
}
fallback() external payable {
revert InvalidCall();
}
function initialize_1(
address _admin,
address _treasury,
address _depositContract,
address _elDispatcher,
address _clDispatcher,
address _feeRecipientImplementation,
uint256 _globalFee,
uint256 _operatorFee,
uint256 globalCommissionLimitBPS,
uint256 operatorCommissionLimitBPS
) external init(1) {
_checkAddress(_admin);
StakingContractStorageLib.setAdmin(_admin);
_checkAddress(_treasury);
StakingContractStorageLib.setTreasury(_treasury);
if (_globalFee > BASIS_POINTS) {
revert InvalidFee();
}
StakingContractStorageLib.setGlobalFee(_globalFee);
if (_operatorFee > BASIS_POINTS) {
revert InvalidFee();
}
StakingContractStorageLib.setOperatorFee(_operatorFee);
_checkAddress(_elDispatcher);
StakingContractStorageLib.setELDispatcher(_elDispatcher);
_checkAddress(_clDispatcher);
StakingContractStorageLib.setCLDispatcher(_clDispatcher);
_checkAddress(_depositContract);
StakingContractStorageLib.setDepositContract(_depositContract);
_checkAddress(_feeRecipientImplementation);
StakingContractStorageLib.setFeeRecipientImplementation(_feeRecipientImplementation);
initialize_2(globalCommissionLimitBPS, operatorCommissionLimitBPS);
}
function initialize_2(uint256 globalCommissionLimitBPS, uint256 operatorCommissionLimitBPS) public init(2) {
if (globalCommissionLimitBPS > BASIS_POINTS) {
revert InvalidFee();
}
StakingContractStorageLib.setGlobalCommissionLimit(globalCommissionLimitBPS);
if (operatorCommissionLimitBPS > BASIS_POINTS) {
revert InvalidFee();
}
StakingContractStorageLib.setOperatorCommissionLimit(operatorCommissionLimitBPS);
}
function setWithdrawerCustomizationEnabled(bool _enabled) external onlyAdmin {
StakingContractStorageLib.setWithdrawerCustomizationEnabled(_enabled);
emit SetWithdrawerCustomizationStatus(_enabled);
}
function getAdmin() external view returns (address) {
return StakingContractStorageLib.getAdmin();
}
function setTreasury(address _newTreasury) external onlyAdmin {
emit ChangedTreasury(_newTreasury);
StakingContractStorageLib.setTreasury(_newTreasury);
}
function getTreasury() external view returns (address) {
return StakingContractStorageLib.getTreasury();
}
function getGlobalFee() external view returns (uint256) {
return StakingContractStorageLib.getGlobalFee();
}
function getOperatorFee() external view returns (uint256) {
return StakingContractStorageLib.getOperatorFee();
}
function getELFeeRecipient(bytes calldata _publicKey) external view returns (address) {
return _getDeterministicReceiver(_publicKey, EXECUTION_LAYER_SALT_PREFIX);
}
function getCLFeeRecipient(bytes calldata _publicKey) external view returns (address) {
return _getDeterministicReceiver(_publicKey, CONSENSUS_LAYER_SALT_PREFIX);
}
function getOperatorFeeRecipient(bytes32 pubKeyRoot) external view returns (address) {
if (StakingContractStorageLib.getOperatorIndexPerValidator().value[pubKeyRoot].enabled == false) {
revert PublicKeyNotInContract();
}
return
StakingContractStorageLib
.getOperators()
.value[StakingContractStorageLib.getOperatorIndexPerValidator().value[pubKeyRoot].operatorIndex]
.feeRecipient;
}
function getWithdrawer(bytes calldata _publicKey) external view returns (address) {
return _getWithdrawer(_getPubKeyRoot(_publicKey));
}
function getWithdrawerFromPublicKeyRoot(bytes32 _publicKeyRoot) external view returns (address) {
return _getWithdrawer(_publicKeyRoot);
}
function getExitRequestedFromRoot(bytes32 _publicKeyRoot) external view returns (bool) {
return _getExitRequest(_publicKeyRoot);
}
function getWithdrawnFromPublicKeyRoot(bytes32 _publicKeyRoot) external view returns (bool) {
return StakingContractStorageLib.getWithdrawnMap().value[_publicKeyRoot];
}
function getEnabledFromPublicKeyRoot(bytes32 _publicKeyRoot) external view returns (bool) {
return StakingContractStorageLib.getOperatorIndexPerValidator().value[_publicKeyRoot].enabled;
}
function toggleWithdrawnFromPublicKeyRoot(bytes32 _publicKeyRoot) external {
if (msg.sender != StakingContractStorageLib.getCLDispatcher()) {
revert Unauthorized();
}
StakingContractStorageLib.getWithdrawnMap().value[_publicKeyRoot] = true;
}
function getDepositsStopped() external view returns (bool) {
return StakingContractStorageLib.getDepositStopped();
}
function getOperator(uint256 _operatorIndex)
external
view
returns (
address operatorAddress,
address feeRecipientAddress,
uint256 limit,
uint256 keys,
uint256 funded,
uint256 available,
bool deactivated
)
{
StakingContractStorageLib.OperatorsSlot storage operators = StakingContractStorageLib.getOperators();
if (_operatorIndex < operators.value.length) {
StakingContractStorageLib.ValidatorsFundingInfo memory _operatorInfo = StakingContractStorageLib
.getValidatorsFundingInfo(_operatorIndex);
StakingContractStorageLib.OperatorInfo storage _operator = operators.value[_operatorIndex];
(operatorAddress, feeRecipientAddress, limit, keys, deactivated) = (
_operator.operator,
_operator.feeRecipient,
_operator.limit,
_operator.publicKeys.length,
_operator.deactivated
);
(funded, available) = (_operatorInfo.funded, _operatorInfo.availableKeys);
}
}
function getValidator(uint256 _operatorIndex, uint256 _validatorIndex)
external
view
returns (
bytes memory publicKey,
bytes memory signature,
address withdrawer,
bool funded
)
{
StakingContractStorageLib.OperatorsSlot storage operators = StakingContractStorageLib.getOperators();
publicKey = operators.value[_operatorIndex].publicKeys[_validatorIndex];
signature = operators.value[_operatorIndex].signatures[_validatorIndex];
withdrawer = _getWithdrawer(_getPubKeyRoot(publicKey));
funded = _validatorIndex < StakingContractStorageLib.getValidatorsFundingInfo(_operatorIndex).funded;
}
function getAvailableValidatorCount() external view returns (uint256) {
return StakingContractStorageLib.getTotalAvailableValidators();
}
function transferOwnership(address _newAdmin) external onlyAdmin {
StakingContractStorageLib.setPendingAdmin(_newAdmin);
}
function acceptOwnership() external {
address newAdmin = StakingContractStorageLib.getPendingAdmin();
if (msg.sender != newAdmin) {
revert Unauthorized();
}
StakingContractStorageLib.setAdmin(newAdmin);
StakingContractStorageLib.setPendingAdmin(address(0));
emit ChangedAdmin(newAdmin);
}
function getPendingAdmin() external view returns (address) {
return StakingContractStorageLib.getPendingAdmin();
}
function addOperator(address _operatorAddress, address _feeRecipientAddress) external onlyAdmin returns (uint256) {
StakingContractStorageLib.OperatorsSlot storage operators = StakingContractStorageLib.getOperators();
StakingContractStorageLib.OperatorInfo memory newOperator;
if (operators.value.length == 1) {
revert MaximumOperatorCountAlreadyReached();
}
newOperator.operator = _operatorAddress;
newOperator.feeRecipient = _feeRecipientAddress;
operators.value.push(newOperator);
uint256 operatorIndex = operators.value.length - 1;
emit NewOperator(_operatorAddress, _feeRecipientAddress, operatorIndex);
return operatorIndex;
}
function setOperatorAddresses(
uint256 _operatorIndex,
address _operatorAddress,
address _feeRecipientAddress
) external onlyActiveOperatorFeeRecipient(_operatorIndex) {
_checkAddress(_operatorAddress);
_checkAddress(_feeRecipientAddress);
StakingContractStorageLib.OperatorsSlot storage operators = StakingContractStorageLib.getOperators();
operators.value[_operatorIndex].operator = _operatorAddress;
operators.value[_operatorIndex].feeRecipient = _feeRecipientAddress;
emit ChangedOperatorAddresses(_operatorIndex, _operatorAddress, _feeRecipientAddress);
}
function setWithdrawer(bytes calldata _publicKey, address _newWithdrawer) external {
if (!StakingContractStorageLib.getWithdrawerCustomizationEnabled()) {
revert Forbidden();
}
_checkAddress(_newWithdrawer);
bytes32 pubkeyRoot = _getPubKeyRoot(_publicKey);
StakingContractStorageLib.WithdrawersSlot storage withdrawers = StakingContractStorageLib.getWithdrawers();
if (withdrawers.value[pubkeyRoot] != msg.sender) {
revert Unauthorized();
}
emit ChangedWithdrawer(_publicKey, _newWithdrawer);
withdrawers.value[pubkeyRoot] = _newWithdrawer;
}
function setOperatorLimit(
uint256 _operatorIndex,
uint256 _limit,
uint256 _snapshot
) external onlyAdmin {
StakingContractStorageLib.OperatorsSlot storage operators = StakingContractStorageLib.getOperators();
if (operators.value[_operatorIndex].deactivated) {
revert Deactivated();
}
uint256 publicKeyCount = operators.value[_operatorIndex].publicKeys.length;
if (publicKeyCount < _limit) {
revert OperatorLimitTooHigh(_limit, publicKeyCount);
}
if (
operators.value[_operatorIndex].limit < _limit &&
StakingContractStorageLib.getLastValidatorEdit() > _snapshot
) {
revert LastEditAfterSnapshot();
}
operators.value[_operatorIndex].limit = _limit;
_updateAvailableValidatorCount(_operatorIndex);
emit ChangedOperatorLimit(_operatorIndex, _limit);
}
function deactivateOperator(uint256 _operatorIndex, address _temporaryFeeRecipient) external onlyAdmin {
StakingContractStorageLib.OperatorsSlot storage operators = StakingContractStorageLib.getOperators();
operators.value[_operatorIndex].limit = 0;
emit ChangedOperatorLimit(_operatorIndex, 0);
operators.value[_operatorIndex].deactivated = true;
emit DeactivatedOperator(_operatorIndex);
operators.value[_operatorIndex].feeRecipient = _temporaryFeeRecipient;
emit ChangedOperatorAddresses(_operatorIndex, operators.value[_operatorIndex].operator, _temporaryFeeRecipient);
_updateAvailableValidatorCount(_operatorIndex);
}
function activateOperator(uint256 _operatorIndex, address _newFeeRecipient) external onlyAdmin {
StakingContractStorageLib.OperatorsSlot storage operators = StakingContractStorageLib.getOperators();
operators.value[_operatorIndex].deactivated = false;
emit ActivatedOperator(_operatorIndex);
operators.value[_operatorIndex].feeRecipient = _newFeeRecipient;
emit ChangedOperatorAddresses(_operatorIndex, operators.value[_operatorIndex].operator, _newFeeRecipient);
}
function setOperatorFee(uint256 _operatorFee) external onlyAdmin {
if (_operatorFee > StakingContractStorageLib.getOperatorCommissionLimit()) {
revert InvalidFee();
}
StakingContractStorageLib.setOperatorFee(_operatorFee);
emit ChangedOperatorFee(_operatorFee);
}
function setGlobalFee(uint256 _globalFee) external onlyAdmin {
if (_globalFee > StakingContractStorageLib.getGlobalCommissionLimit()) {
revert InvalidFee();
}
StakingContractStorageLib.setGlobalFee(_globalFee);
emit ChangedGlobalFee(_globalFee);
}
function addValidators(
uint256 _operatorIndex,
uint256 _keyCount,
bytes calldata _publicKeys,
bytes calldata _signatures
) external onlyActiveOperator(_operatorIndex) {
if (_keyCount == 0) {
revert InvalidArgument();
}
if (_publicKeys.length % PUBLIC_KEY_LENGTH != 0 || _publicKeys.length / PUBLIC_KEY_LENGTH != _keyCount) {
revert InvalidPublicKeys();
}
if (_signatures.length % SIGNATURE_LENGTH != 0 || _signatures.length / SIGNATURE_LENGTH != _keyCount) {
revert InvalidSignatures();
}
StakingContractStorageLib.OperatorsSlot storage operators = StakingContractStorageLib.getOperators();
StakingContractStorageLib.OperatorIndexPerValidatorSlot
storage operatorIndexPerValidator = StakingContractStorageLib.getOperatorIndexPerValidator();
for (uint256 i; i < _keyCount; ) {
bytes memory publicKey = BytesLib.slice(_publicKeys, i * PUBLIC_KEY_LENGTH, PUBLIC_KEY_LENGTH);
bytes memory signature = BytesLib.slice(_signatures, i * SIGNATURE_LENGTH, SIGNATURE_LENGTH);
operators.value[_operatorIndex].publicKeys.push(publicKey);
operators.value[_operatorIndex].signatures.push(signature);
bytes32 pubKeyRoot = _getPubKeyRoot(publicKey);
if (operatorIndexPerValidator.value[pubKeyRoot].enabled) {
revert DuplicateValidatorKey(publicKey);
}
operatorIndexPerValidator.value[pubKeyRoot] = StakingContractStorageLib.OperatorIndex({
enabled: true,
operatorIndex: uint32(_operatorIndex)
});
unchecked {
++i;
}
}
emit ValidatorKeysAdded(_operatorIndex, _publicKeys, _signatures);
_updateLastValidatorsEdit();
_updateAvailableValidatorCount(_operatorIndex);
}
function removeValidators(uint256 _operatorIndex, uint256[] calldata _indexes)
external
onlyActiveOperatorOrAdmin(_operatorIndex)
{
if (_indexes.length == 0) {
revert InvalidArgument();
}
StakingContractStorageLib.ValidatorsFundingInfo memory operatorInfo = StakingContractStorageLib
.getValidatorsFundingInfo(_operatorIndex);
StakingContractStorageLib.OperatorsSlot storage operators = StakingContractStorageLib.getOperators();
StakingContractStorageLib.OperatorIndexPerValidatorSlot
storage operatorIndexPerValidator = StakingContractStorageLib.getOperatorIndexPerValidator();
if (_indexes[_indexes.length - 1] < operatorInfo.funded) {
revert FundedValidatorDeletionAttempt();
}
for (uint256 i; i < _indexes.length; ) {
if (i > 0 && _indexes[i] >= _indexes[i - 1]) {
revert UnsortedIndexes();
}
bytes32 pubKeyRoot = _getPubKeyRoot(operators.value[_operatorIndex].publicKeys[_indexes[i]]);
operatorIndexPerValidator.value[pubKeyRoot].enabled = false;
operatorIndexPerValidator.value[pubKeyRoot].operatorIndex = 0;
emit ValidatorKeyRemoved(_operatorIndex, operators.value[_operatorIndex].publicKeys[_indexes[i]]);
if (_indexes[i] == operators.value[_operatorIndex].publicKeys.length - 1) {
operators.value[_operatorIndex].publicKeys.pop();
operators.value[_operatorIndex].signatures.pop();
} else {
operators.value[_operatorIndex].publicKeys[_indexes[i]] = operators.value[_operatorIndex].publicKeys[
operators.value[_operatorIndex].publicKeys.length - 1
];
operators.value[_operatorIndex].publicKeys.pop();
operators.value[_operatorIndex].signatures[_indexes[i]] = operators.value[_operatorIndex].signatures[
operators.value[_operatorIndex].signatures.length - 1
];
operators.value[_operatorIndex].signatures.pop();
}
unchecked {
++i;
}
}
if (_indexes[_indexes.length - 1] < operators.value[_operatorIndex].limit) {
operators.value[_operatorIndex].limit = _indexes[_indexes.length - 1];
emit ChangedOperatorLimit(_operatorIndex, _indexes[_indexes.length - 1]);
}
_updateLastValidatorsEdit();
_updateAvailableValidatorCount(_operatorIndex);
}
function batchWithdrawELFee(bytes calldata _publicKeys) external {
if (_publicKeys.length % PUBLIC_KEY_LENGTH != 0) {
revert InvalidPublicKeys();
}
for (uint256 i = 0; i < _publicKeys.length; ) {
bytes memory publicKey = BytesLib.slice(_publicKeys, i, PUBLIC_KEY_LENGTH);
_onlyWithdrawerOrAdmin(publicKey);
_deployAndWithdraw(publicKey, EXECUTION_LAYER_SALT_PREFIX, StakingContractStorageLib.getELDispatcher());
unchecked {
i += PUBLIC_KEY_LENGTH;
}
}
}
function batchWithdrawCLFee(bytes calldata _publicKeys) external {
if (_publicKeys.length % PUBLIC_KEY_LENGTH != 0) {
revert InvalidPublicKeys();
}
for (uint256 i = 0; i < _publicKeys.length; ) {
bytes memory publicKey = BytesLib.slice(_publicKeys, i, PUBLIC_KEY_LENGTH);
_onlyWithdrawerOrAdmin(publicKey);
_deployAndWithdraw(publicKey, CONSENSUS_LAYER_SALT_PREFIX, StakingContractStorageLib.getCLDispatcher());
unchecked {
i += PUBLIC_KEY_LENGTH;
}
}
}
function batchWithdraw(bytes calldata _publicKeys) external {
if (_publicKeys.length % PUBLIC_KEY_LENGTH != 0) {
revert InvalidPublicKeys();
}
for (uint256 i = 0; i < _publicKeys.length; ) {
bytes memory publicKey = BytesLib.slice(_publicKeys, i, PUBLIC_KEY_LENGTH);
_onlyWithdrawerOrAdmin(publicKey);
_deployAndWithdraw(publicKey, EXECUTION_LAYER_SALT_PREFIX, StakingContractStorageLib.getELDispatcher());
_deployAndWithdraw(publicKey, CONSENSUS_LAYER_SALT_PREFIX, StakingContractStorageLib.getCLDispatcher());
unchecked {
i += PUBLIC_KEY_LENGTH;
}
}
}
function withdrawELFee(bytes calldata _publicKey) external {
_onlyWithdrawerOrAdmin(_publicKey);
_deployAndWithdraw(_publicKey, EXECUTION_LAYER_SALT_PREFIX, StakingContractStorageLib.getELDispatcher());
}
function withdrawCLFee(bytes calldata _publicKey) external {
_onlyWithdrawerOrAdmin(_publicKey);
_deployAndWithdraw(_publicKey, CONSENSUS_LAYER_SALT_PREFIX, StakingContractStorageLib.getCLDispatcher());
}
function withdraw(bytes calldata _publicKey) external {
_onlyWithdrawerOrAdmin(_publicKey);
_deployAndWithdraw(_publicKey, EXECUTION_LAYER_SALT_PREFIX, StakingContractStorageLib.getELDispatcher());
_deployAndWithdraw(_publicKey, CONSENSUS_LAYER_SALT_PREFIX, StakingContractStorageLib.getCLDispatcher());
}
function requestValidatorsExit(bytes calldata _publicKeys) external {
if (_publicKeys.length % PUBLIC_KEY_LENGTH != 0) {
revert InvalidPublicKeys();
}
for (uint256 i = 0; i < _publicKeys.length; ) {
bytes memory publicKey = BytesLib.slice(_publicKeys, i, PUBLIC_KEY_LENGTH);
bytes32 pubKeyRoot = _getPubKeyRoot(publicKey);
address withdrawer = _getWithdrawer(pubKeyRoot);
if (msg.sender != withdrawer) {
revert Unauthorized();
}
_setExitRequest(pubKeyRoot, true);
emit ExitRequest(withdrawer, publicKey);
unchecked {
i += PUBLIC_KEY_LENGTH;
}
}
}
function setDepositsStopped(bool val) external onlyAdmin {
emit ChangedDepositsStopped(val);
StakingContractStorageLib.setDepositStopped(val);
}
function _onlyWithdrawerOrAdmin(bytes memory _publicKey) internal view {
if (
msg.sender != _getWithdrawer(_getPubKeyRoot(_publicKey)) &&
StakingContractStorageLib.getAdmin() != msg.sender
) {
revert InvalidWithdrawer();
}
}
function _onlyActiveOperator(uint256 _operatorIndex) internal view {
StakingContractStorageLib.OperatorInfo storage operatorInfo = StakingContractStorageLib.getOperators().value[
_operatorIndex
];
if (operatorInfo.deactivated) {
revert Deactivated();
}
if (msg.sender != operatorInfo.operator) {
revert Unauthorized();
}
}
function _getPubKeyRoot(bytes memory _publicKey) internal pure returns (bytes32) {
return sha256(abi.encodePacked(_publicKey, bytes16(0)));
}
function _getWithdrawer(bytes32 _publicKeyRoot) internal view returns (address) {
return StakingContractStorageLib.getWithdrawers().value[_publicKeyRoot];
}
function _getExitRequest(bytes32 _publicKeyRoot) internal view returns (bool) {
return StakingContractStorageLib.getExitRequestMap().value[_publicKeyRoot];
}
function _setExitRequest(bytes32 _publicKeyRoot, bool _value) internal {
StakingContractStorageLib.getExitRequestMap().value[_publicKeyRoot] = _value;
}
function _updateAvailableValidatorCount(uint256 _operatorIndex) internal {
StakingContractStorageLib.ValidatorsFundingInfo memory validatorFundingInfo = StakingContractStorageLib
.getValidatorsFundingInfo(_operatorIndex);
StakingContractStorageLib.OperatorsSlot storage operators = StakingContractStorageLib.getOperators();
uint32 oldAvailableCount = validatorFundingInfo.availableKeys;
uint32 newAvailableCount = 0;
uint256 cap = operators.value[_operatorIndex].limit;
if (cap <= validatorFundingInfo.funded) {
StakingContractStorageLib.setValidatorsFundingInfo(_operatorIndex, 0, validatorFundingInfo.funded);
} else {
newAvailableCount = uint32(cap - validatorFundingInfo.funded);
StakingContractStorageLib.setValidatorsFundingInfo(
_operatorIndex,
newAvailableCount,
validatorFundingInfo.funded
);
}
if (oldAvailableCount != newAvailableCount) {
StakingContractStorageLib.setTotalAvailableValidators(
(StakingContractStorageLib.getTotalAvailableValidators() - oldAvailableCount) + newAvailableCount
);
}
}
function _updateLastValidatorsEdit() internal {
StakingContractStorageLib.setLastValidatorEdit(block.number);
emit ValidatorsEdited(block.number);
}
function _addressToWithdrawalCredentials(address _recipient) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_recipient)) + WITHDRAWAL_CREDENTIAL_PREFIX_01);
}
function _depositValidatorsOfOperator(uint256 _operatorIndex, uint256 _validatorCount) internal {
StakingContractStorageLib.OperatorsSlot storage operators = StakingContractStorageLib.getOperators();
StakingContractStorageLib.OperatorInfo storage operator = operators.value[_operatorIndex];
StakingContractStorageLib.ValidatorsFundingInfo memory vfi = StakingContractStorageLib.getValidatorsFundingInfo(
_operatorIndex
);
for (uint256 i = vfi.funded; i < vfi.funded + _validatorCount; ) {
bytes memory publicKey = operator.publicKeys[i];
bytes memory signature = operator.signatures[i];
address consensusLayerRecipient = _getDeterministicReceiver(publicKey, CONSENSUS_LAYER_SALT_PREFIX);
bytes32 withdrawalCredentials = _addressToWithdrawalCredentials(consensusLayerRecipient);
bytes32 pubkeyRoot = _getPubKeyRoot(publicKey);
_depositValidator(publicKey, pubkeyRoot, signature, withdrawalCredentials);
StakingContractStorageLib.getWithdrawers().value[pubkeyRoot] = msg.sender;
emit Deposit(msg.sender, msg.sender, publicKey, signature);
unchecked {
++i;
}
}
StakingContractStorageLib.setValidatorsFundingInfo(
_operatorIndex,
uint32(vfi.availableKeys - _validatorCount),
uint32(vfi.funded + _validatorCount)
);
}
function _depositValidator(
bytes memory _publicKey,
bytes32 _pubkeyRoot,
bytes memory _signature,
bytes32 _withdrawalCredentials
) internal {
bytes32 signatureRoot = sha256(
abi.encodePacked(
sha256(BytesLib.slice(_signature, 0, 64)),
sha256(abi.encodePacked(BytesLib.slice(_signature, 64, SIGNATURE_LENGTH - 64), bytes32(0)))
)
);
bytes32 depositDataRoot = sha256(
abi.encodePacked(
sha256(abi.encodePacked(_pubkeyRoot, _withdrawalCredentials)),
sha256(abi.encodePacked(DEPOSIT_SIZE_AMOUNT_LITTLEENDIAN64, signatureRoot))
)
);
uint256 targetBalance = address(this).balance - DEPOSIT_SIZE;
IDepositContract(StakingContractStorageLib.getDepositContract()).deposit{value: DEPOSIT_SIZE}(
_publicKey,
abi.encodePacked(_withdrawalCredentials),
_signature,
depositDataRoot
);
if (address(this).balance != targetBalance) {
revert DepositFailure();
}
}
function _depositOnOneOperator(uint256 _depositCount, uint256 _totalAvailableValidators) internal {
StakingContractStorageLib.setTotalAvailableValidators(_totalAvailableValidators - _depositCount);
_depositValidatorsOfOperator(0, _depositCount);
}
function _deposit() internal {
if (StakingContractStorageLib.getDepositStopped()) {
revert DepositsStopped();
}
if (msg.value == 0 || msg.value % DEPOSIT_SIZE != 0) {
revert InvalidDepositValue();
}
uint256 totalAvailableValidators = StakingContractStorageLib.getTotalAvailableValidators();
uint256 depositCount = msg.value / DEPOSIT_SIZE;
if (depositCount > totalAvailableValidators) {
revert NotEnoughValidators();
}
StakingContractStorageLib.OperatorsSlot storage operators = StakingContractStorageLib.getOperators();
if (operators.value.length == 0) {
revert NoOperators();
}
_depositOnOneOperator(depositCount, totalAvailableValidators);
}
function _min(uint256 _a, uint256 _b) internal pure returns (uint256) {
if (_a < _b) {
return _a;
}
return _b;
}
function _getDeterministicReceiver(bytes memory _publicKey, uint256 _prefix) internal view returns (address) {
bytes32 publicKeyRoot = _getPubKeyRoot(_publicKey);
bytes32 salt = sha256(abi.encodePacked(_prefix, publicKeyRoot));
address implementation = StakingContractStorageLib.getFeeRecipientImplementation();
return Clones.predictDeterministicAddress(implementation, salt);
}
function _deployAndWithdraw(
bytes memory _publicKey,
uint256 _prefix,
address _dispatcher
) internal {
bytes32 publicKeyRoot = _getPubKeyRoot(_publicKey);
bytes32 feeRecipientSalt = sha256(abi.encodePacked(_prefix, publicKeyRoot));
address implementation = StakingContractStorageLib.getFeeRecipientImplementation();
address feeRecipientAddress = Clones.predictDeterministicAddress(implementation, feeRecipientSalt);
if (feeRecipientAddress.code.length == 0) {
Clones.cloneDeterministic(implementation, feeRecipientSalt);
IFeeRecipient(feeRecipientAddress).init(_dispatcher, publicKeyRoot);
}
IFeeRecipient(feeRecipientAddress).withdraw();
}
function _checkAddress(address _address) internal pure {
if (_address == address(0)) {
revert InvalidZeroAddress();
}
}
}
文件 18 的 22:StakingContractStorageLib.sol
pragma solidity >=0.8.10;
library StakingContractStorageLib {
function getUint256(bytes32 position) internal view returns (uint256 data) {
assembly {
data := sload(position)
}
}
function setUint256(bytes32 position, uint256 data) internal {
assembly {
sstore(position, data)
}
}
function getAddress(bytes32 position) internal view returns (address data) {
assembly {
data := sload(position)
}
}
function setAddress(bytes32 position, address data) internal {
assembly {
sstore(position, data)
}
}
function getBool(bytes32 position) internal view returns (bool data) {
assembly {
data := sload(position)
}
}
function setBool(bytes32 position, bool data) internal {
assembly {
sstore(position, data)
}
}
bytes32 internal constant VERSION_SLOT = keccak256("StakingContract.version");
function getVersion() internal view returns (uint256) {
return getUint256(VERSION_SLOT);
}
function setVersion(uint256 _newVersion) internal {
setUint256(VERSION_SLOT, _newVersion);
}
bytes32 internal constant ADMIN_SLOT = keccak256("StakingContract.admin");
bytes32 internal constant PENDING_ADMIN_SLOT = keccak256("StakingContract.pendingAdmin");
function getAdmin() internal view returns (address) {
return getAddress(ADMIN_SLOT);
}
function setAdmin(address _newAdmin) internal {
setAddress(ADMIN_SLOT, _newAdmin);
}
function getPendingAdmin() internal view returns (address) {
return getAddress(PENDING_ADMIN_SLOT);
}
function setPendingAdmin(address _newPendingAdmin) internal {
setAddress(PENDING_ADMIN_SLOT, _newPendingAdmin);
}
bytes32 internal constant TREASURY_SLOT = keccak256("StakingContract.treasury");
function getTreasury() internal view returns (address) {
return getAddress(TREASURY_SLOT);
}
function setTreasury(address _newTreasury) internal {
setAddress(TREASURY_SLOT, _newTreasury);
}
bytes32 internal constant DEPOSIT_CONTRACT_SLOT = keccak256("StakingContract.depositContract");
function getDepositContract() internal view returns (address) {
return getAddress(DEPOSIT_CONTRACT_SLOT);
}
function setDepositContract(address _newDepositContract) internal {
setAddress(DEPOSIT_CONTRACT_SLOT, _newDepositContract);
}
bytes32 internal constant OPERATORS_SLOT = keccak256("StakingContract.operators");
struct OperatorInfo {
address operator;
address feeRecipient;
uint256 limit;
bytes[] publicKeys;
bytes[] signatures;
bool deactivated;
}
struct OperatorsSlot {
OperatorInfo[] value;
}
function getOperators() internal pure returns (OperatorsSlot storage p) {
bytes32 slot = OPERATORS_SLOT;
assembly {
p.slot := slot
}
}
uint256 internal constant FUNDED_OFFSET = 32;
bytes32 internal constant VALIDATORS_FUNDING_INFO_SLOT = keccak256("StakingContract.validatorsFundingInfo");
struct ValidatorsFundingInfo {
uint32 availableKeys;
uint32 funded;
}
struct UintToUintMappingSlot {
mapping(uint256 => uint256) value;
}
function getValidatorsFundingInfo(uint256 _index) internal view returns (ValidatorsFundingInfo memory vfi) {
UintToUintMappingSlot storage p;
bytes32 slot = VALIDATORS_FUNDING_INFO_SLOT;
assembly {
p.slot := slot
}
uint256 slotIndex = _index >> 2;
uint256 innerIndex = (_index & 3) << 6;
uint256 value = p.value[slotIndex] >> innerIndex;
vfi.availableKeys = uint32(value);
vfi.funded = uint32(value >> FUNDED_OFFSET);
}
function setValidatorsFundingInfo(
uint256 _index,
uint32 _availableKeys,
uint32 _funded
) internal {
UintToUintMappingSlot storage p;
bytes32 slot = VALIDATORS_FUNDING_INFO_SLOT;
assembly {
p.slot := slot
}
uint256 slotIndex = _index >> 2;
uint256 innerIndex = (_index & 3) << 6;
p.value[slotIndex] =
(p.value[slotIndex] & (~(uint256(0xFFFFFFFFFFFFFFFF) << innerIndex))) |
((uint256(_availableKeys) | (uint256(_funded) << FUNDED_OFFSET)) << innerIndex);
}
bytes32 internal constant TOTAL_AVAILABLE_VALIDATORS_SLOT = keccak256("StakingContract.totalAvailableValidators");
function getTotalAvailableValidators() internal view returns (uint256) {
return getUint256(TOTAL_AVAILABLE_VALIDATORS_SLOT);
}
function setTotalAvailableValidators(uint256 _newTotal) internal {
setUint256(TOTAL_AVAILABLE_VALIDATORS_SLOT, _newTotal);
}
bytes32 internal constant WITHDRAWERS_SLOT = keccak256("StakingContract.withdrawers");
struct WithdrawersSlot {
mapping(bytes32 => address) value;
}
function getWithdrawers() internal pure returns (WithdrawersSlot storage p) {
bytes32 slot = WITHDRAWERS_SLOT;
assembly {
p.slot := slot
}
}
struct OperatorIndex {
bool enabled;
uint32 operatorIndex;
}
struct OperatorIndexPerValidatorSlot {
mapping(bytes32 => OperatorIndex) value;
}
bytes32 internal constant OPERATOR_INDEX_PER_VALIDATOR_SLOT =
keccak256("StakingContract.operatorIndexPerValidator");
function getOperatorIndexPerValidator() internal pure returns (OperatorIndexPerValidatorSlot storage p) {
bytes32 slot = OPERATOR_INDEX_PER_VALIDATOR_SLOT;
assembly {
p.slot := slot
}
}
bytes32 internal constant GLOBAL_FEE_SLOT = keccak256("StakingContract.globalFee");
function getGlobalFee() internal view returns (uint256) {
return getUint256(GLOBAL_FEE_SLOT);
}
function setGlobalFee(uint256 _newTreasuryFee) internal {
setUint256(GLOBAL_FEE_SLOT, _newTreasuryFee);
}
bytes32 internal constant OPERATOR_FEE_SLOT = keccak256("StakingContract.operatorFee");
function getOperatorFee() internal view returns (uint256) {
return getUint256(OPERATOR_FEE_SLOT);
}
function setOperatorFee(uint256 _newOperatorFee) internal {
setUint256(OPERATOR_FEE_SLOT, _newOperatorFee);
}
bytes32 internal constant EL_DISPATCHER_SLOT = keccak256("StakingContract.executionLayerDispatcher");
function getELDispatcher() internal view returns (address) {
return getAddress(EL_DISPATCHER_SLOT);
}
function setELDispatcher(address _newElDispatcher) internal {
setAddress(EL_DISPATCHER_SLOT, _newElDispatcher);
}
bytes32 internal constant CL_DISPATCHER_SLOT = keccak256("StakingContract.consensusLayerDispatcher");
function getCLDispatcher() internal view returns (address) {
return getAddress(CL_DISPATCHER_SLOT);
}
function setCLDispatcher(address _newClDispatcher) internal {
setAddress(CL_DISPATCHER_SLOT, _newClDispatcher);
}
bytes32 internal constant FEE_RECIPIENT_IMPLEMENTATION_SLOT =
keccak256("StakingContract.feeRecipientImplementation");
function getFeeRecipientImplementation() internal view returns (address) {
return getAddress(FEE_RECIPIENT_IMPLEMENTATION_SLOT);
}
function setFeeRecipientImplementation(address _newFeeRecipientImplementation) internal {
setAddress(FEE_RECIPIENT_IMPLEMENTATION_SLOT, _newFeeRecipientImplementation);
}
bytes32 internal constant WITHDRAWER_CUSTOMIZATION_ENABLED_SLOT =
keccak256("StakingContract.withdrawerCustomizationEnabled");
function getWithdrawerCustomizationEnabled() internal view returns (bool) {
return getBool(WITHDRAWER_CUSTOMIZATION_ENABLED_SLOT);
}
function setWithdrawerCustomizationEnabled(bool _enabled) internal {
setBool(WITHDRAWER_CUSTOMIZATION_ENABLED_SLOT, _enabled);
}
bytes32 internal constant EXIT_REQUEST_MAPPING_SLOT =
bytes32(uint256(keccak256("StakingContract.exitRequest")) - 1);
struct ExitRequestMap {
mapping(bytes32 => bool) value;
}
function getExitRequestMap() internal pure returns (ExitRequestMap storage p) {
bytes32 slot = EXIT_REQUEST_MAPPING_SLOT;
assembly {
p.slot := slot
}
}
bytes32 internal constant WITHDRAWN_MAPPING_SLOT = bytes32(uint256(keccak256("StakingContract.withdrawn")) - 1);
struct WithdrawnMap {
mapping(bytes32 => bool) value;
}
function getWithdrawnMap() internal pure returns (WithdrawnMap storage p) {
bytes32 slot = WITHDRAWN_MAPPING_SLOT;
assembly {
p.slot := slot
}
}
bytes32 internal constant GLOBAL_COMMISSION_LIMIT_SLOT =
bytes32(uint256(keccak256("StakingContract.globalCommissionLimit")) - 1);
function getGlobalCommissionLimit() internal view returns (uint256) {
return getUint256(GLOBAL_COMMISSION_LIMIT_SLOT);
}
function setGlobalCommissionLimit(uint256 value) internal {
setUint256(GLOBAL_COMMISSION_LIMIT_SLOT, value);
}
bytes32 internal constant OPERATOR_COMMISSION_LIMIT_SLOT =
bytes32(uint256(keccak256("StakingContract.operatorCommissionLimit")) - 1);
function getOperatorCommissionLimit() internal view returns (uint256) {
return getUint256(OPERATOR_COMMISSION_LIMIT_SLOT);
}
function setOperatorCommissionLimit(uint256 value) internal {
setUint256(OPERATOR_COMMISSION_LIMIT_SLOT, value);
}
bytes32 internal constant DEPOSIT_STOPPED_SLOT = bytes32(uint256(keccak256("StakingContract.depositStopped")) - 1);
function getDepositStopped() internal view returns (bool) {
return getBool(DEPOSIT_STOPPED_SLOT);
}
function setDepositStopped(bool val) internal {
setBool(DEPOSIT_STOPPED_SLOT, val);
}
bytes32 internal constant LAST_VALIDATOR_EDIT_SLOT =
bytes32(uint256(keccak256("StakingContract.lastValidatorsEdit")) - 1);
function getLastValidatorEdit() internal view returns (uint256) {
return getUint256(LAST_VALIDATOR_EDIT_SLOT);
}
function setLastValidatorEdit(uint256 value) internal {
setUint256(LAST_VALIDATOR_EDIT_SLOT, value);
}
}
文件 19 的 22:StorageSlot.sol
pragma solidity ^0.8.0;
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
文件 20 的 22:TUPProxy.sol
pragma solidity >=0.8.10;
import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";
contract TUPProxy is TransparentUpgradeableProxy {
bytes32 private constant _PAUSE_SLOT = bytes32(uint256(keccak256("eip1967.proxy.pause")) - 1);
error CallWhenPaused();
constructor(
address _logic,
address admin_,
bytes memory _data
) payable TransparentUpgradeableProxy(_logic, admin_, _data) {}
function isPaused() external ifAdmin returns (bool) {
return StorageSlot.getBooleanSlot(_PAUSE_SLOT).value;
}
function pause() external ifAdmin {
StorageSlot.getBooleanSlot(_PAUSE_SLOT).value = true;
}
function unpause() external ifAdmin {
StorageSlot.getBooleanSlot(_PAUSE_SLOT).value = false;
}
function _beforeFallback() internal override {
if (StorageSlot.getBooleanSlot(_PAUSE_SLOT).value == false || msg.sender == address(0)) {
super._beforeFallback();
} else {
revert CallWhenPaused();
}
}
}
文件 21 的 22:TransparentUpgradeableProxy.sol
pragma solidity ^0.8.0;
import "../ERC1967/ERC1967Proxy.sol";
contract TransparentUpgradeableProxy is ERC1967Proxy {
constructor(
address _logic,
address admin_,
bytes memory _data
) payable ERC1967Proxy(_logic, _data) {
assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_changeAdmin(admin_);
}
modifier ifAdmin() {
if (msg.sender == _getAdmin()) {
_;
} else {
_fallback();
}
}
function admin() external ifAdmin returns (address admin_) {
admin_ = _getAdmin();
}
function implementation() external ifAdmin returns (address implementation_) {
implementation_ = _implementation();
}
function changeAdmin(address newAdmin) external virtual ifAdmin {
_changeAdmin(newAdmin);
}
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeToAndCall(newImplementation, bytes(""), false);
}
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
_upgradeToAndCall(newImplementation, data, true);
}
function _admin() internal view virtual returns (address) {
return _getAdmin();
}
function _beforeFallback() internal virtual override {
require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
super._beforeFallback();
}
}
文件 22 的 22:draft-IERC1822.sol
pragma solidity ^0.8.0;
interface IERC1822Proxiable {
function proxiableUUID() external view returns (bytes32);
}
{
"compilationTarget": {
"src/contracts/ConsensusLayerFeeDispatcher.sol": "ConsensusLayerFeeDispatcher"
},
"evmVersion": "london",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs",
"useLiteralContent": true
},
"optimizer": {
"enabled": true,
"runs": 10000
},
"remappings": []
}
[{"inputs":[{"internalType":"uint256","name":"_version","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AlreadyInitialized","type":"error"},{"inputs":[{"internalType":"bytes","name":"errorData","type":"bytes"}],"name":"FeeRecipientReceiveError","type":"error"},{"inputs":[],"name":"InvalidCall","type":"error"},{"inputs":[{"internalType":"bytes","name":"errorData","type":"bytes"}],"name":"TreasuryReceiveError","type":"error"},{"inputs":[{"internalType":"bytes","name":"errorData","type":"bytes"}],"name":"WithdrawerReceiveError","type":"error"},{"inputs":[],"name":"ZeroBalanceWithdrawal","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"withdrawer","type":"address"},{"indexed":true,"internalType":"address","name":"feeRecipient","type":"address"},{"indexed":false,"internalType":"bytes32","name":"pubKeyRoot","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"rewards","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"nodeOperatorFee","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"treasuryFee","type":"uint256"}],"name":"Withdrawal","type":"event"},{"stateMutability":"payable","type":"fallback"},{"inputs":[{"internalType":"bytes32","name":"_publicKeyRoot","type":"bytes32"}],"name":"dispatch","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"getStakingContract","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"_publicKeyRoot","type":"bytes32"}],"name":"getWithdrawer","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_stakingContract","type":"address"}],"name":"initCLD","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]