Verified contractExactGPL-3.0
InstitutionalVault
Address0xe9a876df520c92a61cd954bbefbc5bcb4356cbc0
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.33
- Same code
Only this contract
Details
- Compiler
- solc 0.8.33+commit.64118f21
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- prague
- License
- GPL-3.0
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,674,240
- Creation transaction
- 0x67afdc9ba7…3d58fd9849
59 files
The source code is large: one file is shown at a time. Choose a file in the list.
- src/InstitutionalVault.solmain44.81 KB
- dependencies/@openzeppelin-contracts-5.1.0/access/manager/AccessManaged.sol4.73 KB
- dependencies/@openzeppelin-contracts-5.1.0/access/manager/AccessManager.sol29.88 KB
- dependencies/@openzeppelin-contracts-5.1.0/access/manager/AuthorityUtils.sol1.23 KB
- dependencies/@openzeppelin-contracts-5.1.0/access/manager/IAccessManaged.sol1.11 KB
- dependencies/@openzeppelin-contracts-5.1.0/access/manager/IAccessManager.sol16.37 KB
- dependencies/@openzeppelin-contracts-5.1.0/access/manager/IAuthority.sol482 B
- dependencies/@openzeppelin-contracts-5.1.0/interfaces/IERC1363.sol4.45 KB
- dependencies/@openzeppelin-contracts-5.1.0/interfaces/IERC165.sol192 B
- dependencies/@openzeppelin-contracts-5.1.0/interfaces/IERC1967.sol636 B
- dependencies/@openzeppelin-contracts-5.1.0/interfaces/IERC20.sol181 B
- dependencies/@openzeppelin-contracts-5.1.0/interfaces/IERC4626.sol12.18 KB
- dependencies/@openzeppelin-contracts-5.1.0/interfaces/draft-IERC1822.sol881 B
- dependencies/@openzeppelin-contracts-5.1.0/interfaces/draft-IERC6093.sol6.54 KB
- dependencies/@openzeppelin-contracts-5.1.0/proxy/ERC1967/ERC1967Utils.sol6.24 KB
- dependencies/@openzeppelin-contracts-5.1.0/proxy/beacon/IBeacon.sol472 B
- dependencies/@openzeppelin-contracts-5.1.0/token/ERC20/IERC20.sol2.78 KB
- dependencies/@openzeppelin-contracts-5.1.0/token/ERC20/extensions/IERC20Metadata.sol684 B
- dependencies/@openzeppelin-contracts-5.1.0/token/ERC20/utils/SafeERC20.sol9.44 KB
- dependencies/@openzeppelin-contracts-5.1.0/utils/Address.sol6.03 KB
- dependencies/@openzeppelin-contracts-5.1.0/utils/Context.sol963 B
- dependencies/@openzeppelin-contracts-5.1.0/utils/Errors.sol896 B
- dependencies/@openzeppelin-contracts-5.1.0/utils/Multicall.sol1.7 KB
- dependencies/@openzeppelin-contracts-5.1.0/utils/Panic.sol1.97 KB
- dependencies/@openzeppelin-contracts-5.1.0/utils/StorageSlot.sol4.18 KB
- dependencies/@openzeppelin-contracts-5.1.0/utils/introspection/IERC165.sol870 B
- dependencies/@openzeppelin-contracts-5.1.0/utils/math/Math.sol28.31 KB
- dependencies/@openzeppelin-contracts-5.1.0/utils/math/SafeCast.sol34.94 KB
- dependencies/@openzeppelin-contracts-5.1.0/utils/types/Time.sol5.16 KB
- dependencies/@openzeppelin-contracts-upgradeable-5.1.0/access/manager/AccessManagedUpgradeable.sol6.03 KB
- dependencies/@openzeppelin-contracts-upgradeable-5.1.0/proxy/utils/Initializable.sol8.91 KB
- dependencies/@openzeppelin-contracts-upgradeable-5.1.0/proxy/utils/UUPSUpgradeable.sol6.6 KB
- dependencies/@openzeppelin-contracts-upgradeable-5.1.0/token/ERC20/ERC20Upgradeable.sol12.23 KB
- dependencies/@openzeppelin-contracts-upgradeable-5.1.0/token/ERC20/extensions/ERC4626Upgradeable.sol13.66 KB
- dependencies/@openzeppelin-contracts-upgradeable-5.1.0/utils/ContextUpgradeable.sol1.19 KB
- src/Errors.sol690 B
- src/InstitutionalVaultStorage.sol1.6 KB
- src/NonRestakingWithdrawalCredentials.sol6.07 KB
- src/NonRestakingWithdrawalCredentialsFactory.sol2.28 KB
- src/interface/Eigenlayer-Slashing/IDelegationManager.sol28.95 KB
- src/interface/Eigenlayer-Slashing/IETHPOSDeposit.sol3.67 KB
- src/interface/Eigenlayer-Slashing/IEigenPod.sol28.48 KB
- src/interface/Eigenlayer-Slashing/IEigenPodManager.sol8.31 KB
- src/interface/Eigenlayer-Slashing/IPausable.sol4.03 KB
- src/interface/Eigenlayer-Slashing/IPauserRegistry.sol785 B
- src/interface/Eigenlayer-Slashing/ISemVerMixin.sol457 B
- src/interface/Eigenlayer-Slashing/IShareManager.sol2.89 KB
- src/interface/Eigenlayer-Slashing/ISignatureUtilsMixin.sol2.04 KB
- src/interface/Eigenlayer-Slashing/IStrategy.sol7.72 KB
- src/interface/Eigenlayer-Slashing/IStrategyManager.sol13.2 KB
- src/interface/Eigenlayer-Slashing/libraries/BeaconChainProofs.sol15.4 KB
- src/interface/Eigenlayer-Slashing/libraries/Endian.sol1.13 KB
- src/interface/Eigenlayer-Slashing/libraries/Merkle.sol6.97 KB
- src/interface/Eigenlayer-Slashing/libraries/OperatorSetLib.sol822 B
- src/interface/Eigenlayer-Slashing/libraries/SlashingLib.sol7.15 KB
- src/interface/IBeaconDepositContract.sol361 B
- src/interface/IEigenPodManager.sol265 B
- src/interface/IInstitutionalVault.sol16.01 KB
- src/interface/IWETH.sol262 B
src/InstitutionalVault.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.0 <0.9.0;
import {
CustomCallFailed,
DelegateCallFailed,
EthTransferFailed,
FeeBpsExceedsCap,
InvalidInput,
InvalidMaxAprBps,
InvalidMaxTotalFeeBps,
NotEnoughETH,
NotEnoughWETH,
RewardsExceedSanityBound,
SelfRecipient,
WithdrawalCredentialsNotSet,
ZeroAddress,
ZeroAddressRecipient,
ZeroAssets,
ZeroFeeBps,
ZeroShares
} from "./Errors.sol";
import { FeeRecipient, VaultStorage } from "./InstitutionalVaultStorage.sol";
import { NonRestakingWithdrawalCredentials } from "./NonRestakingWithdrawalCredentials.sol";
import { NonRestakingWithdrawalCredentialsFactory } from "./NonRestakingWithdrawalCredentialsFactory.sol";
import { IDelegationManager, IDelegationManagerTypes } from "./interface/Eigenlayer-Slashing/IDelegationManager.sol";
import { IEigenPod, IEigenPodTypes } from "./interface/Eigenlayer-Slashing/IEigenPod.sol";
import { IStrategy } from "./interface/Eigenlayer-Slashing/IStrategy.sol";
import { IBeaconDepositContract } from "./interface/IBeaconDepositContract.sol";
import { IEigenPodManager } from "./interface/IEigenPodManager.sol";
import { IInstitutionalVault } from "./interface/IInstitutionalVault.sol";
import { IWETH } from "./interface/IWETH.sol";
import { AccessManagedUpgradeable } from
"@openzeppelin/contracts-upgradeable/access/manager/AccessManagedUpgradeable.sol";
import { UUPSUpgradeable } from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import { ERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import { ERC4626Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC4626Upgradeable.sol";
import { IAccessManager } from "@openzeppelin/contracts/access/manager/IAccessManager.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
/**
* @title InstitutionalVault
* @author Puffer Finance
* @notice A vault that allows for deposits of ETH and converts them to shares of the vault
*/
contract InstitutionalVault is
VaultStorage,
ERC4626Upgradeable,
UUPSUpgradeable,
AccessManagedUpgradeable,
IInstitutionalVault
{
using SafeERC20 for IERC20;
address internal constant _BEACON_CHAIN_STRATEGY = 0xbeaC0eeEeeeeEEeEeEEEEeeEEeEeeeEeeEEBEaC0;
string public constant VERSION = "3.0.0";
/// @notice Basis-point denominator (100%): bounds the reward allowance and forms the mint denominator.
uint16 internal constant BPS_DENOMINATOR = 10_000;
/// @notice Hard ceiling on the Σ-recipient fee, kept below 100% so the mint denominator can never reach 0.
uint16 internal constant HARD_FEE_BPS_CAP = 9_900; //99%
uint256 internal constant SECONDS_PER_YEAR = 365 days;
/// @notice Baseline below which the per-report reward allowance is not enforced. At such a small baseline
/// the percentage bound can be smaller than a legitimate reward, so it would block honest reports.
uint256 internal constant MIN_APR_BREAKER_BASELINE = 1 ether;
IWETH public immutable WETH;
IBeaconDepositContract public immutable BEACON_DEPOSIT_CONTRACT;
IEigenPodManager public immutable EIGEN_POD_MANAGER;
IDelegationManager public immutable EIGEN_DELEGATION_MANAGER;
address public immutable NON_RESTAKING_WITHDRAWAL_CREDENTIALS_FACTORY;
/**
* @notice Constructor for the vault
* @param weth The address of the WETH token
* @param eigenPodManager The address of the EigenPodManager
* @param beaconDepositContract The address of the Beacon Deposit Contract
* @param eigenDelegationManager The address of the EigenDelegationManager
*/
constructor(
address weth,
address eigenPodManager,
address beaconDepositContract,
address eigenDelegationManager,
address nonRestakingWithdrawalCredentialsFactory
) {
require(weth != address(0), ZeroAddress());
require(eigenPodManager != address(0), ZeroAddress());
require(beaconDepositContract != address(0), ZeroAddress());
require(eigenDelegationManager != address(0), ZeroAddress());
require(nonRestakingWithdrawalCredentialsFactory != address(0), ZeroAddress());
WETH = IWETH(weth);
EIGEN_POD_MANAGER = IEigenPodManager(eigenPodManager);
BEACON_DEPOSIT_CONTRACT = IBeaconDepositContract(beaconDepositContract);
EIGEN_DELEGATION_MANAGER = IDelegationManager(eigenDelegationManager);
NON_RESTAKING_WITHDRAWAL_CREDENTIALS_FACTORY = nonRestakingWithdrawalCredentialsFactory;
_disableInitializers();
}
/**
* @notice Allow contract to receive ETH
*/
receive() external payable { }
/**
* @notice Initialize the vault and create a new EigenPod
* @param accessManager The address of the access manager
* @param shareTokenName The name of the share token
* @param shareTokenSymbol The symbol of the share token
*/
function initialize(address accessManager, string calldata shareTokenName, string calldata shareTokenSymbol)
external
initializer
{
require(accessManager != address(0), ZeroAddress());
__AccessManaged_init(accessManager);
__ERC20_init(shareTokenName, shareTokenSymbol);
__ERC4626_init(IERC20(address(WETH)));
__UUPSUpgradeable_init();
__Context_init();
Storage storage $ = _getVaultStorage();
$.eigenPod = address(EIGEN_POD_MANAGER.createPod());
}
/**
* @notice Initialize and deploys the non-restaking withdrawal credentials
* contract (if not already deployed by a prior impl version) and bootstraps the v3
* fee mechanism storage
*/
function initializerV3(FeeRecipient[] calldata initialRecipients, uint16 maxAprBps_, uint16 maxTotalFeeBps_)
external
restricted
reinitializer(3)
{
_checkMaxAprBps(maxAprBps_);
_checkMaxTotalFeeBps(maxTotalFeeBps_);
Storage storage $ = _getVaultStorage();
// Deploy WC for fresh vaults; idempotent skip for upgraded ones.
if ($.noRestakingWithdrawalCredentials == address(0)) {
(bool success,) = address(NON_RESTAKING_WITHDRAWAL_CREDENTIALS_FACTORY).delegatecall(
abi.encodeCall(NonRestakingWithdrawalCredentialsFactory.deployNewStakingWithdrawalCredentials, ())
);
require(success, DelegateCallFailed());
}
// Bootstrap fee state. The lastTotalAssets snapshot prevents the first oracle report from
// minting fees on the entire pre-existing TVL.
$.lastTotalAssets = SafeCast.toUint128(totalAssets());
$.lastReportTimestamp = uint64(block.timestamp);
$.netLPFlowSinceLastReport = 0;
$.maxAprBps = maxAprBps_;
$.maxTotalFeeBps = maxTotalFeeBps_;
_setFeeRecipientsInternal($, initialRecipients);
}
/**
* @notice Deposit ETH into the vault
* Depositor receives institutionalETH shares in return
* @param receiver The address to receive the shares
*/
function depositETH(address receiver) public payable virtual restricted returns (uint256) {
uint256 maxAssets = maxDeposit(receiver);
if (msg.value > maxAssets) {
revert ERC4626ExceededMaxDeposit(receiver, msg.value, maxAssets);
}
uint256 shares = previewDeposit(msg.value);
require(shares != 0, ZeroShares());
_mint(receiver, shares);
// depositETH bypasses OZ ERC4626 _deposit; track LP flow directly.
_increaseNetLPFlow(msg.value);
emit Deposit(_msgSender(), receiver, msg.value, shares);
emit DepositedETH(_msgSender(), receiver, msg.value, shares);
return shares;
}
/**
* @notice Override the deposit function to allow for the deposit of shares (institutionalETH)
* Restricted modifier is used to pause/unpause the deposit function
* @param assets The amount of assets (WETH) to deposit
* @param receiver The address to receive the shares
* @return shares The amount of shares (institutionalETH) minted
*/
function deposit(uint256 assets, address receiver)
public
virtual
override(ERC4626Upgradeable, IInstitutionalVault)
restricted
returns (uint256)
{
return super.deposit(assets, receiver);
}
/**
* @notice Redeems (institutionalETH) `shares` to receive (WETH) assets from the vault, burning the `owner`'s (institutionalETH) `shares`.
* The caller of this function does not have to be the `owner` if the `owner` has approved the caller to spend their institutionalETH.
* @param shares The amount of shares (institutionalETH) to withdraw
* @param receiver The address to receive the assets (WETH)
* @param owner The address of the owner for which the shares (institutionalETH) are burned.
* @return assets The amount of assets (WETH) redeemed
*/
function redeem(uint256 shares, address receiver, address owner)
public
virtual
override(ERC4626Upgradeable, IInstitutionalVault)
restricted
returns (uint256)
{
uint256 maxShares = maxRedeem(owner);
if (shares > maxShares) {
revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
}
uint256 assets = previewRedeem(shares);
require(assets != 0, ZeroAssets());
_wrapETH(assets);
_withdraw({ caller: _msgSender(), receiver: receiver, owner: owner, assets: assets, shares: shares });
return assets;
}
/**
* @notice Redeems (institutionalETH) `shares` to receive (native ETH) assets from the vault, burning the `owner`'s (institutionalETH) `shares`.
* The caller of this function does not have to be the `owner` if the `owner` has approved the caller to spend their institutionalETH.
* @param shares The amount of shares (institutionalETH) to withdraw
* @param receiver The address to receive the assets (native ETH)
* @param owner The address of the owner for which the shares (institutionalETH) are burned.
* @return assets The amount of assets (native ETH) redeemed
*/
function redeemETH(uint256 shares, address receiver, address owner) public virtual restricted returns (uint256) {
uint256 maxShares = maxRedeem(owner);
if (shares > maxShares) {
revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
}
uint256 assets = previewRedeem(shares);
require(assets != 0, ZeroAssets());
_exitNativeETH(assets, shares, receiver, owner);
return assets;
}
/**
* @notice Withdrawals WETH assets from the vault, burning the `owner`'s (institutionalETH) shares.
* The caller of this function does not have to be the `owner` if the `owner` has approved the caller to spend their institutionalETH.
* @param assets The amount of assets (WETH) to withdraw
* @param receiver The address to receive the assets (WETH)
* @param owner The address of the owner for which the shares (institutionalETH) are burned.
* @return shares The amount of shares (institutionalETH) burned
*/
function withdraw(uint256 assets, address receiver, address owner)
public
virtual
override(ERC4626Upgradeable, IInstitutionalVault)
restricted
returns (uint256)
{
uint256 maxAssets = maxWithdraw(owner);
if (assets > maxAssets) {
revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);
}
_wrapETH(assets);
uint256 shares = previewWithdraw(assets);
_withdraw({ caller: _msgSender(), receiver: receiver, owner: owner, assets: assets, shares: shares });
return shares;
}
/**
* @notice Withdrawals native ETH assets from the vault, burning the `owner`'s (institutionalETH) shares.
* The caller of this function does not have to be the `owner` if the `owner` has approved the caller to spend their institutionalETH.
* @param assets The amount of assets (native ETH) to withdraw
* @param receiver The address to receive the assets (native ETH)
* @param owner The address of the owner for which the shares (institutionalETH) are burned.
* @return shares The amount of shares (institutionalETH) burned
*/
function withdrawETH(uint256 assets, address receiver, address owner) public virtual restricted returns (uint256) {
uint256 maxAssets = maxWithdraw(owner);
if (assets > maxAssets) {
revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);
}
uint256 shares = previewWithdraw(assets);
_exitNativeETH(assets, shares, receiver, owner);
return shares;
}
/**
* @notice Override the transfer function to allow for the transfer of shares (institutionalETH)
* Restricted modifier is used to pause/unpause the transfer function
* @param to The address to transfer to
* @param value The amount of shares to transfer
* @return bool Whether the transfer was successful
*/
function transfer(address to, uint256 value)
public
virtual
override(ERC20Upgradeable, IERC20)
restricted
returns (bool)
{
return super.transfer(to, value);
}
/**
* @notice Override the transferFrom function to allow for the transfer of shares (institutionalETH)
* Restricted modifier is used to pause/unpause the transferFrom function
* @param from The address to transfer from
* @param to The address to transfer to
* @param value The amount of shares to transfer
* @return bool Whether the transfer was successful
*/
function transferFrom(address from, address to, uint256 value)
public
virtual
override(ERC20Upgradeable, IERC20)
restricted
returns (bool)
{
return super.transferFrom(from, to, value);
}
/**
* @notice Override the mint function to allow for the minting of shares (institutionalETH)
* Restricted modifier is used to pause/unpause the mint function
* @param shares The amount of shares (institutionalETH) to mint
* @param receiver The address to receive the shares
* @return assets The amount of assets (WETH) minted
*/
function mint(uint256 shares, address receiver)
public
virtual
override(ERC4626Upgradeable, IInstitutionalVault)
restricted
returns (uint256)
{
return super.mint(shares, receiver);
}
// Start validators =====================================================
/**
* @notice Start restaking validators through EigenLayer
* @param pubKeys The public keys of the validators to restake
* @param signatures The signatures of the validators to restake
* @param amountsInGwei The amounts of ETH to restake for each validator (in Gwei)
* @param depositDataRoots The deposit data roots of the validators to restake
*/
function startRestakingValidators(
bytes[] calldata pubKeys,
bytes[] calldata signatures,
uint256[] calldata amountsInGwei,
bytes32[] calldata depositDataRoots
) external virtual restricted {
_startValidators(pubKeys, signatures, amountsInGwei, depositDataRoots, true);
}
/**
* @notice Start non restaking validators by directly depositing into the Beacon Deposit Contract
* This allows additional deposits to be made for a certain validator
* @param pubKeys The public keys of the validators
* @param signatures The signatures of the validators
* @param amountsInGwei The amounts of ETH to deposit for each validator (in Gwei)
* @param depositDataRoots The deposit data roots of the validators
*/
function startNonRestakingValidators(
bytes[] calldata pubKeys,
bytes[] calldata signatures,
uint256[] calldata amountsInGwei,
bytes32[] calldata depositDataRoots
) external virtual restricted {
_startValidators(pubKeys, signatures, amountsInGwei, depositDataRoots, false);
}
// End of validators ====================================================
// EigenLayer interactions ==============================================
/**
* @notice Queue withdrawals for the restaking validators on EigenLayer
* @param shareAmount The amount of shares to withdraw (wei)
*/
function queueWithdrawals(uint256 shareAmount) external virtual override restricted {
IDelegationManagerTypes.QueuedWithdrawalParams[] memory withdrawals =
new IDelegationManagerTypes.QueuedWithdrawalParams[](1);
uint256[] memory shares = new uint256[](1);
shares[0] = shareAmount;
IStrategy[] memory strategies = new IStrategy[](1);
strategies[0] = IStrategy(_BEACON_CHAIN_STRATEGY);
withdrawals[0] = IDelegationManagerTypes.QueuedWithdrawalParams({
strategies: strategies,
depositShares: shares,
__deprecated_withdrawer: address(0)
});
EIGEN_DELEGATION_MANAGER.queueWithdrawals(withdrawals);
}
/**
* @notice Completes the queued withdrawals on the EigenLayer
* @param withdrawals The withdrawals to complete
* @param receiveAsTokens Per withdrawal: true to receive the underlying ETH (reducing
* restakedValidatorsETH by the ETH received), false to receive redelegatable shares.
*/
function completeQueuedWithdrawals(
IDelegationManagerTypes.Withdrawal[] calldata withdrawals,
bool[] calldata receiveAsTokens
) external virtual restricted {
uint256 n = withdrawals.length;
require(n == receiveAsTokens.length, InvalidInput());
// The DelegationManager indexes tokens[i] alongside withdrawals[i], so size tokens[] to match.
// Every entry is the same single-element [address(0)] (the beacon-chain ETH token), so share one array.
IERC20[] memory ethToken = new IERC20[](1);
IERC20[][] memory tokens = new IERC20[][](n);
for (uint256 i = 0; i < n; i++) {
require(withdrawals[i].strategies.length == 1 && withdrawals[i].scaledShares.length == 1, InvalidInput());
require(address(withdrawals[i].strategies[0]) == _BEACON_CHAIN_STRATEGY, InvalidInput());
tokens[i] = ethToken;
}
Storage storage $ = _getVaultStorage();
uint256 balanceBefore = _ethPlusWeth();
EIGEN_DELEGATION_MANAGER.completeQueuedWithdrawals({
withdrawals: withdrawals,
tokens: tokens,
receiveAsTokens: receiveAsTokens
});
uint256 balanceAfter = _ethPlusWeth();
uint256 difference = balanceAfter - balanceBefore;
// Saturating subtraction via Math.trySub to avoid an underflow panic
(, uint256 result) = Math.trySub($.restakedValidatorsETH, SafeCast.toUint128(difference));
uint128 newRestakedValidatorsETH = SafeCast.toUint128(result);
$.restakedValidatorsETH = newRestakedValidatorsETH;
emit RestakedValidatorsETHUpdated(newRestakedValidatorsETH);
}
/**
* @notice Request a withdrawal of restaked validators on EigenLayer
* @param requests The requests to withdraw
*/
function requestWithdrawal(IEigenPodTypes.WithdrawalRequest[] calldata requests)
external
payable
virtual
restricted
{
IEigenPod(getEigenPod()).requestWithdrawal{ value: msg.value }(requests);
}
/**
* @notice Request consolidation of restaked validators
* @param srcPubkeys The public keys of the validators to consolidate
* @param targetPubkeys The public keys of the validators to consolidate to
*/
function requestEigenPodConsolidation(bytes[] calldata srcPubkeys, bytes[] calldata targetPubkeys)
external
payable
virtual
restricted
{
IEigenPod.ConsolidationRequest[] memory requests = new IEigenPodTypes.ConsolidationRequest[](srcPubkeys.length);
for (uint256 i = 0; i < srcPubkeys.length; i++) {
requests[i] =
IEigenPodTypes.ConsolidationRequest({ srcPubkey: srcPubkeys[i], targetPubkey: targetPubkeys[i] });
}
// The remainder is donated to the vault and not refunded to the caller
IEigenPod(getEigenPod()).requestConsolidation{ value: msg.value }(requests);
}
// End of EigenLayer interactions =======================================
/**
* @notice Sweep the ETH held by the non-restaking withdrawal credentials contract into the vault and
* update the accounting in the same transaction, so the swept ETH is not counted twice.
* @dev `nonRestakedValidatorsETH` drops by the ETH received, clamped at zero. ETH sent directly to the
* credentials contract is included, so the counter can end up below the real validator balance.
*/
function withdrawNonRestakedETH() external virtual restricted {
uint256 balanceBefore = _ethPlusWeth();
Storage storage $ = _getVaultStorage();
NonRestakingWithdrawalCredentials(payable($.noRestakingWithdrawalCredentials)).withdrawETH();
uint256 balanceAfter = _ethPlusWeth();
uint256 difference = balanceAfter - balanceBefore;
// Saturating subtraction via Math.trySub to avoid an underflow panic
(, uint256 result) = Math.trySub($.nonRestakedValidatorsETH, SafeCast.toUint128(difference));
uint128 newNonRestakedValidatorsETH = SafeCast.toUint128(result);
$.nonRestakedValidatorsETH = newNonRestakedValidatorsETH;
emit NonRestakedValidatorsETHUpdated(newNonRestakedValidatorsETH);
}
/**
* @notice Custom call to the target contract
* @dev Payable is just in case that the owner wants to send ETH instead of using ETH/WETH from the Vault
* @param target The address of the target contract
* @param data The data to call the target contract with
*/
function customExternalCall(address target, bytes calldata data, uint256 value)
external
payable
virtual
restricted
{
// Another check is done to see if the caller is allowed to call the function identified by a selector.
(bool isAllowed,) = IAccessManager(authority()).canCall(_msgSender(), target, bytes4(data));
if (!isAllowed) {
revert AccessManagedUnauthorized(_msgSender());
}
_unwrapWETH(value);
(bool success,) = target.call{ value: value }(data);
emit CustomExternalCall(target, data, value);
require(success, CustomCallFailed());
}
/**
* @notice Set the ETH backing the restaking and non-restaking validators, then accrue fees on the
* rewards earned since the last report.
* @dev The amounts feed totalAssets(); see its natspec.
* @param restakedValidatorsETH The ETH backing the restaking validators
* @param nonRestakedValidatorsETH The ETH backing the non-restaking validators
*/
function setValidatorsETH(uint128 restakedValidatorsETH, uint128 nonRestakedValidatorsETH)
external
virtual
restricted
{
Storage storage $ = _getVaultStorage();
$.restakedValidatorsETH = restakedValidatorsETH;
$.nonRestakedValidatorsETH = nonRestakedValidatorsETH;
emit RestakedValidatorsETHUpdated(restakedValidatorsETH);
emit NonRestakedValidatorsETHUpdated(nonRestakedValidatorsETH);
_accrueFees($);
}
/**
* @notice Replace the fee-recipient list atomically.
*/
function setFeeRecipients(FeeRecipient[] calldata recipients) external virtual restricted {
_setFeeRecipientsInternal(_getVaultStorage(), recipients);
}
/**
* @notice Update the per-report reward allowance.
*/
function setMaxAprBps(uint16 newMax) external virtual restricted {
_checkMaxAprBps(newMax);
_getVaultStorage().maxAprBps = newMax;
emit MaxAprBpsUpdated(newMax);
}
/**
* @notice Update the mutable Σ-recipient-bps fee cap.
* @dev Reverts if `newMax` is below the current Σ recipient bps, so the live list never sits above the cap.
*/
function setMaxTotalFeeBps(uint16 newMax) external virtual restricted {
_checkMaxTotalFeeBps(newMax);
Storage storage $ = _getVaultStorage();
require(_totalFeeBps($) <= newMax, FeeBpsExceedsCap());
$.maxTotalFeeBps = newMax;
emit MaxTotalFeeBpsUpdated(newMax);
}
/**
* @notice Admin mints `shares` to `to` directly, without any assets entering the vault.
* Each existing holder's share value drops because the same assets now back more shares.
* Used to restore a holder who has lost wallet access, or to correct accounting after an error.
* @dev Reverts on `to == address(this)` (SelfRecipient) and on `to == address(0)` (OZ ERC20).
* Restricted to the admin role. Emits AdminMinted.
* `netLPFlowSinceLastReport` is unaffected: this operation moves only shares, not assets,
* so it does not contribute to the oracle's LP-flow accounting.
* @param to The recipient of the newly minted shares.
* @param shares The amount of share tokens to mint.
*/
function adminMint(address to, uint256 shares) external virtual restricted {
require(to != address(this), SelfRecipient());
_mint(to, shares);
emit AdminMinted(_msgSender(), to, shares);
}
/**
* @notice Admin burns `shares` from `from` directly, without any assets leaving the vault.
* Each remaining holder's share value rises because the same assets now back fewer shares.
* Used to clean up a lost wallet's balance, or to correct accounting after an error.
* @dev Reverts on `from == address(this)` (SelfRecipient), on `from == address(0)` (OZ ERC20),
* and on insufficient balance. Restricted to the admin role. Emits AdminBurned.
* `netLPFlowSinceLastReport` is unaffected: this operation moves only shares, not assets,
* so it does not contribute to the oracle's LP-flow accounting.
* @param from The address whose shares are burned.
* @param shares The amount of share tokens to burn.
*/
function adminBurn(address from, uint256 shares) external virtual restricted {
require(from != address(this), SelfRecipient());
_burn(from, shares);
emit AdminBurned(_msgSender(), from, shares);
}
/**
* @notice Admin sends `amount` of `token` to `to`. Pass `token == address(0)` for native ETH.
* Rescues stuck or mistakenly-sent tokens, and can move any asset out of the vault - including
* WETH and ETH that back shares, which lowers the share value for all holders.
* @dev Reverts on `to == address(0)` (ZeroAddress), on `to == address(this)` (SelfRecipient), and on a
* failed native ETH send (EthTransferFailed). Restricted to the admin role; frozen while the vault
* target is paused. Emits Rescued.
* `netLPFlowSinceLastReport` is unaffected: the next oracle report reads the lower totalAssets as
* negative rewards and mints no fees.
* @param token The token to send, or address(0) for native ETH.
* @param to The recipient.
* @param amount The requested amount to send.
*/
function rescueAnything(address token, address to, uint256 amount) external virtual restricted {
require(to != address(0), ZeroAddress());
require(to != address(this), SelfRecipient());
emit Rescued(_msgSender(), token, to, amount);
if (token == address(0)) {
(bool ok,) = payable(to).call{ value: amount }("");
require(ok, EthTransferFailed());
} else {
IERC20(token).safeTransfer(to, amount);
}
}
// Getters ==============================================================
/**
* @dev See {IERC4626-totalAssets}.
* The shares (institutionalETH) are backed by a combination of WETH and ETH. `totalAssets()` is the sum of:
* - WETH held in the vault
* - ETH held in the vault, excluding the current call's msg.value
* - `restakedValidatorsETH`: ETH backing the restaking validators
* - `nonRestakedValidatorsETH`: ETH backing the non-restaking validators
*
* The vault cannot read beacon-chain balances, so `restakedValidatorsETH` and `nonRestakedValidatorsETH`
* are maintained by the oracle via `setValidatorsETH`, and the share exchange rate is only as accurate as
* the latest oracle report. Validator ETH swept into the NonRestakingWithdrawalCredentials contract stays
* counted in `nonRestakedValidatorsETH` until `withdrawNonRestakedETH` moves it into the vault and
* reduces the counter. The reduction tracks the vault's balance change, so ETH sent directly to the
* credentials contract also comes off the counter and leaves `totalAssets()` low until the next report.
*
* Native ETH deposits: msg.value is added to address(this).balance before this runs, so the current call's
* callvalue is subtracted to avoid counting an in-flight deposit twice. callvalue is read via assembly
* because msg.value is unavailable in a view function.
*/
function totalAssets() public view virtual override(ERC4626Upgradeable, IInstitutionalVault) returns (uint256) {
Storage storage $ = _getVaultStorage();
uint256 callValue;
// solhint-disable-next-line no-inline-assembly
assembly {
callValue := callvalue()
}
return WETH.balanceOf(address(this)) + (address(this).balance - callValue) + $.restakedValidatorsETH
+ $.nonRestakedValidatorsETH;
}
/**
* @notice Get the withdrawal credentials for the non restaking validators
* @return The withdrawal credentials
*/
function getWithdrawalCredentials() public view virtual returns (bytes memory) {
Storage storage $ = _getVaultStorage();
require($.noRestakingWithdrawalCredentials != address(0), WithdrawalCredentialsNotSet());
return _encodeWithdrawalCredentials($.noRestakingWithdrawalCredentials);
}
/**
* @notice Get the withdrawal credentials for the restaking validators
* @return The withdrawal credentials
*/
function getEigenPodWithdrawalCredentials() public view virtual returns (bytes memory) {
return _encodeWithdrawalCredentials(_getVaultStorage().eigenPod);
}
/**
* @notice Get the address of the EigenPod
* @return The address of the EigenPod
*/
function getEigenPod() public view virtual returns (address) {
return _getVaultStorage().eigenPod;
}
/**
* @notice Get the ETH backing the restaking validators
* @return The ETH backing the restaking validators
*/
function getRestakedValidatorETH() public view virtual returns (uint256) {
return _getVaultStorage().restakedValidatorsETH;
}
/**
* @notice Get the ETH backing the non-restaking validators
* @return The ETH backing the non-restaking validators
*/
function getNonRestakedValidatorETH() public view virtual returns (uint256) {
return _getVaultStorage().nonRestakedValidatorsETH;
}
/**
* @notice Get the address of the no restaking withdrawal credentials
* @return The address of the no restaking withdrawal credentials
*/
function getNoRestakingWithdrawalCredentials() public view virtual returns (address) {
return _getVaultStorage().noRestakingWithdrawalCredentials;
}
/// @notice Get the current fee-recipient list.
function getFeeRecipients() external view returns (FeeRecipient[] memory) {
return _getVaultStorage().feeRecipients;
}
/// @notice Get the totalAssets snapshot taken at the last oracle report.
function getLastTotalAssets() external view returns (uint128) {
return _getVaultStorage().lastTotalAssets;
}
/// @notice Get the net LP deposit-minus-withdrawal flow since the last oracle report.
function getNetLPFlow() external view returns (int128) {
return _getVaultStorage().netLPFlowSinceLastReport;
}
/// @notice Get the timestamp of the last fee-accrual report.
function getLastReportTimestamp() external view returns (uint64) {
return _getVaultStorage().lastReportTimestamp;
}
/// @notice Get the per-report reward allowance, in basis points.
function getMaxAprBps() external view returns (uint16) {
return _getVaultStorage().maxAprBps;
}
/// @notice Get the cap on the sum of recipient fee bps, in basis points.
function getMaxTotalFeeBps() external view returns (uint16) {
return _getVaultStorage().maxTotalFeeBps;
}
// Internal functions ===================================================
/// @dev Deposit each validator's ETH to the beacon deposit contract and add the total to the matching counter.
function _startValidators(
bytes[] calldata pubKeys,
bytes[] calldata signatures,
uint256[] calldata amountsInGwei,
bytes32[] calldata depositDataRoots,
bool restakedValidators
) internal {
require(
pubKeys.length == signatures.length && pubKeys.length == amountsInGwei.length
&& pubKeys.length == depositDataRoots.length,
InvalidInput()
);
uint256 totalAmount;
for (uint256 i = 0; i < pubKeys.length; i++) {
totalAmount += amountsInGwei[i];
}
totalAmount = _convertGweiToWei(totalAmount);
_unwrapWETH(totalAmount);
bytes memory withdrawalCredentials =
restakedValidators ? getEigenPodWithdrawalCredentials() : getWithdrawalCredentials();
for (uint256 i = 0; i < pubKeys.length; i++) {
BEACON_DEPOSIT_CONTRACT.deposit{ value: _convertGweiToWei(amountsInGwei[i]) }(
pubKeys[i], withdrawalCredentials, signatures[i], depositDataRoots[i]
);
if (restakedValidators) {
emit StartedRestakingValidator(pubKeys[i], amountsInGwei[i]);
} else {
emit StartedNonRestakingValidator(pubKeys[i], amountsInGwei[i]);
}
}
Storage storage $ = _getVaultStorage();
if (restakedValidators) {
$.restakedValidatorsETH += SafeCast.toUint128(totalAmount);
emit RestakedValidatorsETHUpdated($.restakedValidatorsETH);
} else {
$.nonRestakedValidatorsETH += SafeCast.toUint128(totalAmount);
emit NonRestakedValidatorsETHUpdated($.nonRestakedValidatorsETH);
}
}
/**
* @notice Accrue consensus-rewards fees since the last oracle report.
* @dev The rewards signal is `ΔtotalAssets − netLPFlowSinceLastReport`
*/
function _accrueFees(Storage storage $) internal virtual {
uint256 newTA = totalAssets();
int256 rawDelta = int256(newTA) - int256(uint256($.lastTotalAssets));
int256 rewards = rawDelta - int256($.netLPFlowSinceLastReport);
if (rewards > 0) {
uint256 r = uint256(rewards);
uint256 elapsed = block.timestamp - uint256($.lastReportTimestamp);
uint256 maxRewards =
(uint256($.maxAprBps) * uint256($.lastTotalAssets) * elapsed) / SECONDS_PER_YEAR / BPS_DENOMINATOR;
// Circuit breaker: rewards above the allowance revert; the admin raises maxAprBps for a real spike.
// Skipped below MIN_APR_BREAKER_BASELINE, where the percentage bound can be smaller than a real reward.
if ($.lastTotalAssets > MIN_APR_BREAKER_BASELINE) {
require(r <= maxRewards, RewardsExceedSanityBound());
}
_mintFeeShares($, r, newTA);
}
$.lastTotalAssets = SafeCast.toUint128(newTA);
$.netLPFlowSinceLastReport = 0;
$.lastReportTimestamp = uint64(block.timestamp);
emit FeesAccrued(rewards, newTA);
}
/**
* @notice Mint fee shares, split pro-rata among recipients.
* @dev Single mint sized by Σ bps; the last recipient absorbs rounding dust so the total minted
* matches the formula exactly. Recipient i ends up with shares worth bps_i/10_000 × rewards.
*/
function _mintFeeShares(Storage storage $, uint256 rewards, uint256 newTA) internal virtual {
uint256 n = $.feeRecipients.length;
if (n == 0) return;
uint256 totalBps = _totalFeeBps($);
if (totalBps == 0) return;
uint256 numByBps = rewards * totalBps;
uint256 denom = newTA * BPS_DENOMINATOR;
uint256 feeShares = Math.mulDiv(numByBps, totalSupply(), denom - numByBps);
uint256 distributed;
for (uint256 i; i < n - 1; ++i) {
FeeRecipient storage feeRecipient = $.feeRecipients[i];
address recipient = feeRecipient.recipient;
uint16 bps = feeRecipient.bps;
uint256 share = Math.mulDiv(feeShares, bps, totalBps);
_mint(recipient, share);
emit FeeDistributed(recipient, share, bps);
distributed += share;
}
FeeRecipient storage lastRecipient = $.feeRecipients[n - 1];
address lastRecipientAddress = lastRecipient.recipient;
uint256 lastShare = feeShares - distributed;
_mint(lastRecipientAddress, lastShare);
emit FeeDistributed(lastRecipientAddress, lastShare, lastRecipient.bps);
emit FeeSharesMinted(feeShares, totalBps);
}
/// @dev Reject exit receivers that would destroy the payout: the zero address strands it, and the vault
/// itself hands it to the remaining holders. Same guards `rescueAnything` applies.
function _checkExitReceiver(address receiver) internal view {
require(receiver != address(0), ZeroAddress());
require(receiver != address(this), SelfRecipient());
}
/// @dev Bounds check for the per-report reward allowance.
function _checkMaxAprBps(uint16 value) internal pure {
require(value > 0 && value <= BPS_DENOMINATOR, InvalidMaxAprBps());
}
/// @dev Bounds check for the Σ-recipient-bps fee cap.
function _checkMaxTotalFeeBps(uint16 value) internal pure {
require(value > 0 && value <= HARD_FEE_BPS_CAP, InvalidMaxTotalFeeBps());
}
/// @dev A 0x02 compounding withdrawal credential pointing at `target`.
function _encodeWithdrawalCredentials(address target) internal pure returns (bytes memory) {
return abi.encodePacked(bytes1(uint8(2)), bytes11(0), target);
}
/// @dev Sum of the current recipients' fee bps.
function _totalFeeBps(Storage storage $) internal view returns (uint256 totalBps) {
uint256 len = $.feeRecipients.length;
for (uint256 i; i < len; ++i) {
totalBps += $.feeRecipients[i].bps;
}
}
/// @dev Replace the fee-recipient list, rejecting zero and self recipients and enforcing the total-bps cap.
function _setFeeRecipientsInternal(Storage storage $, FeeRecipient[] calldata recipients) internal {
delete $.feeRecipients;
uint256 totalBps;
uint256 len = recipients.length;
for (uint256 i; i < len; ++i) {
require(recipients[i].recipient != address(0), ZeroAddressRecipient());
require(recipients[i].recipient != address(this), SelfRecipient());
require(recipients[i].bps != 0, ZeroFeeBps());
totalBps += recipients[i].bps;
$.feeRecipients.push(recipients[i]);
}
require(totalBps <= $.maxTotalFeeBps, FeeBpsExceedsCap());
emit FeeRecipientsUpdated(recipients);
}
/**
* @notice Shared native-ETH exit path for redeemETH and withdrawETH.
* @dev Spends the caller's allowance when it is not the owner, burns the shares, unwraps WETH, and sends
* native ETH to the receiver. Native exits bypass the ERC4626 _withdraw hook, so the net-LP-flow
* decrement that the hook applies is mirrored here.
*/
function _exitNativeETH(uint256 assets, uint256 shares, address receiver, address owner) internal virtual {
_checkExitReceiver(receiver);
address caller = _msgSender();
if (caller != owner) {
_spendAllowance(owner, caller, shares);
}
_burn(owner, shares);
_decreaseNetLPFlow(assets);
_unwrapWETH(assets);
(bool success,) = receiver.call{ value: assets }("");
require(success, EthTransferFailed());
emit Withdraw(caller, receiver, owner, assets, shares);
emit WithdrawnETH(caller, receiver, owner, assets, shares);
}
/**
* @notice Wraps the vault's ETH balance to WETH
* @dev Used to provide WETH liquidity
*/
function _wrapETH(uint256 assets) internal virtual {
uint256 balance = address(this).balance;
uint256 wethBalance = WETH.balanceOf(address(this));
if (wethBalance >= assets) {
return;
}
uint256 amountToWrap;
unchecked {
amountToWrap = assets - wethBalance;
}
if (balance >= amountToWrap) {
WETH.deposit{ value: amountToWrap }();
} else {
revert NotEnoughETH();
}
}
/**
* @notice Unwrap only what is needed
* @param assets The amount of WETH to unwrap
*/
function _unwrapWETH(uint256 assets) internal virtual {
uint256 balance = address(this).balance;
uint256 wethBalance = WETH.balanceOf(address(this));
if (balance >= assets) {
return;
}
uint256 amountToUnwrap;
unchecked {
amountToUnwrap = assets - balance;
}
if (wethBalance >= amountToUnwrap) {
WETH.withdraw(amountToUnwrap);
} else {
revert NotEnoughWETH();
}
}
/// @dev The vault's spendable balance: native ETH plus WETH holdings.
function _ethPlusWeth() internal view returns (uint256) {
return address(this).balance + WETH.balanceOf(address(this));
}
/**
* @notice Convert Gwei to Wei
* @param amount The amount of Gwei
* @return The amount of Wei
*/
function _convertGweiToWei(uint256 amount) internal pure returns (uint256) {
return amount * 1e9;
}
/**
* @notice Authorize the upgrade of the vault
* @param newImplementation The address of the new implementation
*/
function _authorizeUpgrade(address newImplementation) internal virtual override restricted { }
/// @dev Record an LP deposit so the next oracle report can subtract it from the rewards signal.
function _increaseNetLPFlow(uint256 assets) internal {
_getVaultStorage().netLPFlowSinceLastReport += SafeCast.toInt128(SafeCast.toInt256(assets));
}
/// @dev Record an LP withdrawal so the next oracle report does not mistake it for a loss.
function _decreaseNetLPFlow(uint256 assets) internal {
_getVaultStorage().netLPFlowSinceLastReport -= SafeCast.toInt128(SafeCast.toInt256(assets));
}
/**
* @dev OZ ERC4626 hook. Bumps netLPFlow on deposit/mint so the next oracle report can subtract
* LP-driven asset growth from the rewards signal. `depositETH` instruments itself directly.
* Rejects a zero-share mint, so a deposit that rounds down to nothing reverts.
*/
function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual override {
require(shares != 0, ZeroShares());
super._deposit(caller, receiver, assets, shares);
_increaseNetLPFlow(assets);
}
/**
* @dev OZ ERC4626 hook. Decrements netLPFlow on withdraw/redeem and guards the WETH exit receiver.
*/
function _withdraw(address caller, address receiver, address owner, uint256 assets, uint256 shares)
internal
virtual
override
{
_checkExitReceiver(receiver);
super._withdraw(caller, receiver, owner, assets, shares);
_decreaseNetLPFlow(assets);
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"@openzeppelin/contracts-upgradeable/=dependencies/@openzeppelin-contracts-upgradeable-5.1.0/",
"@openzeppelin/contracts/=dependencies/@openzeppelin-contracts-5.1.0/",
"forge-std/=dependencies/forge-std-1.9.5/src/",
"@openzeppelin-contracts-5.1.0/=dependencies/@openzeppelin-contracts-5.1.0/",
"@openzeppelin-contracts-upgradeable-5.1.0/=dependencies/@openzeppelin-contracts-upgradeable-5.1.0/",
"forge-std-1.9.5/=dependencies/forge-std-1.9.5/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.