Overview
ETH Balance
0 ETH
Eth Value
$0.00More Info
Private Name Tags
ContractCreator
View more zero value Internal Transactions in Advanced View mode
Advanced mode:
Loading...
Loading
Contract Source Code Verified (Exact Match)
Contract Name:
ynETH
Compiler Version
v0.8.24+commit.e11b9ed9
Optimization Enabled:
Yes with 200 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: BSD 3-Clause License pragma solidity ^0.8.24; import {Math} from "lib/openzeppelin-contracts/contracts/utils/math/Math.sol"; import {IStakingNodesManager} from "src/interfaces/IStakingNodesManager.sol"; import {IRewardsDistributor} from "src/interfaces/IRewardsDistributor.sol"; import {IynETH} from "src/interfaces/IynETH.sol"; import {ynBase} from "src/ynBase.sol"; interface IYnETHEvents { event DepositETHPausedUpdated(bool isPaused); event Deposit(address indexed sender, address indexed receiver, uint256 assets, uint256 shares, uint256 totalDepositedInPool); event RewardsReceived(uint256 value, uint256 totalDepositedInPool); event ETHWithdrawn(uint256 ethAmount, uint256 totalDepositedInPool); event WithdrawnETHProcessed(uint256 ethAmount, uint256 totalDepositedInPool); } /** * @title ynETH * @dev The ynETH contract is a core component of the YieldNEst restaking protocol, facilitating the native restaking of ETH /// management of staking nodes, and distribution of rewards. It serves as the entry point for users to deposit ETH /// in exchange for ynETH tokens, representing their share of the staked ETH. */ contract ynETH is IynETH, ynBase, IYnETHEvents { //-------------------------------------------------------------------------------------- //---------------------------------- ERRORS ------------------------------------------- //-------------------------------------------------------------------------------------- error Paused(); error ZeroAddress(); error ZeroETH(); error NoDirectETHDeposit(); error CallerNotStakingNodeManager(address expected, address provided); error NotRewardsDistributor(address caller); error InsufficientBalance(); error TransferFailed(); error CallerNotAuthorized(address caller); error ZeroShares(); //-------------------------------------------------------------------------------------- //---------------------------------- ROLES -------------------------------------------- //-------------------------------------------------------------------------------------- bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); //-------------------------------------------------------------------------------------- //---------------------------------- VARIABLES --------------------------------------- //-------------------------------------------------------------------------------------- IStakingNodesManager public stakingNodesManager; IRewardsDistributor public rewardsDistributor; bool public depositsPaused; uint256 public totalDepositedInPool; //-------------------------------------------------------------------------------------- //---------------------------------- INITIALIZATION ---------------------------------- //-------------------------------------------------------------------------------------- /** * @notice Configuration for contract initialization. */ struct Init { address admin; address pauser; address unpauser; IStakingNodesManager stakingNodesManager; IRewardsDistributor rewardsDistributor; address[] pauseWhitelist; } constructor() { _disableInitializers(); } /** * @notice Initializes the contract. * @dev MUST be called during the contract upgrade to set up the proxies state. */ function initialize(Init memory init) external notZeroAddress(init.admin) notZeroAddress(init.pauser) notZeroAddress(init.unpauser) notZeroAddress(address(init.stakingNodesManager)) notZeroAddress(address(init.rewardsDistributor)) initializer { __AccessControl_init(); __ynBase_init("ynETH", "ynETH"); _grantRole(DEFAULT_ADMIN_ROLE, init.admin); _grantRole(PAUSER_ROLE, init.pauser); _grantRole(UNPAUSER_ROLE, init.unpauser); stakingNodesManager = init.stakingNodesManager; rewardsDistributor = init.rewardsDistributor; _setTransfersPaused(true); // transfers are initially paused _updatePauseWhitelist(init.pauseWhitelist, true); } receive() external payable { revert NoDirectETHDeposit(); } //-------------------------------------------------------------------------------------- //---------------------------------- DEPOSITS --------------------------------------- //-------------------------------------------------------------------------------------- /** * @notice Allows depositing ETH into the contract in exchange for shares. * @dev Mints shares equivalent to the deposited ETH value and assigns them to the receiver. * @param receiver The address to receive the minted shares. * @return shares The amount of shares minted for the deposited ETH. */ function depositETH(address receiver) public payable returns (uint256 shares) { if (depositsPaused) { revert Paused(); } if (msg.value == 0) { revert ZeroETH(); } uint256 assets = msg.value; shares = previewDeposit(assets); if (shares == 0) { revert ZeroShares(); } _mint(receiver, shares); totalDepositedInPool += assets; emit Deposit(msg.sender, receiver, assets, shares, totalDepositedInPool); } /** * @notice Calculates the amount of shares to be minted for a given deposit. * @param assets The amount of assets to be deposited. * @return The amount of shares to be minted. */ function previewDeposit(uint256 assets) public view virtual returns (uint256) { return _convertToShares(assets, Math.Rounding.Floor); } /** * @notice Converts a given amount of assets to shares. * @param assets The amount of assets to be converted. * @return shares The equivalent amount of shares. */ function convertToShares(uint256 assets) public view returns (uint256 shares) { return _convertToShares(assets, Math.Rounding.Floor); } /** * @notice Converts from ynETH to ETH using the current exchange rate. * The exchange rate is given by the total supply of ynETH and total ETH controlled by the protocol. */ function _convertToShares(uint256 ethAmount, Math.Rounding rounding) internal view returns (uint256) { // 1:1 exchange rate on the first stake. // Use totalSupply to see if this is the boostrap call, not totalAssets if (totalSupply() == 0) { return ethAmount; } // deltaynETH = (ynETHSupply / totalControlled) * ethAmount return Math.mulDiv( ethAmount, totalSupply(), totalAssets(), rounding ); } //-------------------------------------------------------------------------------------- //---------------------------------- WITHDRAWALS -------------------------------------- //-------------------------------------------------------------------------------------- /** * @notice Calculates the amount of assets that would be redeemed for a given amount of shares at current block * @param shares The amount of shares to redeem. * @return assets The equivalent amount of assets. */ function previewRedeem(uint256 shares) external view returns (uint256 assets) { return _convertToAssets(shares, Math.Rounding.Floor); } /** * @notice Converts a given amount of shares to assets at current block * @param shares The amount of shares to convert. * @return assets The equivalent amount of assets. */ function convertToAssets(uint256 shares) external view returns (uint256 assets) { return _convertToAssets(shares, Math.Rounding.Floor); } /** * @dev Internal implementation of {convertToAssets}. */ function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view returns (uint256) { uint256 supply = totalSupply(); // 1:1 exchange rate on the first stake. // Use totalSupply to see if this call is made before boostrap call, not totalAssets if (supply == 0) { return shares; } return Math.mulDiv(shares, totalAssets(), supply, rounding); } function burn(uint256 amount) external onlyRole(BURNER_ROLE) { _burn(msg.sender, amount); } //-------------------------------------------------------------------------------------- //---------------------------------- ASSETS ------------------------------------------- //-------------------------------------------------------------------------------------- /** * @notice Calculates the total assets controlled by the protocol. * @dev This includes both the ETH deposited in the pool awaiting processing and the ETH already sent to validators on the beacon chain. * @return total The total amount of ETH in wei. */ function totalAssets() public view returns (uint256) { uint256 total = 0; // Allocated ETH for deposits pending to be processed. total += totalDepositedInPool; // The total ETH sent to the beacon chain. total += totalDeposited(); return total; } /** * @notice Returns the total amount of ETH deposited across all validators. * @return totalDeposited The total amount of ETH deposited in all validators. */ function totalDeposited() internal view returns (uint256) { return stakingNodesManager.totalDeposited(); } //-------------------------------------------------------------------------------------- //---------------------------------- STAKING/UNSTAKING and REWARDS ------------------- //-------------------------------------------------------------------------------------- /** * @dev Receives rewards in ETH and adds them to the total deposited in the pool. * Only the rewards distributor contract can call this function. * Reverts if called by any address other than the rewards distributor. */ function receiveRewards() external payable { if (msg.sender != address(rewardsDistributor)) { revert NotRewardsDistributor(msg.sender); } totalDepositedInPool += msg.value; emit RewardsReceived(msg.value, totalDepositedInPool); } /** * @dev Withdraws a specified amount of ETH from the pool to the Staking Nodes Manager. * This function can only be called by the Staking Nodes Manager. * @param ethAmount The amount of ETH to withdraw in wei. */ function withdrawETH(uint256 ethAmount) public onlyStakingNodesManager override { uint256 currentTotalDepositedInPool = totalDepositedInPool; // Check if the pool has enough ETH to fulfill the withdrawal request. if (currentTotalDepositedInPool < ethAmount) { revert InsufficientBalance(); } // Deduct the withdrawal amount from the total deposited in the pool. uint256 newTotalDepositedInPool = currentTotalDepositedInPool - ethAmount; totalDepositedInPool = newTotalDepositedInPool; // Transfer the specified amount of ETH to the Staking Nodes Manager. (bool success, ) = payable(address(stakingNodesManager)).call{value: ethAmount}(""); if (!success) { revert TransferFailed(); } emit ETHWithdrawn(ethAmount, newTotalDepositedInPool); } /** * @dev Processes ETH that has been withdrawn from the staking nodes and adds it to the pool. * This function can only be called by the Staking Nodes Manager. * It increases the total deposited in the pool by the amount of ETH sent with the call. */ function processWithdrawnETH() public payable { // ETH can be returned either by the stakingNodesManager or by the redemptionAssetsVault if (!(msg.sender == address(stakingNodesManager) || msg.sender == (address(stakingNodesManager.redemptionAssetsVault())))) { revert CallerNotAuthorized(msg.sender); } totalDepositedInPool += msg.value; emit WithdrawnETHProcessed(msg.value, totalDepositedInPool); } //-------------------------------------------------------------------------------------- //---------------------------------- PAUSING ----------------------------------------- //-------------------------------------------------------------------------------------- /** * @notice Pauses ETH deposits. * @dev Can only be called by an account with the PAUSER_ROLE. */ function pauseDeposits() external onlyRole(PAUSER_ROLE) { depositsPaused = true; emit DepositETHPausedUpdated(depositsPaused); } /** * @notice Unpauses ETH deposits. * @dev Can only be called by an account with the UNPAUSER_ROLE. */ function unpauseDeposits() external onlyRole(UNPAUSER_ROLE) { depositsPaused = false; emit DepositETHPausedUpdated(depositsPaused); } //-------------------------------------------------------------------------------------- //---------------------------------- MODIFIERS --------------------------------------- //-------------------------------------------------------------------------------------- /** * @dev Ensures that the function is only called by the Staking Nodes Manager. */ modifier onlyStakingNodesManager() { if (msg.sender != address(stakingNodesManager)) { revert CallerNotStakingNodeManager( address(stakingNodesManager), msg.sender ); } _; } /** * @notice Ensure that the given address is not the zero address. * @param _address The address to check. */ modifier notZeroAddress(address _address) { if (_address == address(0)) { revert ZeroAddress(); } _; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol) pragma solidity ^0.8.20; import {Panic} from "../Panic.sol"; import {SafeCast} from "./SafeCast.sol"; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { enum Rounding { Floor, // Toward negative infinity Ceil, // Toward positive infinity Trunc, // Toward zero Expand // Away from zero } /** * @dev Returns the addition of two unsigned integers, with an success flag (no overflow). */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow). */ function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow). */ function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a success flag (no division by zero). */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero). */ function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant. * * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone. * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute * one branch when needed, making this function more expensive. */ function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) { unchecked { // branchless ternary works because: // b ^ (a ^ b) == a // b ^ 0 == b return b ^ ((a ^ b) * SafeCast.toUint(condition)); } } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return ternary(a > b, a, b); } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return ternary(a < b, a, b); } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds towards infinity instead * of rounding towards zero. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { if (b == 0) { // Guarantee the same behavior as in a regular Solidity division. Panic.panic(Panic.DIVISION_BY_ZERO); } // The following calculation ensures accurate ceiling division without overflow. // Since a is non-zero, (a - 1) / b will not overflow. // The largest possible result occurs when (a - 1) / b is type(uint256).max, // but the largest value we can obtain is type(uint256).max - 1, which happens // when a = type(uint256).max and b = 1. unchecked { return SafeCast.toUint(a > 0) * ((a - 1) / b + 1); } } /** * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or * denominator == 0. * * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by * Uniswap Labs also under MIT license. */ function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2²⁵⁶ + prod0. uint256 prod0 = x * y; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { // Solidity will revert if denominator == 0, unlike the div opcode on its own. // The surrounding unchecked block does not change this fact. // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic. return prod0 / denominator; } // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0. if (denominator <= prod1) { Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW)); } /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. // Always >= 1. See https://cs.stackexchange.com/q/138556/92363. uint256 twos = denominator & (0 - denominator); assembly { // Divide denominator by twos. denominator := div(denominator, twos) // Divide [prod1 prod0] by twos. prod0 := div(prod0, twos) // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one. twos := add(div(sub(0, twos), twos), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * twos; // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv ≡ 1 mod 2⁴. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also // works in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2⁸ inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶ inverse *= 2 - denominator * inverse; // inverse mod 2³² inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴ inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸ inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶ // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /** * @dev Calculates x * y / denominator with full precision, following the selected rounding direction. */ function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) { return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0); } /** * @dev Calculate the modular multiplicative inverse of a number in Z/nZ. * * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, expect 0. * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible. * * If the input value is not inversible, 0 is returned. * * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}. */ function invMod(uint256 a, uint256 n) internal pure returns (uint256) { unchecked { if (n == 0) return 0; // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version) // Used to compute integers x and y such that: ax + ny = gcd(a, n). // When the gcd is 1, then the inverse of a modulo n exists and it's x. // ax + ny = 1 // ax = 1 + (-y)n // ax ≡ 1 (mod n) # x is the inverse of a modulo n // If the remainder is 0 the gcd is n right away. uint256 remainder = a % n; uint256 gcd = n; // Therefore the initial coefficients are: // ax + ny = gcd(a, n) = n // 0a + 1n = n int256 x = 0; int256 y = 1; while (remainder != 0) { uint256 quotient = gcd / remainder; (gcd, remainder) = ( // The old remainder is the next gcd to try. remainder, // Compute the next remainder. // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd // where gcd is at most n (capped to type(uint256).max) gcd - remainder * quotient ); (x, y) = ( // Increment the coefficient of a. y, // Decrement the coefficient of n. // Can overflow, but the result is casted to uint256 so that the // next value of y is "wrapped around" to a value between 0 and n - 1. x - y * int256(quotient) ); } if (gcd != 1) return 0; // No inverse exists. return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative. } } /** * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`. * * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that * `a**(p-2)` is the modular multiplicative inverse of a in Fp. * * NOTE: this function does NOT check that `p` is a prime greater than `2`. */ function invModPrime(uint256 a, uint256 p) internal view returns (uint256) { unchecked { return Math.modExp(a, p - 2, p); } } /** * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m) * * Requirements: * - modulus can't be zero * - underlying staticcall to precompile must succeed * * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make * sure the chain you're using it on supports the precompiled contract for modular exponentiation * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, * the underlying function will succeed given the lack of a revert, but the result may be incorrectly * interpreted as 0. */ function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) { (bool success, uint256 result) = tryModExp(b, e, m); if (!success) { Panic.panic(Panic.DIVISION_BY_ZERO); } return result; } /** * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m). * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying * to operate modulo 0 or if the underlying precompile reverted. * * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack * of a revert, but the result may be incorrectly interpreted as 0. */ function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) { if (m == 0) return (false, 0); /// @solidity memory-safe-assembly assembly { let ptr := mload(0x40) // | Offset | Content | Content (Hex) | // |-----------|------------|--------------------------------------------------------------------| // | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 | // | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 | // | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 | // | 0x60:0x7f | value of b | 0x<.............................................................b> | // | 0x80:0x9f | value of e | 0x<.............................................................e> | // | 0xa0:0xbf | value of m | 0x<.............................................................m> | mstore(ptr, 0x20) mstore(add(ptr, 0x20), 0x20) mstore(add(ptr, 0x40), 0x20) mstore(add(ptr, 0x60), b) mstore(add(ptr, 0x80), e) mstore(add(ptr, 0xa0), m) // Given the result < m, it's guaranteed to fit in 32 bytes, // so we can use the memory scratch space located at offset 0. success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20) result := mload(0x00) } } /** * @dev Variant of {modExp} that supports inputs of arbitrary length. */ function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) { (bool success, bytes memory result) = tryModExp(b, e, m); if (!success) { Panic.panic(Panic.DIVISION_BY_ZERO); } return result; } /** * @dev Variant of {tryModExp} that supports inputs of arbitrary length. */ function tryModExp( bytes memory b, bytes memory e, bytes memory m ) internal view returns (bool success, bytes memory result) { if (_zeroBytes(m)) return (false, new bytes(0)); uint256 mLen = m.length; // Encode call args in result and move the free memory pointer result = abi.encodePacked(b.length, e.length, mLen, b, e, m); /// @solidity memory-safe-assembly assembly { let dataPtr := add(result, 0x20) // Write result on top of args to avoid allocating extra memory. success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen) // Overwrite the length. // result.length > returndatasize() is guaranteed because returndatasize() == m.length mstore(result, mLen) // Set the memory pointer after the returned data. mstore(0x40, add(dataPtr, mLen)) } } /** * @dev Returns whether the provided byte array is zero. */ function _zeroBytes(bytes memory byteArray) private pure returns (bool) { for (uint256 i = 0; i < byteArray.length; ++i) { if (byteArray[i] != 0) { return false; } } return true; } /** * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded * towards zero. * * This method is based on Newton's method for computing square roots; the algorithm is restricted to only * using integer operations. */ function sqrt(uint256 a) internal pure returns (uint256) { unchecked { // Take care of easy edge cases when a == 0 or a == 1 if (a <= 1) { return a; } // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between // the current value as `ε_n = | x_n - sqrt(a) |`. // // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is // bigger than any uint256. // // By noticing that // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)` // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar // to the msb function. uint256 aa = a; uint256 xn = 1; if (aa >= (1 << 128)) { aa >>= 128; xn <<= 64; } if (aa >= (1 << 64)) { aa >>= 64; xn <<= 32; } if (aa >= (1 << 32)) { aa >>= 32; xn <<= 16; } if (aa >= (1 << 16)) { aa >>= 16; xn <<= 8; } if (aa >= (1 << 8)) { aa >>= 8; xn <<= 4; } if (aa >= (1 << 4)) { aa >>= 4; xn <<= 2; } if (aa >= (1 << 2)) { xn <<= 1; } // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1). // // We can refine our estimation by noticing that the middle of that interval minimizes the error. // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2). // This is going to be our x_0 (and ε_0) xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2) // From here, Newton's method give us: // x_{n+1} = (x_n + a / x_n) / 2 // // One should note that: // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a // = ((x_n² + a) / (2 * x_n))² - a // = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a // = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²) // = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²) // = (x_n² - a)² / (2 * x_n)² // = ((x_n² - a) / (2 * x_n))² // ≥ 0 // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n // // This gives us the proof of quadratic convergence of the sequence: // ε_{n+1} = | x_{n+1} - sqrt(a) | // = | (x_n + a / x_n) / 2 - sqrt(a) | // = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) | // = | (x_n - sqrt(a))² / (2 * x_n) | // = | ε_n² / (2 * x_n) | // = ε_n² / | (2 * x_n) | // // For the first iteration, we have a special case where x_0 is known: // ε_1 = ε_0² / | (2 * x_0) | // ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2))) // ≤ 2**(2*e-4) / (3 * 2**(e-1)) // ≤ 2**(e-3) / 3 // ≤ 2**(e-3-log2(3)) // ≤ 2**(e-4.5) // // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n: // ε_{n+1} = ε_n² / | (2 * x_n) | // ≤ (2**(e-k))² / (2 * 2**(e-1)) // ≤ 2**(2*e-2*k) / 2**e // ≤ 2**(e-2*k) xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5 xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9 xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18 xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36 xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72 // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either // sqrt(a) or sqrt(a) + 1. return xn - SafeCast.toUint(xn > a / xn); } } /** * @dev Calculates sqrt(a), following the selected rounding direction. */ function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = sqrt(a); return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a); } } /** * @dev Return the log in base 2 of a positive value rounded towards zero. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; uint256 exp; unchecked { exp = 128 * SafeCast.toUint(value > (1 << 128) - 1); value >>= exp; result += exp; exp = 64 * SafeCast.toUint(value > (1 << 64) - 1); value >>= exp; result += exp; exp = 32 * SafeCast.toUint(value > (1 << 32) - 1); value >>= exp; result += exp; exp = 16 * SafeCast.toUint(value > (1 << 16) - 1); value >>= exp; result += exp; exp = 8 * SafeCast.toUint(value > (1 << 8) - 1); value >>= exp; result += exp; exp = 4 * SafeCast.toUint(value > (1 << 4) - 1); value >>= exp; result += exp; exp = 2 * SafeCast.toUint(value > (1 << 2) - 1); value >>= exp; result += exp; result += SafeCast.toUint(value > 1); } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value); } } /** * @dev Return the log in base 10 of a positive value rounded towards zero. * Returns 0 if given 0. */ function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log10(value); return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value); } } /** * @dev Return the log in base 256 of a positive value rounded towards zero. * Returns 0 if given 0. * * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. */ function log256(uint256 value) internal pure returns (uint256) { uint256 result = 0; uint256 isGt; unchecked { isGt = SafeCast.toUint(value > (1 << 128) - 1); value >>= isGt * 128; result += isGt * 16; isGt = SafeCast.toUint(value > (1 << 64) - 1); value >>= isGt * 64; result += isGt * 8; isGt = SafeCast.toUint(value > (1 << 32) - 1); value >>= isGt * 32; result += isGt * 4; isGt = SafeCast.toUint(value > (1 << 16) - 1); value >>= isGt * 16; result += isGt * 2; result += SafeCast.toUint(value > (1 << 8) - 1); } return result; } /** * @dev Return the log in base 256, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value); } } /** * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers. */ function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) { return uint8(rounding) % 2 == 1; } }
// SPDX-License-Identifier: BSD 3-Clause License pragma solidity ^0.8.24; import {UpgradeableBeacon} from "lib/openzeppelin-contracts/contracts/proxy/beacon/UpgradeableBeacon.sol"; import {IDelegationManager} from "lib/eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; import {IStrategyManager} from "lib/eigenlayer-contracts/src/contracts/interfaces/IStrategyManager.sol"; import {RewardsType} from "src/interfaces/IRewardsDistributor.sol"; import {IEigenPodManager} from "lib/eigenlayer-contracts/src/contracts/interfaces/IEigenPodManager.sol"; import {IStakingNode} from "src/interfaces/IStakingNode.sol"; import {IRedemptionAssetsVault} from "src/interfaces/IRedemptionAssetsVault.sol"; interface IStakingNodesManager { struct ValidatorData { bytes publicKey; bytes signature; bytes32 depositDataRoot; uint256 nodeId; } struct Validator { bytes publicKey; uint256 nodeId; } struct WithdrawalAction { uint256 nodeId; uint256 amountToReinvest; uint256 amountToQueue; uint256 rewardsAmount; } function eigenPodManager() external view returns (IEigenPodManager); function delegationManager() external view returns (IDelegationManager); function strategyManager() external view returns (IStrategyManager); function getAllValidators() external view returns (Validator[] memory); function getAllNodes() external view returns (IStakingNode[] memory); function isStakingNodesOperator(address) external view returns (bool); function isStakingNodesDelegator(address _address) external view returns (bool); function processRewards(uint256 nodeId, RewardsType rewardsType) external payable; function registerValidators( ValidatorData[] calldata _depositData ) external; function nodesLength() external view returns (uint256); function upgradeableBeacon() external returns (UpgradeableBeacon); function totalDeposited() external view returns (uint256); function processPrincipalWithdrawals( WithdrawalAction[] memory actions ) external; function redemptionAssetsVault() external returns (IRedemptionAssetsVault); function isStakingNodesWithdrawer(address _address) external view returns (bool); function nodes(uint256 index) external view returns (IStakingNode); }
// SPDX-License-Identifier: BSD 3-Clause License pragma solidity ^0.8.24; import {IRewardsReceiver} from "src/interfaces/IRewardsReceiver.sol"; enum RewardsType { ExecutionLayer, ConsensusLayer } interface IRewardsDistributor { /// @notice Returns the address of the ynETH token. /// @return address of the ynETH token. function ynETH() external view returns (address); /// @notice Processes the rewards for the execution and consensus layer. /// @dev This function should be called by off-chain rewards distribution service. function processRewards() external; /// @notice Returns the address of the execution layer rewards receiver. /// @return address of the execution layer rewards receiver. function executionLayerReceiver() external view returns (IRewardsReceiver); /// @notice Returns the address of the consensus layer rewards receiver. /// @return address of the consensus layer rewards receiver. function consensusLayerReceiver() external view returns (IRewardsReceiver); /// @notice Returns the address of the fees receiver. /// @return address of the fees receiver. function feesReceiver() external view returns (address); /// @notice Returns the protocol fees in basis points (1/10000). /// @return uint16 fees in basis points. function feesBasisPoints() external view returns (uint16); /// @notice Sets the address to receive protocol fees. /// @param newReceiver The new fees receiver address. function setFeesReceiver(address payable newReceiver) external; /// @notice Sets the protocol fees in basis points (1/10000). /// @param newFeesBasisPoints The new fees in basis points. function setFeesBasisPoints(uint16 newFeesBasisPoints) external; }
// SPDX-License-Identifier: BSD 3-Clause License pragma solidity ^0.8.24; import {IERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; import {IRedeemableAsset} from "src/interfaces/IRedeemableAsset.sol"; import {IStakingNodesManager} from "src/interfaces/IStakingNodesManager.sol"; interface IynETH is IERC20, IRedeemableAsset { function withdrawETH(uint256 ethAmount) external; function processWithdrawnETH() external payable; function receiveRewards() external payable; function pauseDeposits() external; function unpauseDeposits() external; /// @notice Allows depositing ETH into the contract in exchange for shares. /// @param receiver The address to receive the minted shares. /// @return shares The amount of shares minted for the deposited ETH. function depositETH(address receiver) external payable returns (uint256 shares); function previewRedeem(uint256 shares) external view returns (uint256); /// @notice Returns the total amount of assets managed by the contract. /// @return The total amount of assets in wei. function totalAssets() external view returns (uint256); /// @notice Returns the address of the StakingNodesManager contract. /// @return The address of the StakingNodesManager contract. function stakingNodesManager() external view returns (IStakingNodesManager); /// @notice Simulates the effects of a deposit at the current block, given the amount of assets. /// @param assets The amount of assets to simulate depositing. /// @return shares The amount of shares that would be minted. function previewDeposit(uint256 assets) external view returns (uint256 shares); }
// SPDX-License-Identifier: BSD 3-Clause License pragma solidity ^0.8.24; import "lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol"; import "lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol"; interface IynBaseEvents { event TransfersUnpaused(); event PauseWhitelistUpdated(address indexed account, bool isWhitelisted); } /// @title ynBase /// @dev This contract serves as the base for the YieldNest protocol, providing core functionalities such as /// ERC20 token mechanics, access control, and transfer pause capabilities. /// It integrates with OpenZeppelin's upgradeable contracts for ERC20 and AccessControl functionalities. /// The contract includes mechanisms to pause transfers, manage a whitelist for paused transfers, and handle initialization processes. contract ynBase is ERC20Upgradeable, AccessControlUpgradeable, IynBaseEvents { //-------------------------------------------------------------------------------------- //---------------------------------- ERRORS ------------------------------------------ //-------------------------------------------------------------------------------------- error TransfersPaused(); //-------------------------------------------------------------------------------------- //---------------------------------- ROLES ------------------------------------------- //-------------------------------------------------------------------------------------- /// @notice Role is allowed to set the pause state bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /// @notice Role allowed to unset the pause state bytes32 public constant UNPAUSER_ROLE = keccak256("UNPAUSER_ROLE"); //-------------------------------------------------------------------------------------- //---------------------------------- STORAGE ----------------------------------------- //-------------------------------------------------------------------------------------- /// @custom:storage-location erc7201:yieldnest.storage.ynBase struct ynBaseStorage { mapping (address => bool) pauseWhiteList; bool transfersPaused; } // keccak256(abi.encode(uint256(keccak256("erc7201:yieldnest.storage.ynBase")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant ynBaseStorageLocation = 0x7e7ba5b20f89141f0255e9704ce6ce6e55f5f28e4fc0d626fc76bedba3053200; function _getYnBaseStorage() private pure returns (ynBaseStorage storage $) { assembly { $.slot := ynBaseStorageLocation } } //-------------------------------------------------------------------------------------- //---------------------------------- INITIALIZATION ---------------------------------- //-------------------------------------------------------------------------------------- /** * @dev Sets the values for {name} and {symbol}. * * All two of these values are immutable: they can only be set once during * construction. */ function __ynBase_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init(name_, symbol_); } //-------------------------------------------------------------------------------------- //---------------------------------- BOOTSTRAP TRANSFERS PAUSE ----------------------- //-------------------------------------------------------------------------------------- /** * @dev Hooks into the transfer events of ERC20 with checks for paused transfers and whitelist exemptions. * Reverts if transfers are paused, the sender is not whitelisted, and the transfer is not a mint or burn operation. * @param from Address sending the tokens * @param to Address receiving the tokens * @param amount Amount of tokens being transferred */ function _update(address from, address to, uint256 amount) internal virtual override { ynBaseStorage storage $ = _getYnBaseStorage(); // revert if transfers are paused, the from is not on the whitelist and // it's neither a mint (from = 0) nor a burn (to = 0) if ($.transfersPaused && !$.pauseWhiteList[from] && from != address(0) && to != address(0)) { revert TransfersPaused(); } super._update(from, to, amount); } /// @dev This is a one-way toggle. Once unpaused, transfers can't be paused again. function unpauseTransfers() external onlyRole(UNPAUSER_ROLE) { ynBaseStorage storage $ = _getYnBaseStorage(); $.transfersPaused = false; emit TransfersUnpaused(); } /** * @dev Adds addresses to the pause whitelist, allowing them to transfer tokens even when transfers are paused. * Can only be called by an account with the `UNPAUSER_ROLE`. * @param whitelistedForTransfers An array of addresses to be added to the whitelist. */ function addToPauseWhitelist(address[] memory whitelistedForTransfers) external onlyRole(UNPAUSER_ROLE) { _updatePauseWhitelist(whitelistedForTransfers, true); } /** * @dev Removes addresses from the pause whitelist, preventing them from transferring tokens when transfers are paused. * Can only be called by an account with the `UNPAUSER_ROLE`. * @param unlisted An array of addresses to be removed from the whitelist. */ function removeFromPauseWhitelist(address[] memory unlisted) external onlyRole(UNPAUSER_ROLE) { _updatePauseWhitelist(unlisted, false); } /** * @dev Internal function to update the pause whitelist status of addresses. * @param whitelistedForTransfers An array of addresses whose whitelist status is to be updated. * @param whitelisted The whitelist status to be set for the provided addresses. */ function _updatePauseWhitelist(address[] memory whitelistedForTransfers, bool whitelisted) internal { ynBaseStorage storage $ = _getYnBaseStorage(); for (uint256 i = 0; i < whitelistedForTransfers.length; i++) { address targetAddress = whitelistedForTransfers[i]; $.pauseWhiteList[targetAddress] = whitelisted; emit PauseWhitelistUpdated(targetAddress, whitelisted); } } /** * @dev Internal function to set the paused status of transfers. * @param _transfersPaused The paused status to be set. */ function _setTransfersPaused(bool _transfersPaused) internal { ynBaseStorage storage $ = _getYnBaseStorage(); $.transfersPaused = _transfersPaused; } /** * @dev Returns true if the address is in the pause whitelist, false otherwise. */ function pauseWhiteList(address addr) public view returns (bool) { ynBaseStorage storage $ = _getYnBaseStorage(); return $.pauseWhiteList[addr]; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; /** * @dev Helper library for emitting standardized panic codes. * * ```solidity * contract Example { * using Panic for uint256; * * // Use any of the declared internal constants * function foo() { Panic.GENERIC.panic(); } * * // Alternatively * function foo() { Panic.panic(Panic.GENERIC); } * } * ``` * * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil]. */ // slither-disable-next-line unused-state library Panic { /// @dev generic / unspecified error uint256 internal constant GENERIC = 0x00; /// @dev used by the assert() builtin uint256 internal constant ASSERT = 0x01; /// @dev arithmetic underflow or overflow uint256 internal constant UNDER_OVERFLOW = 0x11; /// @dev division or modulo by zero uint256 internal constant DIVISION_BY_ZERO = 0x12; /// @dev enum conversion error uint256 internal constant ENUM_CONVERSION_ERROR = 0x21; /// @dev invalid encoding in storage uint256 internal constant STORAGE_ENCODING_ERROR = 0x22; /// @dev empty array pop uint256 internal constant EMPTY_ARRAY_POP = 0x31; /// @dev array out of bounds access uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32; /// @dev resource error (too large allocation or too large array) uint256 internal constant RESOURCE_ERROR = 0x41; /// @dev calling invalid internal function uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51; /// @dev Reverts with a panic code. Recommended to use with /// the internal constants with predefined codes. function panic(uint256 code) internal pure { /// @solidity memory-safe-assembly assembly { mstore(0x00, 0x4e487b71) mstore(0x20, code) revert(0x1c, 0x24) } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SafeCast.sol) // This file was procedurally generated from scripts/generate/templates/SafeCast.js. pragma solidity ^0.8.20; /** * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeCast { /** * @dev Value doesn't fit in an uint of `bits` size. */ error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value); /** * @dev An int value doesn't fit in an uint of `bits` size. */ error SafeCastOverflowedIntToUint(int256 value); /** * @dev Value doesn't fit in an int of `bits` size. */ error SafeCastOverflowedIntDowncast(uint8 bits, int256 value); /** * @dev An uint value doesn't fit in an int of `bits` size. */ error SafeCastOverflowedUintToInt(uint256 value); /** * @dev Returns the downcasted uint248 from uint256, reverting on * overflow (when the input is greater than largest uint248). * * Counterpart to Solidity's `uint248` operator. * * Requirements: * * - input must fit into 248 bits */ function toUint248(uint256 value) internal pure returns (uint248) { if (value > type(uint248).max) { revert SafeCastOverflowedUintDowncast(248, value); } return uint248(value); } /** * @dev Returns the downcasted uint240 from uint256, reverting on * overflow (when the input is greater than largest uint240). * * Counterpart to Solidity's `uint240` operator. * * Requirements: * * - input must fit into 240 bits */ function toUint240(uint256 value) internal pure returns (uint240) { if (value > type(uint240).max) { revert SafeCastOverflowedUintDowncast(240, value); } return uint240(value); } /** * @dev Returns the downcasted uint232 from uint256, reverting on * overflow (when the input is greater than largest uint232). * * Counterpart to Solidity's `uint232` operator. * * Requirements: * * - input must fit into 232 bits */ function toUint232(uint256 value) internal pure returns (uint232) { if (value > type(uint232).max) { revert SafeCastOverflowedUintDowncast(232, value); } return uint232(value); } /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { if (value > type(uint224).max) { revert SafeCastOverflowedUintDowncast(224, value); } return uint224(value); } /** * @dev Returns the downcasted uint216 from uint256, reverting on * overflow (when the input is greater than largest uint216). * * Counterpart to Solidity's `uint216` operator. * * Requirements: * * - input must fit into 216 bits */ function toUint216(uint256 value) internal pure returns (uint216) { if (value > type(uint216).max) { revert SafeCastOverflowedUintDowncast(216, value); } return uint216(value); } /** * @dev Returns the downcasted uint208 from uint256, reverting on * overflow (when the input is greater than largest uint208). * * Counterpart to Solidity's `uint208` operator. * * Requirements: * * - input must fit into 208 bits */ function toUint208(uint256 value) internal pure returns (uint208) { if (value > type(uint208).max) { revert SafeCastOverflowedUintDowncast(208, value); } return uint208(value); } /** * @dev Returns the downcasted uint200 from uint256, reverting on * overflow (when the input is greater than largest uint200). * * Counterpart to Solidity's `uint200` operator. * * Requirements: * * - input must fit into 200 bits */ function toUint200(uint256 value) internal pure returns (uint200) { if (value > type(uint200).max) { revert SafeCastOverflowedUintDowncast(200, value); } return uint200(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits */ function toUint192(uint256 value) internal pure returns (uint192) { if (value > type(uint192).max) { revert SafeCastOverflowedUintDowncast(192, value); } return uint192(value); } /** * @dev Returns the downcasted uint184 from uint256, reverting on * overflow (when the input is greater than largest uint184). * * Counterpart to Solidity's `uint184` operator. * * Requirements: * * - input must fit into 184 bits */ function toUint184(uint256 value) internal pure returns (uint184) { if (value > type(uint184).max) { revert SafeCastOverflowedUintDowncast(184, value); } return uint184(value); } /** * @dev Returns the downcasted uint176 from uint256, reverting on * overflow (when the input is greater than largest uint176). * * Counterpart to Solidity's `uint176` operator. * * Requirements: * * - input must fit into 176 bits */ function toUint176(uint256 value) internal pure returns (uint176) { if (value > type(uint176).max) { revert SafeCastOverflowedUintDowncast(176, value); } return uint176(value); } /** * @dev Returns the downcasted uint168 from uint256, reverting on * overflow (when the input is greater than largest uint168). * * Counterpart to Solidity's `uint168` operator. * * Requirements: * * - input must fit into 168 bits */ function toUint168(uint256 value) internal pure returns (uint168) { if (value > type(uint168).max) { revert SafeCastOverflowedUintDowncast(168, value); } return uint168(value); } /** * @dev Returns the downcasted uint160 from uint256, reverting on * overflow (when the input is greater than largest uint160). * * Counterpart to Solidity's `uint160` operator. * * Requirements: * * - input must fit into 160 bits */ function toUint160(uint256 value) internal pure returns (uint160) { if (value > type(uint160).max) { revert SafeCastOverflowedUintDowncast(160, value); } return uint160(value); } /** * @dev Returns the downcasted uint152 from uint256, reverting on * overflow (when the input is greater than largest uint152). * * Counterpart to Solidity's `uint152` operator. * * Requirements: * * - input must fit into 152 bits */ function toUint152(uint256 value) internal pure returns (uint152) { if (value > type(uint152).max) { revert SafeCastOverflowedUintDowncast(152, value); } return uint152(value); } /** * @dev Returns the downcasted uint144 from uint256, reverting on * overflow (when the input is greater than largest uint144). * * Counterpart to Solidity's `uint144` operator. * * Requirements: * * - input must fit into 144 bits */ function toUint144(uint256 value) internal pure returns (uint144) { if (value > type(uint144).max) { revert SafeCastOverflowedUintDowncast(144, value); } return uint144(value); } /** * @dev Returns the downcasted uint136 from uint256, reverting on * overflow (when the input is greater than largest uint136). * * Counterpart to Solidity's `uint136` operator. * * Requirements: * * - input must fit into 136 bits */ function toUint136(uint256 value) internal pure returns (uint136) { if (value > type(uint136).max) { revert SafeCastOverflowedUintDowncast(136, value); } return uint136(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { if (value > type(uint128).max) { revert SafeCastOverflowedUintDowncast(128, value); } return uint128(value); } /** * @dev Returns the downcasted uint120 from uint256, reverting on * overflow (when the input is greater than largest uint120). * * Counterpart to Solidity's `uint120` operator. * * Requirements: * * - input must fit into 120 bits */ function toUint120(uint256 value) internal pure returns (uint120) { if (value > type(uint120).max) { revert SafeCastOverflowedUintDowncast(120, value); } return uint120(value); } /** * @dev Returns the downcasted uint112 from uint256, reverting on * overflow (when the input is greater than largest uint112). * * Counterpart to Solidity's `uint112` operator. * * Requirements: * * - input must fit into 112 bits */ function toUint112(uint256 value) internal pure returns (uint112) { if (value > type(uint112).max) { revert SafeCastOverflowedUintDowncast(112, value); } return uint112(value); } /** * @dev Returns the downcasted uint104 from uint256, reverting on * overflow (when the input is greater than largest uint104). * * Counterpart to Solidity's `uint104` operator. * * Requirements: * * - input must fit into 104 bits */ function toUint104(uint256 value) internal pure returns (uint104) { if (value > type(uint104).max) { revert SafeCastOverflowedUintDowncast(104, value); } return uint104(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { if (value > type(uint96).max) { revert SafeCastOverflowedUintDowncast(96, value); } return uint96(value); } /** * @dev Returns the downcasted uint88 from uint256, reverting on * overflow (when the input is greater than largest uint88). * * Counterpart to Solidity's `uint88` operator. * * Requirements: * * - input must fit into 88 bits */ function toUint88(uint256 value) internal pure returns (uint88) { if (value > type(uint88).max) { revert SafeCastOverflowedUintDowncast(88, value); } return uint88(value); } /** * @dev Returns the downcasted uint80 from uint256, reverting on * overflow (when the input is greater than largest uint80). * * Counterpart to Solidity's `uint80` operator. * * Requirements: * * - input must fit into 80 bits */ function toUint80(uint256 value) internal pure returns (uint80) { if (value > type(uint80).max) { revert SafeCastOverflowedUintDowncast(80, value); } return uint80(value); } /** * @dev Returns the downcasted uint72 from uint256, reverting on * overflow (when the input is greater than largest uint72). * * Counterpart to Solidity's `uint72` operator. * * Requirements: * * - input must fit into 72 bits */ function toUint72(uint256 value) internal pure returns (uint72) { if (value > type(uint72).max) { revert SafeCastOverflowedUintDowncast(72, value); } return uint72(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { if (value > type(uint64).max) { revert SafeCastOverflowedUintDowncast(64, value); } return uint64(value); } /** * @dev Returns the downcasted uint56 from uint256, reverting on * overflow (when the input is greater than largest uint56). * * Counterpart to Solidity's `uint56` operator. * * Requirements: * * - input must fit into 56 bits */ function toUint56(uint256 value) internal pure returns (uint56) { if (value > type(uint56).max) { revert SafeCastOverflowedUintDowncast(56, value); } return uint56(value); } /** * @dev Returns the downcasted uint48 from uint256, reverting on * overflow (when the input is greater than largest uint48). * * Counterpart to Solidity's `uint48` operator. * * Requirements: * * - input must fit into 48 bits */ function toUint48(uint256 value) internal pure returns (uint48) { if (value > type(uint48).max) { revert SafeCastOverflowedUintDowncast(48, value); } return uint48(value); } /** * @dev Returns the downcasted uint40 from uint256, reverting on * overflow (when the input is greater than largest uint40). * * Counterpart to Solidity's `uint40` operator. * * Requirements: * * - input must fit into 40 bits */ function toUint40(uint256 value) internal pure returns (uint40) { if (value > type(uint40).max) { revert SafeCastOverflowedUintDowncast(40, value); } return uint40(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { if (value > type(uint32).max) { revert SafeCastOverflowedUintDowncast(32, value); } return uint32(value); } /** * @dev Returns the downcasted uint24 from uint256, reverting on * overflow (when the input is greater than largest uint24). * * Counterpart to Solidity's `uint24` operator. * * Requirements: * * - input must fit into 24 bits */ function toUint24(uint256 value) internal pure returns (uint24) { if (value > type(uint24).max) { revert SafeCastOverflowedUintDowncast(24, value); } return uint24(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { if (value > type(uint16).max) { revert SafeCastOverflowedUintDowncast(16, value); } return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits */ function toUint8(uint256 value) internal pure returns (uint8) { if (value > type(uint8).max) { revert SafeCastOverflowedUintDowncast(8, value); } return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { if (value < 0) { revert SafeCastOverflowedIntToUint(value); } return uint256(value); } /** * @dev Returns the downcasted int248 from int256, reverting on * overflow (when the input is less than smallest int248 or * greater than largest int248). * * Counterpart to Solidity's `int248` operator. * * Requirements: * * - input must fit into 248 bits */ function toInt248(int256 value) internal pure returns (int248 downcasted) { downcasted = int248(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(248, value); } } /** * @dev Returns the downcasted int240 from int256, reverting on * overflow (when the input is less than smallest int240 or * greater than largest int240). * * Counterpart to Solidity's `int240` operator. * * Requirements: * * - input must fit into 240 bits */ function toInt240(int256 value) internal pure returns (int240 downcasted) { downcasted = int240(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(240, value); } } /** * @dev Returns the downcasted int232 from int256, reverting on * overflow (when the input is less than smallest int232 or * greater than largest int232). * * Counterpart to Solidity's `int232` operator. * * Requirements: * * - input must fit into 232 bits */ function toInt232(int256 value) internal pure returns (int232 downcasted) { downcasted = int232(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(232, value); } } /** * @dev Returns the downcasted int224 from int256, reverting on * overflow (when the input is less than smallest int224 or * greater than largest int224). * * Counterpart to Solidity's `int224` operator. * * Requirements: * * - input must fit into 224 bits */ function toInt224(int256 value) internal pure returns (int224 downcasted) { downcasted = int224(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(224, value); } } /** * @dev Returns the downcasted int216 from int256, reverting on * overflow (when the input is less than smallest int216 or * greater than largest int216). * * Counterpart to Solidity's `int216` operator. * * Requirements: * * - input must fit into 216 bits */ function toInt216(int256 value) internal pure returns (int216 downcasted) { downcasted = int216(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(216, value); } } /** * @dev Returns the downcasted int208 from int256, reverting on * overflow (when the input is less than smallest int208 or * greater than largest int208). * * Counterpart to Solidity's `int208` operator. * * Requirements: * * - input must fit into 208 bits */ function toInt208(int256 value) internal pure returns (int208 downcasted) { downcasted = int208(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(208, value); } } /** * @dev Returns the downcasted int200 from int256, reverting on * overflow (when the input is less than smallest int200 or * greater than largest int200). * * Counterpart to Solidity's `int200` operator. * * Requirements: * * - input must fit into 200 bits */ function toInt200(int256 value) internal pure returns (int200 downcasted) { downcasted = int200(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(200, value); } } /** * @dev Returns the downcasted int192 from int256, reverting on * overflow (when the input is less than smallest int192 or * greater than largest int192). * * Counterpart to Solidity's `int192` operator. * * Requirements: * * - input must fit into 192 bits */ function toInt192(int256 value) internal pure returns (int192 downcasted) { downcasted = int192(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(192, value); } } /** * @dev Returns the downcasted int184 from int256, reverting on * overflow (when the input is less than smallest int184 or * greater than largest int184). * * Counterpart to Solidity's `int184` operator. * * Requirements: * * - input must fit into 184 bits */ function toInt184(int256 value) internal pure returns (int184 downcasted) { downcasted = int184(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(184, value); } } /** * @dev Returns the downcasted int176 from int256, reverting on * overflow (when the input is less than smallest int176 or * greater than largest int176). * * Counterpart to Solidity's `int176` operator. * * Requirements: * * - input must fit into 176 bits */ function toInt176(int256 value) internal pure returns (int176 downcasted) { downcasted = int176(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(176, value); } } /** * @dev Returns the downcasted int168 from int256, reverting on * overflow (when the input is less than smallest int168 or * greater than largest int168). * * Counterpart to Solidity's `int168` operator. * * Requirements: * * - input must fit into 168 bits */ function toInt168(int256 value) internal pure returns (int168 downcasted) { downcasted = int168(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(168, value); } } /** * @dev Returns the downcasted int160 from int256, reverting on * overflow (when the input is less than smallest int160 or * greater than largest int160). * * Counterpart to Solidity's `int160` operator. * * Requirements: * * - input must fit into 160 bits */ function toInt160(int256 value) internal pure returns (int160 downcasted) { downcasted = int160(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(160, value); } } /** * @dev Returns the downcasted int152 from int256, reverting on * overflow (when the input is less than smallest int152 or * greater than largest int152). * * Counterpart to Solidity's `int152` operator. * * Requirements: * * - input must fit into 152 bits */ function toInt152(int256 value) internal pure returns (int152 downcasted) { downcasted = int152(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(152, value); } } /** * @dev Returns the downcasted int144 from int256, reverting on * overflow (when the input is less than smallest int144 or * greater than largest int144). * * Counterpart to Solidity's `int144` operator. * * Requirements: * * - input must fit into 144 bits */ function toInt144(int256 value) internal pure returns (int144 downcasted) { downcasted = int144(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(144, value); } } /** * @dev Returns the downcasted int136 from int256, reverting on * overflow (when the input is less than smallest int136 or * greater than largest int136). * * Counterpart to Solidity's `int136` operator. * * Requirements: * * - input must fit into 136 bits */ function toInt136(int256 value) internal pure returns (int136 downcasted) { downcasted = int136(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(136, value); } } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits */ function toInt128(int256 value) internal pure returns (int128 downcasted) { downcasted = int128(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(128, value); } } /** * @dev Returns the downcasted int120 from int256, reverting on * overflow (when the input is less than smallest int120 or * greater than largest int120). * * Counterpart to Solidity's `int120` operator. * * Requirements: * * - input must fit into 120 bits */ function toInt120(int256 value) internal pure returns (int120 downcasted) { downcasted = int120(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(120, value); } } /** * @dev Returns the downcasted int112 from int256, reverting on * overflow (when the input is less than smallest int112 or * greater than largest int112). * * Counterpart to Solidity's `int112` operator. * * Requirements: * * - input must fit into 112 bits */ function toInt112(int256 value) internal pure returns (int112 downcasted) { downcasted = int112(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(112, value); } } /** * @dev Returns the downcasted int104 from int256, reverting on * overflow (when the input is less than smallest int104 or * greater than largest int104). * * Counterpart to Solidity's `int104` operator. * * Requirements: * * - input must fit into 104 bits */ function toInt104(int256 value) internal pure returns (int104 downcasted) { downcasted = int104(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(104, value); } } /** * @dev Returns the downcasted int96 from int256, reverting on * overflow (when the input is less than smallest int96 or * greater than largest int96). * * Counterpart to Solidity's `int96` operator. * * Requirements: * * - input must fit into 96 bits */ function toInt96(int256 value) internal pure returns (int96 downcasted) { downcasted = int96(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(96, value); } } /** * @dev Returns the downcasted int88 from int256, reverting on * overflow (when the input is less than smallest int88 or * greater than largest int88). * * Counterpart to Solidity's `int88` operator. * * Requirements: * * - input must fit into 88 bits */ function toInt88(int256 value) internal pure returns (int88 downcasted) { downcasted = int88(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(88, value); } } /** * @dev Returns the downcasted int80 from int256, reverting on * overflow (when the input is less than smallest int80 or * greater than largest int80). * * Counterpart to Solidity's `int80` operator. * * Requirements: * * - input must fit into 80 bits */ function toInt80(int256 value) internal pure returns (int80 downcasted) { downcasted = int80(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(80, value); } } /** * @dev Returns the downcasted int72 from int256, reverting on * overflow (when the input is less than smallest int72 or * greater than largest int72). * * Counterpart to Solidity's `int72` operator. * * Requirements: * * - input must fit into 72 bits */ function toInt72(int256 value) internal pure returns (int72 downcasted) { downcasted = int72(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(72, value); } } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits */ function toInt64(int256 value) internal pure returns (int64 downcasted) { downcasted = int64(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(64, value); } } /** * @dev Returns the downcasted int56 from int256, reverting on * overflow (when the input is less than smallest int56 or * greater than largest int56). * * Counterpart to Solidity's `int56` operator. * * Requirements: * * - input must fit into 56 bits */ function toInt56(int256 value) internal pure returns (int56 downcasted) { downcasted = int56(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(56, value); } } /** * @dev Returns the downcasted int48 from int256, reverting on * overflow (when the input is less than smallest int48 or * greater than largest int48). * * Counterpart to Solidity's `int48` operator. * * Requirements: * * - input must fit into 48 bits */ function toInt48(int256 value) internal pure returns (int48 downcasted) { downcasted = int48(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(48, value); } } /** * @dev Returns the downcasted int40 from int256, reverting on * overflow (when the input is less than smallest int40 or * greater than largest int40). * * Counterpart to Solidity's `int40` operator. * * Requirements: * * - input must fit into 40 bits */ function toInt40(int256 value) internal pure returns (int40 downcasted) { downcasted = int40(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(40, value); } } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits */ function toInt32(int256 value) internal pure returns (int32 downcasted) { downcasted = int32(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(32, value); } } /** * @dev Returns the downcasted int24 from int256, reverting on * overflow (when the input is less than smallest int24 or * greater than largest int24). * * Counterpart to Solidity's `int24` operator. * * Requirements: * * - input must fit into 24 bits */ function toInt24(int256 value) internal pure returns (int24 downcasted) { downcasted = int24(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(24, value); } } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits */ function toInt16(int256 value) internal pure returns (int16 downcasted) { downcasted = int16(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(16, value); } } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits */ function toInt8(int256 value) internal pure returns (int8 downcasted) { downcasted = int8(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(8, value); } } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive if (value > uint256(type(int256).max)) { revert SafeCastOverflowedUintToInt(value); } return int256(value); } /** * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump. */ function toUint(bool b) internal pure returns (uint256 u) { /// @solidity memory-safe-assembly assembly { u := iszero(iszero(b)) } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/UpgradeableBeacon.sol) pragma solidity ^0.8.20; import {IBeacon} from "./IBeacon.sol"; import {Ownable} from "../../access/Ownable.sol"; /** * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their * implementation contract, which is where they will delegate all function calls. * * An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon. */ contract UpgradeableBeacon is IBeacon, Ownable { address private _implementation; /** * @dev The `implementation` of the beacon is invalid. */ error BeaconInvalidImplementation(address implementation); /** * @dev Emitted when the implementation returned by the beacon is changed. */ event Upgraded(address indexed implementation); /** * @dev Sets the address of the initial implementation, and the initial owner who can upgrade the beacon. */ constructor(address implementation_, address initialOwner) Ownable(initialOwner) { _setImplementation(implementation_); } /** * @dev Returns the current implementation address. */ function implementation() public view virtual returns (address) { return _implementation; } /** * @dev Upgrades the beacon to a new implementation. * * Emits an {Upgraded} event. * * Requirements: * * - msg.sender must be the owner of the contract. * - `newImplementation` must be a contract. */ function upgradeTo(address newImplementation) public virtual onlyOwner { _setImplementation(newImplementation); } /** * @dev Sets the implementation contract address for this beacon * * Requirements: * * - `newImplementation` must be a contract. */ function _setImplementation(address newImplementation) private { if (newImplementation.code.length == 0) { revert BeaconInvalidImplementation(newImplementation); } _implementation = newImplementation; emit Upgraded(newImplementation); } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; import "./IStrategy.sol"; import "./ISignatureUtils.sol"; /** * @title DelegationManager * @author Layr Labs, Inc. * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service * @notice This is the contract for delegation in EigenLayer. The main functionalities of this contract are * - enabling anyone to register as an operator in EigenLayer * - allowing operators to specify parameters related to stakers who delegate to them * - enabling any staker to delegate its stake to the operator of its choice (a given staker can only delegate to a single operator at a time) * - enabling a staker to undelegate its assets from the operator it is delegated to (performed as part of the withdrawal process, initiated through the StrategyManager) */ interface IDelegationManager is ISignatureUtils { // @notice Struct used for storing information about a single operator who has registered with EigenLayer struct OperatorDetails { /// @notice DEPRECATED -- this field is no longer used, payments are handled in PaymentCoordinator.sol address __deprecated_earningsReceiver; /** * @notice Address to verify signatures when a staker wishes to delegate to the operator, as well as controlling "forced undelegations". * @dev Signature verification follows these rules: * 1) If this address is left as address(0), then any staker will be free to delegate to the operator, i.e. no signature verification will be performed. * 2) If this address is an EOA (i.e. it has no code), then we follow standard ECDSA signature verification for delegations to the operator. * 3) If this address is a contract (i.e. it has code) then we forward a call to the contract and verify that it returns the correct EIP-1271 "magic value". */ address delegationApprover; /** * @notice A minimum delay -- measured in blocks -- enforced between: * 1) the operator signalling their intent to register for a service, via calling `Slasher.optIntoSlashing` * and * 2) the operator completing registration for the service, via the service ultimately calling `Slasher.recordFirstStakeUpdate` * @dev note that for a specific operator, this value *cannot decrease*, i.e. if the operator wishes to modify their OperatorDetails, * then they are only allowed to either increase this value or keep it the same. */ uint32 stakerOptOutWindowBlocks; } /** * @notice Abstract struct used in calculating an EIP712 signature for a staker to approve that they (the staker themselves) delegate to a specific operator. * @dev Used in computing the `STAKER_DELEGATION_TYPEHASH` and as a reference in the computation of the stakerDigestHash in the `delegateToBySignature` function. */ struct StakerDelegation { // the staker who is delegating address staker; // the operator being delegated to address operator; // the staker's nonce uint256 nonce; // the expiration timestamp (UTC) of the signature uint256 expiry; } /** * @notice Abstract struct used in calculating an EIP712 signature for an operator's delegationApprover to approve that a specific staker delegate to the operator. * @dev Used in computing the `DELEGATION_APPROVAL_TYPEHASH` and as a reference in the computation of the approverDigestHash in the `_delegate` function. */ struct DelegationApproval { // the staker who is delegating address staker; // the operator being delegated to address operator; // the operator's provided salt bytes32 salt; // the expiration timestamp (UTC) of the signature uint256 expiry; } /** * Struct type used to specify an existing queued withdrawal. Rather than storing the entire struct, only a hash is stored. * In functions that operate on existing queued withdrawals -- e.g. completeQueuedWithdrawal`, the data is resubmitted and the hash of the submitted * data is computed by `calculateWithdrawalRoot` and checked against the stored hash in order to confirm the integrity of the submitted data. */ struct Withdrawal { // The address that originated the Withdrawal address staker; // The address that the staker was delegated to at the time that the Withdrawal was created address delegatedTo; // The address that can complete the Withdrawal + will receive funds when completing the withdrawal address withdrawer; // Nonce used to guarantee that otherwise identical withdrawals have unique hashes uint256 nonce; // Block number when the Withdrawal was created uint32 startBlock; // Array of strategies that the Withdrawal contains IStrategy[] strategies; // Array containing the amount of shares in each Strategy in the `strategies` array uint256[] shares; } struct QueuedWithdrawalParams { // Array of strategies that the QueuedWithdrawal contains IStrategy[] strategies; // Array containing the amount of shares in each Strategy in the `strategies` array uint256[] shares; // The address of the withdrawer address withdrawer; } // @notice Emitted when a new operator registers in EigenLayer and provides their OperatorDetails. event OperatorRegistered(address indexed operator, OperatorDetails operatorDetails); /// @notice Emitted when an operator updates their OperatorDetails to @param newOperatorDetails event OperatorDetailsModified(address indexed operator, OperatorDetails newOperatorDetails); /** * @notice Emitted when @param operator indicates that they are updating their MetadataURI string * @dev Note that these strings are *never stored in storage* and are instead purely emitted in events for off-chain indexing */ event OperatorMetadataURIUpdated(address indexed operator, string metadataURI); /// @notice Emitted whenever an operator's shares are increased for a given strategy. Note that shares is the delta in the operator's shares. event OperatorSharesIncreased(address indexed operator, address staker, IStrategy strategy, uint256 shares); /// @notice Emitted whenever an operator's shares are decreased for a given strategy. Note that shares is the delta in the operator's shares. event OperatorSharesDecreased(address indexed operator, address staker, IStrategy strategy, uint256 shares); /// @notice Emitted when @param staker delegates to @param operator. event StakerDelegated(address indexed staker, address indexed operator); /// @notice Emitted when @param staker undelegates from @param operator. event StakerUndelegated(address indexed staker, address indexed operator); /// @notice Emitted when @param staker is undelegated via a call not originating from the staker themself event StakerForceUndelegated(address indexed staker, address indexed operator); /** * @notice Emitted when a new withdrawal is queued. * @param withdrawalRoot Is the hash of the `withdrawal`. * @param withdrawal Is the withdrawal itself. */ event WithdrawalQueued(bytes32 withdrawalRoot, Withdrawal withdrawal); /// @notice Emitted when a queued withdrawal is completed event WithdrawalCompleted(bytes32 withdrawalRoot); /// @notice Emitted when the `minWithdrawalDelayBlocks` variable is modified from `previousValue` to `newValue`. event MinWithdrawalDelayBlocksSet(uint256 previousValue, uint256 newValue); /// @notice Emitted when the `strategyWithdrawalDelayBlocks` variable is modified from `previousValue` to `newValue`. event StrategyWithdrawalDelayBlocksSet(IStrategy strategy, uint256 previousValue, uint256 newValue); /** * @notice Registers the caller as an operator in EigenLayer. * @param registeringOperatorDetails is the `OperatorDetails` for the operator. * @param metadataURI is a URI for the operator's metadata, i.e. a link providing more details on the operator. * * @dev Once an operator is registered, they cannot 'deregister' as an operator, and they will forever be considered "delegated to themself". * @dev Note that the `metadataURI` is *never stored * and is only emitted in the `OperatorMetadataURIUpdated` event */ function registerAsOperator( OperatorDetails calldata registeringOperatorDetails, string calldata metadataURI ) external; /** * @notice Updates an operator's stored `OperatorDetails`. * @param newOperatorDetails is the updated `OperatorDetails` for the operator, to replace their current OperatorDetails`. * * @dev The caller must have previously registered as an operator in EigenLayer. */ function modifyOperatorDetails(OperatorDetails calldata newOperatorDetails) external; /** * @notice Called by an operator to emit an `OperatorMetadataURIUpdated` event indicating the information has updated. * @param metadataURI The URI for metadata associated with an operator * @dev Note that the `metadataURI` is *never stored * and is only emitted in the `OperatorMetadataURIUpdated` event */ function updateOperatorMetadataURI(string calldata metadataURI) external; /** * @notice Caller delegates their stake to an operator. * @param operator The account (`msg.sender`) is delegating its assets to for use in serving applications built on EigenLayer. * @param approverSignatureAndExpiry Verifies the operator approves of this delegation * @param approverSalt A unique single use value tied to an individual signature. * @dev The approverSignatureAndExpiry is used in the event that: * 1) the operator's `delegationApprover` address is set to a non-zero value. * AND * 2) neither the operator nor their `delegationApprover` is the `msg.sender`, since in the event that the operator * or their delegationApprover is the `msg.sender`, then approval is assumed. * @dev In the event that `approverSignatureAndExpiry` is not checked, its content is ignored entirely; it's recommended to use an empty input * in this case to save on complexity + gas costs */ function delegateTo( address operator, SignatureWithExpiry memory approverSignatureAndExpiry, bytes32 approverSalt ) external; /** * @notice Caller delegates a staker's stake to an operator with valid signatures from both parties. * @param staker The account delegating stake to an `operator` account * @param operator The account (`staker`) is delegating its assets to for use in serving applications built on EigenLayer. * @param stakerSignatureAndExpiry Signed data from the staker authorizing delegating stake to an operator * @param approverSignatureAndExpiry is a parameter that will be used for verifying that the operator approves of this delegation action in the event that: * @param approverSalt Is a salt used to help guarantee signature uniqueness. Each salt can only be used once by a given approver. * * @dev If `staker` is an EOA, then `stakerSignature` is verified to be a valid ECDSA stakerSignature from `staker`, indicating their intention for this action. * @dev If `staker` is a contract, then `stakerSignature` will be checked according to EIP-1271. * @dev the operator's `delegationApprover` address is set to a non-zero value. * @dev neither the operator nor their `delegationApprover` is the `msg.sender`, since in the event that the operator or their delegationApprover * is the `msg.sender`, then approval is assumed. * @dev This function will revert if the current `block.timestamp` is equal to or exceeds the expiry * @dev In the case that `approverSignatureAndExpiry` is not checked, its content is ignored entirely; it's recommended to use an empty input * in this case to save on complexity + gas costs */ function delegateToBySignature( address staker, address operator, SignatureWithExpiry memory stakerSignatureAndExpiry, SignatureWithExpiry memory approverSignatureAndExpiry, bytes32 approverSalt ) external; /** * @notice Undelegates the staker from the operator who they are delegated to. Puts the staker into the "undelegation limbo" mode of the EigenPodManager * and queues a withdrawal of all of the staker's shares in the StrategyManager (to the staker), if necessary. * @param staker The account to be undelegated. * @return withdrawalRoot The root of the newly queued withdrawal, if a withdrawal was queued. Otherwise just bytes32(0). * * @dev Reverts if the `staker` is also an operator, since operators are not allowed to undelegate from themselves. * @dev Reverts if the caller is not the staker, nor the operator who the staker is delegated to, nor the operator's specified "delegationApprover" * @dev Reverts if the `staker` is already undelegated. */ function undelegate(address staker) external returns (bytes32[] memory withdrawalRoot); /** * Allows a staker to withdraw some shares. Withdrawn shares/strategies are immediately removed * from the staker. If the staker is delegated, withdrawn shares/strategies are also removed from * their operator. * * All withdrawn shares/strategies are placed in a queue and can be fully withdrawn after a delay. */ function queueWithdrawals(QueuedWithdrawalParams[] calldata queuedWithdrawalParams) external returns (bytes32[] memory); /** * @notice Used to complete the specified `withdrawal`. The caller must match `withdrawal.withdrawer` * @param withdrawal The Withdrawal to complete. * @param tokens Array in which the i-th entry specifies the `token` input to the 'withdraw' function of the i-th Strategy in the `withdrawal.strategies` array. * This input can be provided with zero length if `receiveAsTokens` is set to 'false' (since in that case, this input will be unused) * @param middlewareTimesIndex is the index in the operator that the staker who triggered the withdrawal was delegated to's middleware times array * @param receiveAsTokens If true, the shares specified in the withdrawal will be withdrawn from the specified strategies themselves * and sent to the caller, through calls to `withdrawal.strategies[i].withdraw`. If false, then the shares in the specified strategies * will simply be transferred to the caller directly. * @dev middlewareTimesIndex should be calculated off chain before calling this function by finding the first index that satisfies `slasher.canWithdraw` * @dev beaconChainETHStrategy shares are non-transferrable, so if `receiveAsTokens = false` and `withdrawal.withdrawer != withdrawal.staker`, note that * any beaconChainETHStrategy shares in the `withdrawal` will be _returned to the staker_, rather than transferred to the withdrawer, unlike shares in * any other strategies, which will be transferred to the withdrawer. */ function completeQueuedWithdrawal( Withdrawal calldata withdrawal, IERC20[] calldata tokens, uint256 middlewareTimesIndex, bool receiveAsTokens ) external; /** * @notice Array-ified version of `completeQueuedWithdrawal`. * Used to complete the specified `withdrawals`. The function caller must match `withdrawals[...].withdrawer` * @param withdrawals The Withdrawals to complete. * @param tokens Array of tokens for each Withdrawal. See `completeQueuedWithdrawal` for the usage of a single array. * @param middlewareTimesIndexes One index to reference per Withdrawal. See `completeQueuedWithdrawal` for the usage of a single index. * @param receiveAsTokens Whether or not to complete each withdrawal as tokens. See `completeQueuedWithdrawal` for the usage of a single boolean. * @dev See `completeQueuedWithdrawal` for relevant dev tags */ function completeQueuedWithdrawals( Withdrawal[] calldata withdrawals, IERC20[][] calldata tokens, uint256[] calldata middlewareTimesIndexes, bool[] calldata receiveAsTokens ) external; /** * @notice Increases a staker's delegated share balance in a strategy. * @param staker The address to increase the delegated shares for their operator. * @param strategy The strategy in which to increase the delegated shares. * @param shares The number of shares to increase. * * @dev *If the staker is actively delegated*, then increases the `staker`'s delegated shares in `strategy` by `shares`. Otherwise does nothing. * @dev Callable only by the StrategyManager or EigenPodManager. */ function increaseDelegatedShares(address staker, IStrategy strategy, uint256 shares) external; /** * @notice Decreases a staker's delegated share balance in a strategy. * @param staker The address to increase the delegated shares for their operator. * @param strategy The strategy in which to decrease the delegated shares. * @param shares The number of shares to decrease. * * @dev *If the staker is actively delegated*, then decreases the `staker`'s delegated shares in `strategy` by `shares`. Otherwise does nothing. * @dev Callable only by the StrategyManager or EigenPodManager. */ function decreaseDelegatedShares(address staker, IStrategy strategy, uint256 shares) external; /** * @notice returns the address of the operator that `staker` is delegated to. * @notice Mapping: staker => operator whom the staker is currently delegated to. * @dev Note that returning address(0) indicates that the staker is not actively delegated to any operator. */ function delegatedTo(address staker) external view returns (address); /** * @notice Returns the OperatorDetails struct associated with an `operator`. */ function operatorDetails(address operator) external view returns (OperatorDetails memory); /** * @notice Returns the delegationApprover account for an operator */ function delegationApprover(address operator) external view returns (address); /** * @notice Returns the stakerOptOutWindowBlocks for an operator */ function stakerOptOutWindowBlocks(address operator) external view returns (uint256); /** * @notice Given array of strategies, returns array of shares for the operator */ function getOperatorShares( address operator, IStrategy[] memory strategies ) external view returns (uint256[] memory); /** * @notice Given a list of strategies, return the minimum number of blocks that must pass to withdraw * from all the inputted strategies. Return value is >= minWithdrawalDelayBlocks as this is the global min withdrawal delay. * @param strategies The strategies to check withdrawal delays for */ function getWithdrawalDelay(IStrategy[] calldata strategies) external view returns (uint256); /** * @notice returns the total number of shares in `strategy` that are delegated to `operator`. * @notice Mapping: operator => strategy => total number of shares in the strategy delegated to the operator. * @dev By design, the following invariant should hold for each Strategy: * (operator's shares in delegation manager) = sum (shares above zero of all stakers delegated to operator) * = sum (delegateable shares of all stakers delegated to the operator) */ function operatorShares(address operator, IStrategy strategy) external view returns (uint256); /** * @notice Returns 'true' if `staker` *is* actively delegated, and 'false' otherwise. */ function isDelegated(address staker) external view returns (bool); /** * @notice Returns true is an operator has previously registered for delegation. */ function isOperator(address operator) external view returns (bool); /// @notice Mapping: staker => number of signed delegation nonces (used in `delegateToBySignature`) from the staker that the contract has already checked function stakerNonce(address staker) external view returns (uint256); /** * @notice Mapping: delegationApprover => 32-byte salt => whether or not the salt has already been used by the delegationApprover. * @dev Salts are used in the `delegateTo` and `delegateToBySignature` functions. Note that these functions only process the delegationApprover's * signature + the provided salt if the operator being delegated to has specified a nonzero address as their `delegationApprover`. */ function delegationApproverSaltIsSpent(address _delegationApprover, bytes32 salt) external view returns (bool); /** * @notice Minimum delay enforced by this contract for completing queued withdrawals. Measured in blocks, and adjustable by this contract's owner, * up to a maximum of `MAX_WITHDRAWAL_DELAY_BLOCKS`. Minimum value is 0 (i.e. no delay enforced). * Note that strategies each have a separate withdrawal delay, which can be greater than this value. So the minimum number of blocks that must pass * to withdraw a strategy is MAX(minWithdrawalDelayBlocks, strategyWithdrawalDelayBlocks[strategy]) */ function minWithdrawalDelayBlocks() external view returns (uint256); /** * @notice Minimum delay enforced by this contract per Strategy for completing queued withdrawals. Measured in blocks, and adjustable by this contract's owner, * up to a maximum of `MAX_WITHDRAWAL_DELAY_BLOCKS`. Minimum value is 0 (i.e. no delay enforced). */ function strategyWithdrawalDelayBlocks(IStrategy strategy) external view returns (uint256); /// @notice return address of the beaconChainETHStrategy function beaconChainETHStrategy() external view returns (IStrategy); /** * @notice Calculates the digestHash for a `staker` to sign to delegate to an `operator` * @param staker The signing staker * @param operator The operator who is being delegated to * @param expiry The desired expiry time of the staker's signature */ function calculateCurrentStakerDelegationDigestHash( address staker, address operator, uint256 expiry ) external view returns (bytes32); /** * @notice Calculates the digest hash to be signed and used in the `delegateToBySignature` function * @param staker The signing staker * @param _stakerNonce The nonce of the staker. In practice we use the staker's current nonce, stored at `stakerNonce[staker]` * @param operator The operator who is being delegated to * @param expiry The desired expiry time of the staker's signature */ function calculateStakerDelegationDigestHash( address staker, uint256 _stakerNonce, address operator, uint256 expiry ) external view returns (bytes32); /** * @notice Calculates the digest hash to be signed by the operator's delegationApprove and used in the `delegateTo` and `delegateToBySignature` functions. * @param staker The account delegating their stake * @param operator The account receiving delegated stake * @param _delegationApprover the operator's `delegationApprover` who will be signing the delegationHash (in general) * @param approverSalt A unique and single use value associated with the approver signature. * @param expiry Time after which the approver's signature becomes invalid */ function calculateDelegationApprovalDigestHash( address staker, address operator, address _delegationApprover, bytes32 approverSalt, uint256 expiry ) external view returns (bytes32); /// @notice The EIP-712 typehash for the contract's domain function DOMAIN_TYPEHASH() external view returns (bytes32); /// @notice The EIP-712 typehash for the StakerDelegation struct used by the contract function STAKER_DELEGATION_TYPEHASH() external view returns (bytes32); /// @notice The EIP-712 typehash for the DelegationApproval struct used by the contract function DELEGATION_APPROVAL_TYPEHASH() external view returns (bytes32); /** * @notice Getter function for the current EIP-712 domain separator for this contract. * * @dev The domain separator will change in the event of a fork that changes the ChainID. * @dev By introducing a domain separator the DApp developers are guaranteed that there can be no signature collision. * for more detailed information please read EIP-712. */ function domainSeparator() external view returns (bytes32); /// @notice Mapping: staker => cumulative number of queued withdrawals they have ever initiated. /// @dev This only increments (doesn't decrement), and is used to help ensure that otherwise identical withdrawals have unique hashes. function cumulativeWithdrawalsQueued(address staker) external view returns (uint256); /// @notice Returns the keccak256 hash of `withdrawal`. function calculateWithdrawalRoot(Withdrawal memory withdrawal) external pure returns (bytes32); }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; import "./IStrategy.sol"; import "./ISlasher.sol"; import "./IDelegationManager.sol"; import "./IEigenPodManager.sol"; /** * @title Interface for the primary entrypoint for funds into EigenLayer. * @author Layr Labs, Inc. * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service * @notice See the `StrategyManager` contract itself for implementation details. */ interface IStrategyManager { /** * @notice Emitted when a new deposit occurs on behalf of `staker`. * @param staker Is the staker who is depositing funds into EigenLayer. * @param strategy Is the strategy that `staker` has deposited into. * @param token Is the token that `staker` deposited. * @param shares Is the number of new shares `staker` has been granted in `strategy`. */ event Deposit(address staker, IERC20 token, IStrategy strategy, uint256 shares); /// @notice Emitted when `thirdPartyTransfersForbidden` is updated for a strategy and value by the owner event UpdatedThirdPartyTransfersForbidden(IStrategy strategy, bool value); /// @notice Emitted when the `strategyWhitelister` is changed event StrategyWhitelisterChanged(address previousAddress, address newAddress); /// @notice Emitted when a strategy is added to the approved list of strategies for deposit event StrategyAddedToDepositWhitelist(IStrategy strategy); /// @notice Emitted when a strategy is removed from the approved list of strategies for deposit event StrategyRemovedFromDepositWhitelist(IStrategy strategy); /** * @notice Deposits `amount` of `token` into the specified `strategy`, with the resultant shares credited to `msg.sender` * @param strategy is the specified strategy where deposit is to be made, * @param token is the denomination in which the deposit is to be made, * @param amount is the amount of token to be deposited in the strategy by the staker * @return shares The amount of new shares in the `strategy` created as part of the action. * @dev The `msg.sender` must have previously approved this contract to transfer at least `amount` of `token` on their behalf. * @dev Cannot be called by an address that is 'frozen' (this function will revert if the `msg.sender` is frozen). * * WARNING: Depositing tokens that allow reentrancy (eg. ERC-777) into a strategy is not recommended. This can lead to attack vectors * where the token balance and corresponding strategy shares are not in sync upon reentrancy. */ function depositIntoStrategy(IStrategy strategy, IERC20 token, uint256 amount) external returns (uint256 shares); /** * @notice Used for depositing an asset into the specified strategy with the resultant shares credited to `staker`, * who must sign off on the action. * Note that the assets are transferred out/from the `msg.sender`, not from the `staker`; this function is explicitly designed * purely to help one address deposit 'for' another. * @param strategy is the specified strategy where deposit is to be made, * @param token is the denomination in which the deposit is to be made, * @param amount is the amount of token to be deposited in the strategy by the staker * @param staker the staker that the deposited assets will be credited to * @param expiry the timestamp at which the signature expires * @param signature is a valid signature from the `staker`. either an ECDSA signature if the `staker` is an EOA, or data to forward * following EIP-1271 if the `staker` is a contract * @return shares The amount of new shares in the `strategy` created as part of the action. * @dev The `msg.sender` must have previously approved this contract to transfer at least `amount` of `token` on their behalf. * @dev A signature is required for this function to eliminate the possibility of griefing attacks, specifically those * targeting stakers who may be attempting to undelegate. * @dev Cannot be called if thirdPartyTransfersForbidden is set to true for this strategy * * WARNING: Depositing tokens that allow reentrancy (eg. ERC-777) into a strategy is not recommended. This can lead to attack vectors * where the token balance and corresponding strategy shares are not in sync upon reentrancy */ function depositIntoStrategyWithSignature( IStrategy strategy, IERC20 token, uint256 amount, address staker, uint256 expiry, bytes memory signature ) external returns (uint256 shares); /// @notice Used by the DelegationManager to remove a Staker's shares from a particular strategy when entering the withdrawal queue function removeShares(address staker, IStrategy strategy, uint256 shares) external; /// @notice Used by the DelegationManager to award a Staker some shares that have passed through the withdrawal queue function addShares(address staker, IERC20 token, IStrategy strategy, uint256 shares) external; /// @notice Used by the DelegationManager to convert withdrawn shares to tokens and send them to a recipient function withdrawSharesAsTokens(address recipient, IStrategy strategy, uint256 shares, IERC20 token) external; /// @notice Returns the current shares of `user` in `strategy` function stakerStrategyShares(address user, IStrategy strategy) external view returns (uint256 shares); /** * @notice Get all details on the staker's deposits and corresponding shares * @return (staker's strategies, shares in these strategies) */ function getDeposits(address staker) external view returns (IStrategy[] memory, uint256[] memory); /// @notice Simple getter function that returns `stakerStrategyList[staker].length`. function stakerStrategyListLength(address staker) external view returns (uint256); /** * @notice Owner-only function that adds the provided Strategies to the 'whitelist' of strategies that stakers can deposit into * @param strategiesToWhitelist Strategies that will be added to the `strategyIsWhitelistedForDeposit` mapping (if they aren't in it already) * @param thirdPartyTransfersForbiddenValues bool values to set `thirdPartyTransfersForbidden` to for each strategy */ function addStrategiesToDepositWhitelist( IStrategy[] calldata strategiesToWhitelist, bool[] calldata thirdPartyTransfersForbiddenValues ) external; /** * @notice Owner-only function that removes the provided Strategies from the 'whitelist' of strategies that stakers can deposit into * @param strategiesToRemoveFromWhitelist Strategies that will be removed to the `strategyIsWhitelistedForDeposit` mapping (if they are in it) */ function removeStrategiesFromDepositWhitelist(IStrategy[] calldata strategiesToRemoveFromWhitelist) external; /** * If true for a strategy, a user cannot depositIntoStrategyWithSignature into that strategy for another staker * and also when performing DelegationManager.queueWithdrawals, a staker can only withdraw to themselves. * Defaulted to false for all existing strategies. * @param strategy The strategy to set `thirdPartyTransfersForbidden` value to * @param value bool value to set `thirdPartyTransfersForbidden` to */ function setThirdPartyTransfersForbidden(IStrategy strategy, bool value) external; /// @notice Returns the single, central Delegation contract of EigenLayer function delegation() external view returns (IDelegationManager); /// @notice Returns the single, central Slasher contract of EigenLayer function slasher() external view returns (ISlasher); /// @notice Returns the EigenPodManager contract of EigenLayer function eigenPodManager() external view returns (IEigenPodManager); /// @notice Returns the address of the `strategyWhitelister` function strategyWhitelister() external view returns (address); /// @notice Returns bool for whether or not `strategy` is whitelisted for deposit function strategyIsWhitelistedForDeposit(IStrategy strategy) external view returns (bool); /** * @notice Returns bool for whether or not `strategy` enables credit transfers. i.e enabling * depositIntoStrategyWithSignature calls or queueing withdrawals to a different address than the staker. */ function thirdPartyTransfersForbidden(IStrategy strategy) external view returns (bool); }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; import "@openzeppelin/contracts/proxy/beacon/IBeacon.sol"; import "./IETHPOSDeposit.sol"; import "./IStrategyManager.sol"; import "./IEigenPod.sol"; import "./IPausable.sol"; import "./ISlasher.sol"; import "./IStrategy.sol"; /** * @title Interface for factory that creates and manages solo staking pods that have their withdrawal credentials pointed to EigenLayer. * @author Layr Labs, Inc. * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service */ interface IEigenPodManager is IPausable { /// @notice Emitted to notify the deployment of an EigenPod event PodDeployed(address indexed eigenPod, address indexed podOwner); /// @notice Emitted to notify a deposit of beacon chain ETH recorded in the strategy manager event BeaconChainETHDeposited(address indexed podOwner, uint256 amount); /// @notice Emitted when the balance of an EigenPod is updated event PodSharesUpdated(address indexed podOwner, int256 sharesDelta); /// @notice Emitted every time the total shares of a pod are updated event NewTotalShares(address indexed podOwner, int256 newTotalShares); /// @notice Emitted when a withdrawal of beacon chain ETH is completed event BeaconChainETHWithdrawalCompleted( address indexed podOwner, uint256 shares, uint96 nonce, address delegatedAddress, address withdrawer, bytes32 withdrawalRoot ); /** * @notice Creates an EigenPod for the sender. * @dev Function will revert if the `msg.sender` already has an EigenPod. * @dev Returns EigenPod address */ function createPod() external returns (address); /** * @notice Stakes for a new beacon chain validator on the sender's EigenPod. * Also creates an EigenPod for the sender if they don't have one already. * @param pubkey The 48 bytes public key of the beacon chain validator. * @param signature The validator's signature of the deposit data. * @param depositDataRoot The root/hash of the deposit data for the validator's deposit. */ function stake(bytes calldata pubkey, bytes calldata signature, bytes32 depositDataRoot) external payable; /** * @notice Changes the `podOwner`'s shares by `sharesDelta` and performs a call to the DelegationManager * to ensure that delegated shares are also tracked correctly * @param podOwner is the pod owner whose balance is being updated. * @param sharesDelta is the change in podOwner's beaconChainETHStrategy shares * @dev Callable only by the podOwner's EigenPod contract. * @dev Reverts if `sharesDelta` is not a whole Gwei amount */ function recordBeaconChainETHBalanceUpdate(address podOwner, int256 sharesDelta) external; /// @notice Returns the address of the `podOwner`'s EigenPod if it has been deployed. function ownerToPod(address podOwner) external view returns (IEigenPod); /// @notice Returns the address of the `podOwner`'s EigenPod (whether it is deployed yet or not). function getPod(address podOwner) external view returns (IEigenPod); /// @notice The ETH2 Deposit Contract function ethPOS() external view returns (IETHPOSDeposit); /// @notice Beacon proxy to which the EigenPods point function eigenPodBeacon() external view returns (IBeacon); /// @notice EigenLayer's StrategyManager contract function strategyManager() external view returns (IStrategyManager); /// @notice EigenLayer's Slasher contract function slasher() external view returns (ISlasher); /// @notice Returns 'true' if the `podOwner` has created an EigenPod, and 'false' otherwise. function hasPod(address podOwner) external view returns (bool); /// @notice Returns the number of EigenPods that have been created function numPods() external view returns (uint256); /** * @notice Mapping from Pod owner owner to the number of shares they have in the virtual beacon chain ETH strategy. * @dev The share amount can become negative. This is necessary to accommodate the fact that a pod owner's virtual beacon chain ETH shares can * decrease between the pod owner queuing and completing a withdrawal. * When the pod owner's shares would otherwise increase, this "deficit" is decreased first _instead_. * Likewise, when a withdrawal is completed, this "deficit" is decreased and the withdrawal amount is decreased; We can think of this * as the withdrawal "paying off the deficit". */ function podOwnerShares(address podOwner) external view returns (int256); /// @notice returns canonical, virtual beaconChainETH strategy function beaconChainETHStrategy() external view returns (IStrategy); /** * @notice Used by the DelegationManager to remove a pod owner's shares while they're in the withdrawal queue. * Simply decreases the `podOwner`'s shares by `shares`, down to a minimum of zero. * @dev This function reverts if it would result in `podOwnerShares[podOwner]` being less than zero, i.e. it is forbidden for this function to * result in the `podOwner` incurring a "share deficit". This behavior prevents a Staker from queuing a withdrawal which improperly removes excessive * shares from the operator to whom the staker is delegated. * @dev Reverts if `shares` is not a whole Gwei amount */ function removeShares(address podOwner, uint256 shares) external; /** * @notice Increases the `podOwner`'s shares by `shares`, paying off deficit if possible. * Used by the DelegationManager to award a pod owner shares on exiting the withdrawal queue * @dev Returns the number of shares added to `podOwnerShares[podOwner]` above zero, which will be less than the `shares` input * in the event that the podOwner has an existing shares deficit (i.e. `podOwnerShares[podOwner]` starts below zero) * @dev Reverts if `shares` is not a whole Gwei amount */ function addShares(address podOwner, uint256 shares) external returns (uint256); /** * @notice Used by the DelegationManager to complete a withdrawal, sending tokens to some destination address * @dev Prioritizes decreasing the podOwner's share deficit, if they have one * @dev Reverts if `shares` is not a whole Gwei amount */ function withdrawSharesAsTokens(address podOwner, address destination, uint256 shares) external; }
// SPDX-License-Identifier: BSD 3-Clause License pragma solidity ^0.8.24; import {BeaconChainProofs} from "lib/eigenlayer-contracts/src/contracts/libraries/BeaconChainProofs.sol"; import {IStakingNodesManager} from "src/interfaces/IStakingNodesManager.sol"; import {IStrategy} from "lib/eigenlayer-contracts/src/contracts/interfaces/IStrategyManager.sol"; import {IEigenPod} from "lib/eigenlayer-contracts/src/contracts/interfaces/IEigenPod.sol"; import {ISignatureUtils} from "lib/eigenlayer-contracts/src/contracts/interfaces/ISignatureUtils.sol"; import {IDelegationManager} from "lib/eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; struct WithdrawalCompletionParams { uint256 middlewareTimesIndex; uint256 amount; uint32 withdrawalStartBlock; address delegatedAddress; uint96 nonce; } interface IStakingEvents { /// @notice Emitted when a user stakes ETH and receives ynETH. /// @param staker The address of the user staking ETH. /// @param ethAmount The amount of ETH staked. /// @param ynETHAmount The amount of ynETH received. event Staked(address indexed staker, uint256 ethAmount, uint256 ynETHAmount); event DepositETHPausedUpdated(bool isPaused); event Deposit(address indexed sender, address indexed receiver, uint256 assets, uint256 shares); } interface IStakingNode { /// @notice Configuration for contract initialization. struct Init { IStakingNodesManager stakingNodesManager; uint256 nodeId; } function stakingNodesManager() external view returns (IStakingNodesManager); function eigenPod() external view returns (IEigenPod); function initialize(Init memory init) external; function createEigenPod() external returns (IEigenPod); function delegate( address operator, ISignatureUtils.SignatureWithExpiry memory approverSignatureAndExpiry, bytes32 approverSalt ) external; function undelegate() external; function implementation() external view returns (address); function allocateStakedETH(uint256 amount) external payable; function deallocateStakedETH(uint256 amount) external payable; function getETHBalance() external view returns (uint256); function unverifiedStakedETH() external view returns (uint256); function nodeId() external view returns (uint256); /// @notice Returns the beaconChainETHStrategy address used by the StakingNode. function beaconChainETHStrategy() external view returns (IStrategy); /** * @notice Verifies the withdrawal credentials and balance of validators. * @param beaconTimestamp An array of oracle block numbers corresponding to each validator. * @param stateRootProof An array of state root proofs corresponding to each validator. * @param validatorIndices An array of validator indices. * @param validatorFieldsProofs An array of ValidatorFieldsAndBalanceProofs, containing the merkle proofs for validator fields and balances. * @param validatorFields An array of arrays, each containing the validator fields to be verified. */ function verifyWithdrawalCredentials( uint64 beaconTimestamp, BeaconChainProofs.StateRootProof calldata stateRootProof, uint40[] calldata validatorIndices, bytes[] calldata validatorFieldsProofs, bytes32[][] calldata validatorFields ) external; function queueWithdrawals( uint256 sharesAmount ) external returns (bytes32[] memory fullWithdrawalRoots); function completeQueuedWithdrawals( IDelegationManager.Withdrawal[] memory withdrawals, uint256[] memory middlewareTimesIndexes ) external; function getInitializedVersion() external view returns (uint64); function getUnverifiedStakedETH() external view returns (uint256); function getQueuedSharesAmount() external view returns (uint256); function getWithdrawnETH() external view returns (uint256); function startCheckpoint(bool revertIfNoBalance) external; function initializeV2(uint256 initialUnverifiedStakedETH) external; }
// SPDX-License-Identifier: BSD 3-Clause License pragma solidity ^0.8.24; import "lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol"; interface IRedemptionAssetsVault { // Events event AssetsDeposited( address indexed asset, address indexed depositor, uint256 amount); event AssetTransferred(address indexed asset, address indexed redeemer, address indexed to, uint256 amount); event AssetWithdrawn(address indexed asset, address indexed redeemer, address indexed to, uint256 amount); /// @notice Transfers redemption assets to a specified address based on redemption. /// @dev This is only for INTERNAL USE /// @param to The address to which the assets will be transferred. /// @param amount The amount in unit of account /// @param data Extra data payload for redemption request function transferRedemptionAssets(address to, uint256 amount, bytes calldata data) external; /// @notice Withdraws redemption assets from the queue's balance /// @param amount The amount in unit of account function withdrawRedemptionAssets(uint256 amount) external; /// @notice Retrieves the current redemption rate for the asset in the unit of account. /// @return The current redemption rate function redemptionRate() external view returns (uint256); /// @notice Gets the total amount of redemption assets available for withdrawal in the unit of account. /// @return The available amount of redemption assets function availableRedemptionAssets() external view returns (uint256); }
// SPDX-License-Identifier: BSD 3-Clause License pragma solidity ^0.8.24; import {IERC20} from "lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol"; interface IRewardsReceiver { /// @notice Configuration for contract initialization. struct Init { address admin; address withdrawer; } /// @notice Initializes the contract. /// @dev MUST be called during the contract upgrade to set up the proxies state. function initialize(Init memory init) external; /// @notice Transfers the given amount of ETH to an address. /// @dev Only callable by the withdrawer. function transferETH(address payable to, uint256 amount) external; /// @notice Transfers the given amount of an ERC20 token to an address. /// @dev Only callable by the withdrawer. function transferERC20(IERC20 token, address to, uint256 amount) external; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC-20 standard as defined in the ERC. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the value of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the value of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves a `value` amount of tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 value) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets a `value` amount of tokens as the allowance of `spender` over the * caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 value) external returns (bool); /** * @dev Moves a `value` amount of tokens from `from` to `to` using the * allowance mechanism. `value` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 value) external returns (bool); }
// SPDX-License-Identifier: BSD 3-Clause License pragma solidity ^0.8.24; import "lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol"; interface IRedeemableAsset is IERC20Metadata { function burn(uint256 amount) external; function processWithdrawnETH() external payable; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol"; import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol"; import {Initializable} from "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * TIP: For a detailed writeup see our guide * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * The default value of {decimals} is 18. To change this, you should override * this function so it returns a different value. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC-20 * applications. */ abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors { /// @custom:storage-location erc7201:openzeppelin.storage.ERC20 struct ERC20Storage { mapping(address account => uint256) _balances; mapping(address account => mapping(address spender => uint256)) _allowances; uint256 _totalSupply; string _name; string _symbol; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00; function _getERC20Storage() private pure returns (ERC20Storage storage $) { assembly { $.slot := ERC20StorageLocation } } /** * @dev Sets the values for {name} and {symbol}. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { ERC20Storage storage $ = _getERC20Storage(); $._name = name_; $._symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { ERC20Storage storage $ = _getERC20Storage(); return $._name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { ERC20Storage storage $ = _getERC20Storage(); return $._symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the default value returned by this function, unless * it's overridden. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual returns (uint256) { ERC20Storage storage $ = _getERC20Storage(); return $._totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual returns (uint256) { ERC20Storage storage $ = _getERC20Storage(); return $._balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `value`. */ function transfer(address to, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _transfer(owner, to, value); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual returns (uint256) { ERC20Storage storage $ = _getERC20Storage(); return $._allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Skips emitting an {Approval} event indicating an allowance update. This is not * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve]. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `value`. * - the caller must have allowance for ``from``'s tokens of at least * `value`. */ function transferFrom(address from, address to, uint256 value) public virtual returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, value); _transfer(from, to, value); return true; } /** * @dev Moves a `value` amount of tokens from `from` to `to`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * NOTE: This function is not virtual, {_update} should be overridden instead. */ function _transfer(address from, address to, uint256 value) internal { if (from == address(0)) { revert ERC20InvalidSender(address(0)); } if (to == address(0)) { revert ERC20InvalidReceiver(address(0)); } _update(from, to, value); } /** * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from` * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding * this function. * * Emits a {Transfer} event. */ function _update(address from, address to, uint256 value) internal virtual { ERC20Storage storage $ = _getERC20Storage(); if (from == address(0)) { // Overflow check required: The rest of the code assumes that totalSupply never overflows $._totalSupply += value; } else { uint256 fromBalance = $._balances[from]; if (fromBalance < value) { revert ERC20InsufficientBalance(from, fromBalance, value); } unchecked { // Overflow not possible: value <= fromBalance <= totalSupply. $._balances[from] = fromBalance - value; } } if (to == address(0)) { unchecked { // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply. $._totalSupply -= value; } } else { unchecked { // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256. $._balances[to] += value; } } emit Transfer(from, to, value); } /** * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0). * Relies on the `_update` mechanism * * Emits a {Transfer} event with `from` set to the zero address. * * NOTE: This function is not virtual, {_update} should be overridden instead. */ function _mint(address account, uint256 value) internal { if (account == address(0)) { revert ERC20InvalidReceiver(address(0)); } _update(address(0), account, value); } /** * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply. * Relies on the `_update` mechanism. * * Emits a {Transfer} event with `to` set to the zero address. * * NOTE: This function is not virtual, {_update} should be overridden instead */ function _burn(address account, uint256 value) internal { if (account == address(0)) { revert ERC20InvalidSender(address(0)); } _update(account, address(0), value); } /** * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. * * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument. */ function _approve(address owner, address spender, uint256 value) internal { _approve(owner, spender, value, true); } /** * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event. * * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any * `Approval` event during `transferFrom` operations. * * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to * true using the following override: * * ```solidity * function _approve(address owner, address spender, uint256 value, bool) internal virtual override { * super._approve(owner, spender, value, true); * } * ``` * * Requirements are the same as {_approve}. */ function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual { ERC20Storage storage $ = _getERC20Storage(); if (owner == address(0)) { revert ERC20InvalidApprover(address(0)); } if (spender == address(0)) { revert ERC20InvalidSpender(address(0)); } $._allowances[owner][spender] = value; if (emitEvent) { emit Approval(owner, spender, value); } } /** * @dev Updates `owner` s allowance for `spender` based on spent `value`. * * Does not update the allowance value in case of infinite allowance. * Revert if not enough allowance is available. * * Does not emit an {Approval} event. */ function _spendAllowance(address owner, address spender, uint256 value) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { if (currentAllowance < value) { revert ERC20InsufficientAllowance(spender, currentAllowance, value); } unchecked { _approve(owner, spender, currentAllowance - value, false); } } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol) pragma solidity ^0.8.20; import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol"; import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol"; import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol"; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ```solidity * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ```solidity * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules} * to enforce additional security measures for this role. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable { struct RoleData { mapping(address account => bool) hasRole; bytes32 adminRole; } bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /// @custom:storage-location erc7201:openzeppelin.storage.AccessControl struct AccessControlStorage { mapping(bytes32 role => RoleData) _roles; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800; function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) { assembly { $.slot := AccessControlStorageLocation } } /** * @dev Modifier that checks that an account has a specific role. Reverts * with an {AccessControlUnauthorizedAccount} error including the required role. */ modifier onlyRole(bytes32 role) { _checkRole(role); _; } function __AccessControl_init() internal onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual returns (bool) { AccessControlStorage storage $ = _getAccessControlStorage(); return $._roles[role].hasRole[account]; } /** * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()` * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier. */ function _checkRole(bytes32 role) internal view virtual { _checkRole(role, _msgSender()); } /** * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account` * is missing `role`. */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert AccessControlUnauthorizedAccount(account, role); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) { AccessControlStorage storage $ = _getAccessControlStorage(); return $._roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. * * May emit a {RoleGranted} event. */ function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. * * May emit a {RoleRevoked} event. */ function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `callerConfirmation`. * * May emit a {RoleRevoked} event. */ function renounceRole(bytes32 role, address callerConfirmation) public virtual { if (callerConfirmation != _msgSender()) { revert AccessControlBadConfirmation(); } _revokeRole(role, callerConfirmation); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { AccessControlStorage storage $ = _getAccessControlStorage(); bytes32 previousAdminRole = getRoleAdmin(role); $._roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted. * * Internal function without access restriction. * * May emit a {RoleGranted} event. */ function _grantRole(bytes32 role, address account) internal virtual returns (bool) { AccessControlStorage storage $ = _getAccessControlStorage(); if (!hasRole(role, account)) { $._roles[role].hasRole[account] = true; emit RoleGranted(role, account, _msgSender()); return true; } else { return false; } } /** * @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked. * * Internal function without access restriction. * * May emit a {RoleRevoked} event. */ function _revokeRole(bytes32 role, address account) internal virtual returns (bool) { AccessControlStorage storage $ = _getAccessControlStorage(); if (hasRole(role, account)) { $._roles[role].hasRole[account] = false; emit RoleRevoked(role, account, _msgSender()); return true; } else { return false; } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.20; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {UpgradeableBeacon} will check that this address is a contract. */ function implementation() external view returns (address); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol) pragma solidity ^0.8.20; import {Context} from "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * The initial owner is set to the address provided by the deployer. This can * later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; /** * @dev The caller account is not authorized to perform an operation. */ error OwnableUnauthorizedAccount(address account); /** * @dev The owner is not a valid owner account. (eg. `address(0)`) */ error OwnableInvalidOwner(address owner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the address provided by the deployer as the initial owner. */ constructor(address initialOwner) { if (initialOwner == address(0)) { revert OwnableInvalidOwner(address(0)); } _transferOwnership(initialOwner); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { if (owner() != _msgSender()) { revert OwnableUnauthorizedAccount(_msgSender()); } } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby disabling any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { if (newOwner == address(0)) { revert OwnableInvalidOwner(address(0)); } _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Minimal interface for an `Strategy` contract. * @author Layr Labs, Inc. * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service * @notice Custom `Strategy` implementations may expand extensively on this interface. */ interface IStrategy { /** * @notice Used to emit an event for the exchange rate between 1 share and underlying token in a strategy contract * @param rate is the exchange rate in wad 18 decimals * @dev Tokens that do not have 18 decimals must have offchain services scale the exchange rate by the proper magnitude */ event ExchangeRateEmitted(uint256 rate); /** * Used to emit the underlying token and its decimals on strategy creation * @notice token * @param token is the ERC20 token of the strategy * @param decimals are the decimals of the ERC20 token in the strategy */ event StrategyTokenSet(IERC20 token, uint8 decimals); /** * @notice Used to deposit tokens into this Strategy * @param token is the ERC20 token being deposited * @param amount is the amount of token being deposited * @dev This function is only callable by the strategyManager contract. It is invoked inside of the strategyManager's * `depositIntoStrategy` function, and individual share balances are recorded in the strategyManager as well. * @return newShares is the number of new shares issued at the current exchange ratio. */ function deposit(IERC20 token, uint256 amount) external returns (uint256); /** * @notice Used to withdraw tokens from this Strategy, to the `recipient`'s address * @param recipient is the address to receive the withdrawn funds * @param token is the ERC20 token being transferred out * @param amountShares is the amount of shares being withdrawn * @dev This function is only callable by the strategyManager contract. It is invoked inside of the strategyManager's * other functions, and individual share balances are recorded in the strategyManager as well. */ function withdraw(address recipient, IERC20 token, uint256 amountShares) external; /** * @notice Used to convert a number of shares to the equivalent amount of underlying tokens for this strategy. * @notice In contrast to `sharesToUnderlyingView`, this function **may** make state modifications * @param amountShares is the amount of shares to calculate its conversion into the underlying token * @return The amount of underlying tokens corresponding to the input `amountShares` * @dev Implementation for these functions in particular may vary significantly for different strategies */ function sharesToUnderlying(uint256 amountShares) external returns (uint256); /** * @notice Used to convert an amount of underlying tokens to the equivalent amount of shares in this strategy. * @notice In contrast to `underlyingToSharesView`, this function **may** make state modifications * @param amountUnderlying is the amount of `underlyingToken` to calculate its conversion into strategy shares * @return The amount of underlying tokens corresponding to the input `amountShares` * @dev Implementation for these functions in particular may vary significantly for different strategies */ function underlyingToShares(uint256 amountUnderlying) external returns (uint256); /** * @notice convenience function for fetching the current underlying value of all of the `user`'s shares in * this strategy. In contrast to `userUnderlyingView`, this function **may** make state modifications */ function userUnderlying(address user) external returns (uint256); /** * @notice convenience function for fetching the current total shares of `user` in this strategy, by * querying the `strategyManager` contract */ function shares(address user) external view returns (uint256); /** * @notice Used to convert a number of shares to the equivalent amount of underlying tokens for this strategy. * @notice In contrast to `sharesToUnderlying`, this function guarantees no state modifications * @param amountShares is the amount of shares to calculate its conversion into the underlying token * @return The amount of shares corresponding to the input `amountUnderlying` * @dev Implementation for these functions in particular may vary significantly for different strategies */ function sharesToUnderlyingView(uint256 amountShares) external view returns (uint256); /** * @notice Used to convert an amount of underlying tokens to the equivalent amount of shares in this strategy. * @notice In contrast to `underlyingToShares`, this function guarantees no state modifications * @param amountUnderlying is the amount of `underlyingToken` to calculate its conversion into strategy shares * @return The amount of shares corresponding to the input `amountUnderlying` * @dev Implementation for these functions in particular may vary significantly for different strategies */ function underlyingToSharesView(uint256 amountUnderlying) external view returns (uint256); /** * @notice convenience function for fetching the current underlying value of all of the `user`'s shares in * this strategy. In contrast to `userUnderlying`, this function guarantees no state modifications */ function userUnderlyingView(address user) external view returns (uint256); /// @notice The underlying token for shares in this Strategy function underlyingToken() external view returns (IERC20); /// @notice The total number of extant shares in this Strategy function totalShares() external view returns (uint256); /// @notice Returns either a brief string explaining the strategy's goal & purpose, or a link to metadata that explains in more detail. function explanation() external view returns (string memory); }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; /** * @title The interface for common signature utilities. * @author Layr Labs, Inc. * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service */ interface ISignatureUtils { // @notice Struct that bundles together a signature and an expiration time for the signature. Used primarily for stack management. struct SignatureWithExpiry { // the signature itself, formatted as a single bytes object bytes signature; // the expiration timestamp (UTC) of the signature uint256 expiry; } // @notice Struct that bundles together a signature, a salt for uniqueness, and an expiration time for the signature. Used primarily for stack management. struct SignatureWithSaltAndExpiry { // the signature itself, formatted as a single bytes object bytes signature; // the salt used to generate the signature bytes32 salt; // the expiration timestamp (UTC) of the signature uint256 expiry; } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; import "./IStrategyManager.sol"; import "./IDelegationManager.sol"; /** * @title Interface for the primary 'slashing' contract for EigenLayer. * @author Layr Labs, Inc. * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service * @notice See the `Slasher` contract itself for implementation details. */ interface ISlasher { // struct used to store information about the current state of an operator's obligations to middlewares they are serving struct MiddlewareTimes { // The update block for the middleware whose most recent update was earliest, i.e. the 'stalest' update out of all middlewares the operator is serving uint32 stalestUpdateBlock; // The latest 'serveUntilBlock' from all of the middleware that the operator is serving uint32 latestServeUntilBlock; } // struct used to store details relevant to a single middleware that an operator has opted-in to serving struct MiddlewareDetails { // the block at which the contract begins being able to finalize the operator's registration with the service via calling `recordFirstStakeUpdate` uint32 registrationMayBeginAtBlock; // the block before which the contract is allowed to slash the user uint32 contractCanSlashOperatorUntilBlock; // the block at which the middleware's view of the operator's stake was most recently updated uint32 latestUpdateBlock; } /// @notice Emitted when a middleware times is added to `operator`'s array. event MiddlewareTimesAdded( address operator, uint256 index, uint32 stalestUpdateBlock, uint32 latestServeUntilBlock ); /// @notice Emitted when `operator` begins to allow `contractAddress` to slash them. event OptedIntoSlashing(address indexed operator, address indexed contractAddress); /// @notice Emitted when `contractAddress` signals that it will no longer be able to slash `operator` after the `contractCanSlashOperatorUntilBlock`. event SlashingAbilityRevoked( address indexed operator, address indexed contractAddress, uint32 contractCanSlashOperatorUntilBlock ); /** * @notice Emitted when `slashingContract` 'freezes' the `slashedOperator`. * @dev The `slashingContract` must have permission to slash the `slashedOperator`, i.e. `canSlash(slasherOperator, slashingContract)` must return 'true'. */ event OperatorFrozen(address indexed slashedOperator, address indexed slashingContract); /// @notice Emitted when `previouslySlashedAddress` is 'unfrozen', allowing them to again move deposited funds within EigenLayer. event FrozenStatusReset(address indexed previouslySlashedAddress); /** * @notice Gives the `contractAddress` permission to slash the funds of the caller. * @dev Typically, this function must be called prior to registering for a middleware. */ function optIntoSlashing(address contractAddress) external; /** * @notice Used for 'slashing' a certain operator. * @param toBeFrozen The operator to be frozen. * @dev Technically the operator is 'frozen' (hence the name of this function), and then subject to slashing pending a decision by a human-in-the-loop. * @dev The operator must have previously given the caller (which should be a contract) the ability to slash them, through a call to `optIntoSlashing`. */ function freezeOperator(address toBeFrozen) external; /** * @notice Removes the 'frozen' status from each of the `frozenAddresses` * @dev Callable only by the contract owner (i.e. governance). */ function resetFrozenStatus(address[] calldata frozenAddresses) external; /** * @notice this function is a called by middlewares during an operator's registration to make sure the operator's stake at registration * is slashable until serveUntil * @param operator the operator whose stake update is being recorded * @param serveUntilBlock the block until which the operator's stake at the current block is slashable * @dev adds the middleware's slashing contract to the operator's linked list */ function recordFirstStakeUpdate(address operator, uint32 serveUntilBlock) external; /** * @notice this function is a called by middlewares during a stake update for an operator (perhaps to free pending withdrawals) * to make sure the operator's stake at updateBlock is slashable until serveUntil * @param operator the operator whose stake update is being recorded * @param updateBlock the block for which the stake update is being recorded * @param serveUntilBlock the block until which the operator's stake at updateBlock is slashable * @param insertAfter the element of the operators linked list that the currently updating middleware should be inserted after * @dev insertAfter should be calculated offchain before making the transaction that calls this. this is subject to race conditions, * but it is anticipated to be rare and not detrimental. */ function recordStakeUpdate( address operator, uint32 updateBlock, uint32 serveUntilBlock, uint256 insertAfter ) external; /** * @notice this function is a called by middlewares during an operator's deregistration to make sure the operator's stake at deregistration * is slashable until serveUntil * @param operator the operator whose stake update is being recorded * @param serveUntilBlock the block until which the operator's stake at the current block is slashable * @dev removes the middleware's slashing contract to the operator's linked list and revokes the middleware's (i.e. caller's) ability to * slash `operator` once `serveUntil` is reached */ function recordLastStakeUpdateAndRevokeSlashingAbility(address operator, uint32 serveUntilBlock) external; /// @notice The StrategyManager contract of EigenLayer function strategyManager() external view returns (IStrategyManager); /// @notice The DelegationManager contract of EigenLayer function delegation() external view returns (IDelegationManager); /** * @notice Used to determine whether `staker` is actively 'frozen'. If a staker is frozen, then they are potentially subject to * slashing of their funds, and cannot cannot deposit or withdraw from the strategyManager until the slashing process is completed * and the staker's status is reset (to 'unfrozen'). * @param staker The staker of interest. * @return Returns 'true' if `staker` themselves has their status set to frozen, OR if the staker is delegated * to an operator who has their status set to frozen. Otherwise returns 'false'. */ function isFrozen(address staker) external view returns (bool); /// @notice Returns true if `slashingContract` is currently allowed to slash `toBeSlashed`. function canSlash(address toBeSlashed, address slashingContract) external view returns (bool); /// @notice Returns the block until which `serviceContract` is allowed to slash the `operator`. function contractCanSlashOperatorUntilBlock( address operator, address serviceContract ) external view returns (uint32); /// @notice Returns the block at which the `serviceContract` last updated its view of the `operator`'s stake function latestUpdateBlock(address operator, address serviceContract) external view returns (uint32); /// @notice A search routine for finding the correct input value of `insertAfter` to `recordStakeUpdate` / `_updateMiddlewareList`. function getCorrectValueForInsertAfter(address operator, uint32 updateBlock) external view returns (uint256); /** * @notice Returns 'true' if `operator` can currently complete a withdrawal started at the `withdrawalStartBlock`, with `middlewareTimesIndex` used * to specify the index of a `MiddlewareTimes` struct in the operator's list (i.e. an index in `operatorToMiddlewareTimes[operator]`). The specified * struct is consulted as proof of the `operator`'s ability (or lack thereof) to complete the withdrawal. * This function will return 'false' if the operator cannot currently complete a withdrawal started at the `withdrawalStartBlock`, *or* in the event * that an incorrect `middlewareTimesIndex` is supplied, even if one or more correct inputs exist. * @param operator Either the operator who queued the withdrawal themselves, or if the withdrawing party is a staker who delegated to an operator, * this address is the operator *who the staker was delegated to* at the time of the `withdrawalStartBlock`. * @param withdrawalStartBlock The block number at which the withdrawal was initiated. * @param middlewareTimesIndex Indicates an index in `operatorToMiddlewareTimes[operator]` to consult as proof of the `operator`'s ability to withdraw * @dev The correct `middlewareTimesIndex` input should be computable off-chain. */ function canWithdraw( address operator, uint32 withdrawalStartBlock, uint256 middlewareTimesIndex ) external returns (bool); /** * operator => * [ * ( * the least recent update block of all of the middlewares it's serving/served, * latest time that the stake bonded at that update needed to serve until * ) * ] */ function operatorToMiddlewareTimes( address operator, uint256 arrayIndex ) external view returns (MiddlewareTimes memory); /// @notice Getter function for fetching `operatorToMiddlewareTimes[operator].length` function middlewareTimesLength(address operator) external view returns (uint256); /// @notice Getter function for fetching `operatorToMiddlewareTimes[operator][index].stalestUpdateBlock`. function getMiddlewareTimesIndexStalestUpdateBlock(address operator, uint32 index) external view returns (uint32); /// @notice Getter function for fetching `operatorToMiddlewareTimes[operator][index].latestServeUntil`. function getMiddlewareTimesIndexServeUntilBlock(address operator, uint32 index) external view returns (uint32); /// @notice Getter function for fetching `_operatorToWhitelistedContractsByUpdate[operator].size`. function operatorWhitelistedContractsLinkedListSize(address operator) external view returns (uint256); /// @notice Getter function for fetching a single node in the operator's linked list (`_operatorToWhitelistedContractsByUpdate[operator]`). function operatorWhitelistedContractsLinkedListEntry( address operator, address node ) external view returns (bool, uint256, uint256); }
// ┏━━━┓━┏┓━┏┓━━┏━━━┓━━┏━━━┓━━━━┏━━━┓━━━━━━━━━━━━━━━━━━━┏┓━━━━━┏━━━┓━━━━━━━━━┏┓━━━━━━━━━━━━━━┏┓━ // ┃┏━━┛┏┛┗┓┃┃━━┃┏━┓┃━━┃┏━┓┃━━━━┗┓┏┓┃━━━━━━━━━━━━━━━━━━┏┛┗┓━━━━┃┏━┓┃━━━━━━━━┏┛┗┓━━━━━━━━━━━━┏┛┗┓ // ┃┗━━┓┗┓┏┛┃┗━┓┗┛┏┛┃━━┃┃━┃┃━━━━━┃┃┃┃┏━━┓┏━━┓┏━━┓┏━━┓┏┓┗┓┏┛━━━━┃┃━┗┛┏━━┓┏━┓━┗┓┏┛┏━┓┏━━┓━┏━━┓┗┓┏┛ // ┃┏━━┛━┃┃━┃┏┓┃┏━┛┏┛━━┃┃━┃┃━━━━━┃┃┃┃┃┏┓┃┃┏┓┃┃┏┓┃┃━━┫┣┫━┃┃━━━━━┃┃━┏┓┃┏┓┃┃┏┓┓━┃┃━┃┏┛┗━┓┃━┃┏━┛━┃┃━ // ┃┗━━┓━┃┗┓┃┃┃┃┃┃┗━┓┏┓┃┗━┛┃━━━━┏┛┗┛┃┃┃━┫┃┗┛┃┃┗┛┃┣━━┃┃┃━┃┗┓━━━━┃┗━┛┃┃┗┛┃┃┃┃┃━┃┗┓┃┃━┃┗┛┗┓┃┗━┓━┃┗┓ // ┗━━━┛━┗━┛┗┛┗┛┗━━━┛┗┛┗━━━┛━━━━┗━━━┛┗━━┛┃┏━┛┗━━┛┗━━┛┗┛━┗━┛━━━━┗━━━┛┗━━┛┗┛┗┛━┗━┛┗┛━┗━━━┛┗━━┛━┗━┛ // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┃┃━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┗┛━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ // SPDX-License-Identifier: CC0-1.0 pragma solidity >=0.5.0; // This interface is designed to be compatible with the Vyper version. /// @notice This is the Ethereum 2.0 deposit contract interface. /// For more information see the Phase 0 specification under https://github.com/ethereum/eth2.0-specs interface IETHPOSDeposit { /// @notice A processed deposit event. event DepositEvent(bytes pubkey, bytes withdrawal_credentials, bytes amount, bytes signature, bytes index); /// @notice Submit a Phase 0 DepositData object. /// @param pubkey A BLS12-381 public key. /// @param withdrawal_credentials Commitment to a public key for withdrawals. /// @param signature A BLS12-381 signature. /// @param deposit_data_root The SHA-256 hash of the SSZ-encoded DepositData object. /// Used as a protection against malformed input. function deposit( bytes calldata pubkey, bytes calldata withdrawal_credentials, bytes calldata signature, bytes32 deposit_data_root ) external payable; /// @notice Query the current deposit root hash. /// @return The deposit root hash. function get_deposit_root() external view returns (bytes32); /// @notice Query the current deposit count. /// @return The deposit count encoded as a little endian 64-bit number. function get_deposit_count() external view returns (bytes memory); }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; import "../libraries/BeaconChainProofs.sol"; import "./IEigenPodManager.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title The implementation contract used for restaking beacon chain ETH on EigenLayer * @author Layr Labs, Inc. * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service * @dev Note that all beacon chain balances are stored as gwei within the beacon chain datastructures. We choose * to account balances in terms of gwei in the EigenPod contract and convert to wei when making calls to other contracts */ interface IEigenPod { /** * * STRUCTS / ENUMS * */ enum VALIDATOR_STATUS { INACTIVE, // doesnt exist ACTIVE, // staked on ethpos and withdrawal credentials are pointed to the EigenPod WITHDRAWN // withdrawn from the Beacon Chain } struct ValidatorInfo { // index of the validator in the beacon chain uint64 validatorIndex; // amount of beacon chain ETH restaked on EigenLayer in gwei uint64 restakedBalanceGwei; //timestamp of the validator's most recent balance update uint64 lastCheckpointedAt; // status of the validator VALIDATOR_STATUS status; } struct Checkpoint { bytes32 beaconBlockRoot; uint24 proofsRemaining; uint64 podBalanceGwei; int128 balanceDeltasGwei; } /** * * EVENTS * */ /// @notice Emitted when an ETH validator stakes via this eigenPod event EigenPodStaked(bytes pubkey); /// @notice Emitted when a pod owner updates the proof submitter address event ProofSubmitterUpdated(address prevProofSubmitter, address newProofSubmitter); /// @notice Emitted when an ETH validator's withdrawal credentials are successfully verified to be pointed to this eigenPod event ValidatorRestaked(uint40 validatorIndex); /// @notice Emitted when an ETH validator's balance is proven to be updated. Here newValidatorBalanceGwei // is the validator's balance that is credited on EigenLayer. event ValidatorBalanceUpdated(uint40 validatorIndex, uint64 balanceTimestamp, uint64 newValidatorBalanceGwei); /// @notice Emitted when restaked beacon chain ETH is withdrawn from the eigenPod. event RestakedBeaconChainETHWithdrawn(address indexed recipient, uint256 amount); /// @notice Emitted when ETH is received via the `receive` fallback event NonBeaconChainETHReceived(uint256 amountReceived); /// @notice Emitted when a checkpoint is created event CheckpointCreated( uint64 indexed checkpointTimestamp, bytes32 indexed beaconBlockRoot, uint256 validatorCount ); /// @notice Emitted when a checkpoint is finalized event CheckpointFinalized(uint64 indexed checkpointTimestamp, int256 totalShareDeltaWei); /// @notice Emitted when a validator is proven for a given checkpoint event ValidatorCheckpointed(uint64 indexed checkpointTimestamp, uint40 indexed validatorIndex); /// @notice Emitted when a validaor is proven to have 0 balance at a given checkpoint event ValidatorWithdrawn(uint64 indexed checkpointTimestamp, uint40 indexed validatorIndex); /** * * EXTERNAL STATE-CHANGING METHODS * */ /// @notice Used to initialize the pointers to contracts crucial to the pod's functionality, in beacon proxy construction from EigenPodManager function initialize(address owner) external; /// @notice Called by EigenPodManager when the owner wants to create another ETH validator. function stake(bytes calldata pubkey, bytes calldata signature, bytes32 depositDataRoot) external payable; /** * @notice Transfers `amountWei` in ether from this contract to the specified `recipient` address * @notice Called by EigenPodManager to withdrawBeaconChainETH that has been added to the EigenPod's balance due to a withdrawal from the beacon chain. * @dev The podOwner must have already proved sufficient withdrawals, so that this pod's `withdrawableRestakedExecutionLayerGwei` exceeds the * `amountWei` input (when converted to GWEI). * @dev Reverts if `amountWei` is not a whole Gwei amount */ function withdrawRestakedBeaconChainETH(address recipient, uint256 amount) external; /** * @dev Create a checkpoint used to prove this pod's active validator set. Checkpoints are completed * by submitting one checkpoint proof per ACTIVE validator. During the checkpoint process, the total * change in ACTIVE validator balance is tracked, and any validators with 0 balance are marked `WITHDRAWN`. * @dev Once finalized, the pod owner is awarded shares corresponding to: * - the total change in their ACTIVE validator balances * - any ETH in the pod not already awarded shares * @dev A checkpoint cannot be created if the pod already has an outstanding checkpoint. If * this is the case, the pod owner MUST complete the existing checkpoint before starting a new one. * @param revertIfNoBalance Forces a revert if the pod ETH balance is 0. This allows the pod owner * to prevent accidentally starting a checkpoint that will not increase their shares */ function startCheckpoint(bool revertIfNoBalance) external; /** * @dev Progress the current checkpoint towards completion by submitting one or more validator * checkpoint proofs. Anyone can call this method to submit proofs towards the current checkpoint. * For each validator proven, the current checkpoint's `proofsRemaining` decreases. * @dev If the checkpoint's `proofsRemaining` reaches 0, the checkpoint is finalized. * (see `_updateCheckpoint` for more details) * @dev This method can only be called when there is a currently-active checkpoint. * @param balanceContainerProof proves the beacon's current balance container root against a checkpoint's `beaconBlockRoot` * @param proofs Proofs for one or more validator current balances against the `balanceContainerRoot` */ function verifyCheckpointProofs( BeaconChainProofs.BalanceContainerProof calldata balanceContainerProof, BeaconChainProofs.BalanceProof[] calldata proofs ) external; /** * @dev Verify one or more validators have their withdrawal credentials pointed at this EigenPod, and award * shares based on their effective balance. Proven validators are marked `ACTIVE` within the EigenPod, and * future checkpoint proofs will need to include them. * @dev Withdrawal credential proofs MUST NOT be older than `currentCheckpointTimestamp`. * @dev Validators proven via this method MUST NOT have an exit epoch set already. * @param beaconTimestamp the beacon chain timestamp sent to the 4788 oracle contract. Corresponds * to the parent beacon block root against which the proof is verified. * @param stateRootProof proves a beacon state root against a beacon block root * @param validatorIndices a list of validator indices being proven * @param validatorFieldsProofs proofs of each validator's `validatorFields` against the beacon state root * @param validatorFields the fields of the beacon chain "Validator" container. See consensus specs for * details: https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#validator */ function verifyWithdrawalCredentials( uint64 beaconTimestamp, BeaconChainProofs.StateRootProof calldata stateRootProof, uint40[] calldata validatorIndices, bytes[] calldata validatorFieldsProofs, bytes32[][] calldata validatorFields ) external; /** * @dev Prove that one of this pod's active validators was slashed on the beacon chain. A successful * staleness proof allows the caller to start a checkpoint. * * @dev Note that in order to start a checkpoint, any existing checkpoint must already be completed! * (See `_startCheckpoint` for details) * * @dev Note that this method allows anyone to start a checkpoint as soon as a slashing occurs on the beacon * chain. This is intended to make it easier to external watchers to keep a pod's balance up to date. * * @dev Note too that beacon chain slashings are not instant. There is a delay between the initial slashing event * and the validator's final exit back to the execution layer. During this time, the validator's balance may or * may not drop further due to a correlation penalty. This method allows proof of a slashed validator * to initiate a checkpoint for as long as the validator remains on the beacon chain. Once the validator * has exited and been checkpointed at 0 balance, they are no longer "checkpoint-able" and cannot be proven * "stale" via this method. * See https://eth2book.info/capella/part3/transition/epoch/#slashings for more info. * * @param beaconTimestamp the beacon chain timestamp sent to the 4788 oracle contract. Corresponds * to the parent beacon block root against which the proof is verified. * @param stateRootProof proves a beacon state root against a beacon block root * @param proof the fields of the beacon chain "Validator" container, along with a merkle proof against * the beacon state root. See the consensus specs for more details: * https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#validator * * @dev Staleness conditions: * - Validator's last checkpoint is older than `beaconTimestamp` * - Validator MUST be in `ACTIVE` status in the pod * - Validator MUST be slashed on the beacon chain */ function verifyStaleBalance( uint64 beaconTimestamp, BeaconChainProofs.StateRootProof calldata stateRootProof, BeaconChainProofs.ValidatorProof calldata proof ) external; /// @notice called by owner of a pod to remove any ERC20s deposited in the pod function recoverTokens(IERC20[] memory tokenList, uint256[] memory amountsToWithdraw, address recipient) external; /// @notice Allows the owner of a pod to update the proof submitter, a permissioned /// address that can call `startCheckpoint` and `verifyWithdrawalCredentials`. /// @dev Note that EITHER the podOwner OR proofSubmitter can access these methods, /// so it's fine to set your proofSubmitter to 0 if you want the podOwner to be the /// only address that can call these methods. /// @param newProofSubmitter The new proof submitter address. If set to 0, only the /// pod owner will be able to call `startCheckpoint` and `verifyWithdrawalCredentials` function setProofSubmitter(address newProofSubmitter) external; /** * * VIEW METHODS * */ /// @notice An address with permissions to call `startCheckpoint` and `verifyWithdrawalCredentials`, set /// by the podOwner. This role exists to allow a podOwner to designate a hot wallet that can call /// these methods, allowing the podOwner to remain a cold wallet that is only used to manage funds. /// @dev If this address is NOT set, only the podOwner can call `startCheckpoint` and `verifyWithdrawalCredentials` function proofSubmitter() external view returns (address); /// @notice the amount of execution layer ETH in this contract that is staked in EigenLayer (i.e. withdrawn from beaconchain but not EigenLayer), function withdrawableRestakedExecutionLayerGwei() external view returns (uint64); /// @notice The single EigenPodManager for EigenLayer function eigenPodManager() external view returns (IEigenPodManager); /// @notice The owner of this EigenPod function podOwner() external view returns (address); /// @notice Returns the validatorInfo struct for the provided pubkeyHash function validatorPubkeyHashToInfo(bytes32 validatorPubkeyHash) external view returns (ValidatorInfo memory); /// @notice Returns the validatorInfo struct for the provided pubkey function validatorPubkeyToInfo(bytes calldata validatorPubkey) external view returns (ValidatorInfo memory); /// @notice This returns the status of a given validator function validatorStatus(bytes32 pubkeyHash) external view returns (VALIDATOR_STATUS); /// @notice This returns the status of a given validator pubkey function validatorStatus(bytes calldata validatorPubkey) external view returns (VALIDATOR_STATUS); /// @notice Number of validators with proven withdrawal credentials, who do not have proven full withdrawals function activeValidatorCount() external view returns (uint256); /// @notice The timestamp of the last checkpoint finalized function lastCheckpointTimestamp() external view returns (uint64); /// @notice The timestamp of the currently-active checkpoint. Will be 0 if there is not active checkpoint function currentCheckpointTimestamp() external view returns (uint64); /// @notice Returns the currently-active checkpoint function currentCheckpoint() external view returns (Checkpoint memory); /// @notice For each checkpoint, the total balance attributed to exited validators, in gwei /// /// NOTE that the values added to this mapping are NOT guaranteed to capture the entirety of a validator's /// exit - rather, they capture the total change in a validator's balance when a checkpoint shows their /// balance change from nonzero to zero. While a change from nonzero to zero DOES guarantee that a validator /// has been fully exited, it is possible that the magnitude of this change does not capture what is /// typically thought of as a "full exit." /// /// For example: /// 1. Consider a validator was last checkpointed at 32 ETH before exiting. Once the exit has been processed, /// it is expected that the validator's exited balance is calculated to be `32 ETH`. /// 2. However, before `startCheckpoint` is called, a deposit is made to the validator for 1 ETH. The beacon /// chain will automatically withdraw this ETH, but not until the withdrawal sweep passes over the validator /// again. Until this occurs, the validator's current balance (used for checkpointing) is 1 ETH. /// 3. If `startCheckpoint` is called at this point, the balance delta calculated for this validator will be /// `-31 ETH`, and because the validator has a nonzero balance, it is not marked WITHDRAWN. /// 4. After the exit is processed by the beacon chain, a subsequent `startCheckpoint` and checkpoint proof /// will calculate a balance delta of `-1 ETH` and attribute a 1 ETH exit to the validator. /// /// If this edge case impacts your usecase, it should be possible to mitigate this by monitoring for deposits /// to your exited validators, and waiting to call `startCheckpoint` until those deposits have been automatically /// exited. /// /// Additional edge cases this mapping does not cover: /// - If a validator is slashed, their balance exited will reflect their original balance rather than the slashed amount /// - The final partial withdrawal for an exited validator will be likely be included in this mapping. /// i.e. if a validator was last checkpointed at 32.1 ETH before exiting, the next checkpoint will calculate their /// "exited" amount to be 32.1 ETH rather than 32 ETH. function checkpointBalanceExitedGwei(uint64) external view returns (uint64); /// @notice Query the 4788 oracle to get the parent block root of the slot with the given `timestamp` /// @param timestamp of the block for which the parent block root will be returned. MUST correspond /// to an existing slot within the last 24 hours. If the slot at `timestamp` was skipped, this method /// will revert. function getParentBlockRoot(uint64 timestamp) external view returns (bytes32); }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; import "../interfaces/IPauserRegistry.sol"; /** * @title Adds pausability to a contract, with pausing & unpausing controlled by the `pauser` and `unpauser` of a PauserRegistry contract. * @author Layr Labs, Inc. * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service * @notice Contracts that inherit from this contract may define their own `pause` and `unpause` (and/or related) functions. * These functions should be permissioned as "onlyPauser" which defers to a `PauserRegistry` for determining access control. * @dev Pausability is implemented using a uint256, which allows up to 256 different single bit-flags; each bit can potentially pause different functionality. * Inspiration for this was taken from the NearBridge design here https://etherscan.io/address/0x3FEFc5A4B1c02f21cBc8D3613643ba0635b9a873#code. * For the `pause` and `unpause` functions we've implemented, if you pause, you can only flip (any number of) switches to on/1 (aka "paused"), and if you unpause, * you can only flip (any number of) switches to off/0 (aka "paused"). * If you want a pauseXYZ function that just flips a single bit / "pausing flag", it will: * 1) 'bit-wise and' (aka `&`) a flag with the current paused state (as a uint256) * 2) update the paused state to this new value * @dev We note as well that we have chosen to identify flags by their *bit index* as opposed to their numerical value, so, e.g. defining `DEPOSITS_PAUSED = 3` * indicates specifically that if the *third bit* of `_paused` is flipped -- i.e. it is a '1' -- then deposits should be paused */ interface IPausable { /// @notice Emitted when the `pauserRegistry` is set to `newPauserRegistry`. event PauserRegistrySet(IPauserRegistry pauserRegistry, IPauserRegistry newPauserRegistry); /// @notice Emitted when the pause is triggered by `account`, and changed to `newPausedStatus`. event Paused(address indexed account, uint256 newPausedStatus); /// @notice Emitted when the pause is lifted by `account`, and changed to `newPausedStatus`. event Unpaused(address indexed account, uint256 newPausedStatus); /// @notice Address of the `PauserRegistry` contract that this contract defers to for determining access control (for pausing). function pauserRegistry() external view returns (IPauserRegistry); /** * @notice This function is used to pause an EigenLayer contract's functionality. * It is permissioned to the `pauser` address, which is expected to be a low threshold multisig. * @param newPausedStatus represents the new value for `_paused` to take, which means it may flip several bits at once. * @dev This function can only pause functionality, and thus cannot 'unflip' any bit in `_paused` from 1 to 0. */ function pause(uint256 newPausedStatus) external; /** * @notice Alias for `pause(type(uint256).max)`. */ function pauseAll() external; /** * @notice This function is used to unpause an EigenLayer contract's functionality. * It is permissioned to the `unpauser` address, which is expected to be a high threshold multisig or governance contract. * @param newPausedStatus represents the new value for `_paused` to take, which means it may flip several bits at once. * @dev This function can only unpause functionality, and thus cannot 'flip' any bit in `_paused` from 0 to 1. */ function unpause(uint256 newPausedStatus) external; /// @notice Returns the current paused status as a uint256. function paused() external view returns (uint256); /// @notice Returns 'true' if the `indexed`th bit of `_paused` is 1, and 'false' otherwise function paused(uint8 index) external view returns (bool); /// @notice Allows the unpauser to set a new pauser registry function setPauserRegistry(IPauserRegistry newPauserRegistry) external; }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./Merkle.sol"; import "../libraries/Endian.sol"; //Utility library for parsing and PHASE0 beacon chain block headers //SSZ Spec: https://github.com/ethereum/consensus-specs/blob/dev/ssz/simple-serialize.md#merkleization //BeaconBlockHeader Spec: https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#beaconblockheader //BeaconState Spec: https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#beaconstate library BeaconChainProofs { /// @notice Heights of various merkle trees in the beacon chain /// - beaconBlockRoot /// | HEIGHT: BEACON_BLOCK_HEADER_TREE_HEIGHT /// -- beaconStateRoot /// | HEIGHT: BEACON_STATE_TREE_HEIGHT /// validatorContainerRoot, balanceContainerRoot /// | | HEIGHT: BALANCE_TREE_HEIGHT /// | individual balances /// | HEIGHT: VALIDATOR_TREE_HEIGHT /// individual validators uint256 internal constant BEACON_BLOCK_HEADER_TREE_HEIGHT = 3; uint256 internal constant BEACON_STATE_TREE_HEIGHT = 5; uint256 internal constant BALANCE_TREE_HEIGHT = 38; uint256 internal constant VALIDATOR_TREE_HEIGHT = 40; /// @notice Index of the beaconStateRoot in the `BeaconBlockHeader` container /// /// BeaconBlockHeader = [..., state_root, ...] /// 0... 3 /// /// (See https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#beaconblockheader) uint256 internal constant STATE_ROOT_INDEX = 3; /// @notice Indices for fields in the `BeaconState` container /// /// BeaconState = [..., validators, balances, ...] /// 0... 11 12 /// /// (See https://github.com/ethereum/consensus-specs/blob/dev/specs/capella/beacon-chain.md#beaconstate) uint256 internal constant VALIDATOR_CONTAINER_INDEX = 11; uint256 internal constant BALANCE_CONTAINER_INDEX = 12; /// @notice Number of fields in the `Validator` container /// (See https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#validator) uint256 internal constant VALIDATOR_FIELDS_LENGTH = 8; /// @notice Indices for fields in the `Validator` container uint256 internal constant VALIDATOR_PUBKEY_INDEX = 0; uint256 internal constant VALIDATOR_WITHDRAWAL_CREDENTIALS_INDEX = 1; uint256 internal constant VALIDATOR_BALANCE_INDEX = 2; uint256 internal constant VALIDATOR_SLASHED_INDEX = 3; uint256 internal constant VALIDATOR_ACTIVATION_EPOCH_INDEX = 5; uint256 internal constant VALIDATOR_EXIT_EPOCH_INDEX = 6; /// @notice Slot/Epoch timings uint64 internal constant SECONDS_PER_SLOT = 12; uint64 internal constant SLOTS_PER_EPOCH = 32; uint64 internal constant SECONDS_PER_EPOCH = SLOTS_PER_EPOCH * SECONDS_PER_SLOT; /// @notice `FAR_FUTURE_EPOCH` is used as the default value for certain `Validator` /// fields when a `Validator` is first created on the beacon chain uint64 internal constant FAR_FUTURE_EPOCH = type(uint64).max; bytes8 internal constant UINT64_MASK = 0xffffffffffffffff; /// @notice Contains a beacon state root and a merkle proof verifying its inclusion under a beacon block root struct StateRootProof { bytes32 beaconStateRoot; bytes proof; } /// @notice Contains a validator's fields and a merkle proof of their inclusion under a beacon state root struct ValidatorProof { bytes32[] validatorFields; bytes proof; } /// @notice Contains a beacon balance container root and a proof of this root under a beacon block root struct BalanceContainerProof { bytes32 balanceContainerRoot; bytes proof; } /// @notice Contains a validator balance root and a proof of its inclusion under a balance container root struct BalanceProof { bytes32 pubkeyHash; bytes32 balanceRoot; bytes proof; } /** * * VALIDATOR FIELDS -> BEACON STATE ROOT -> BEACON BLOCK ROOT * */ /// @notice Verify a merkle proof of the beacon state root against a beacon block root /// @param beaconBlockRoot merkle root of the beacon block /// @param proof the beacon state root and merkle proof of its inclusion under `beaconBlockRoot` function verifyStateRoot(bytes32 beaconBlockRoot, StateRootProof calldata proof) internal view { require( proof.proof.length == 32 * (BEACON_BLOCK_HEADER_TREE_HEIGHT), "BeaconChainProofs.verifyStateRoot: Proof has incorrect length" ); /// This merkle proof verifies the `beaconStateRoot` under the `beaconBlockRoot` /// - beaconBlockRoot /// | HEIGHT: BEACON_BLOCK_HEADER_TREE_HEIGHT /// -- beaconStateRoot require( Merkle.verifyInclusionSha256({ proof: proof.proof, root: beaconBlockRoot, leaf: proof.beaconStateRoot, index: STATE_ROOT_INDEX }), "BeaconChainProofs.verifyStateRoot: Invalid state root merkle proof" ); } /// @notice Verify a merkle proof of a validator container against a `beaconStateRoot` /// @dev This proof starts at a validator's container root, proves through the validator container root, /// and continues proving to the root of the `BeaconState` /// @dev See https://eth2book.info/capella/part3/containers/dependencies/#validator for info on `Validator` containers /// @dev See https://eth2book.info/capella/part3/containers/state/#beaconstate for info on `BeaconState` containers /// @param beaconStateRoot merkle root of the `BeaconState` container /// @param validatorFields an individual validator's fields. These are merklized to form a `validatorRoot`, /// which is used as the leaf to prove against `beaconStateRoot` /// @param validatorFieldsProof a merkle proof of inclusion of `validatorFields` under `beaconStateRoot` /// @param validatorIndex the validator's unique index function verifyValidatorFields( bytes32 beaconStateRoot, bytes32[] calldata validatorFields, bytes calldata validatorFieldsProof, uint40 validatorIndex ) internal view { require( validatorFields.length == VALIDATOR_FIELDS_LENGTH, "BeaconChainProofs.verifyValidatorFields: Validator fields has incorrect length" ); /// Note: the reason we use `VALIDATOR_TREE_HEIGHT + 1` here is because the merklization process for /// this container includes hashing the root of the validator tree with the length of the validator list require( validatorFieldsProof.length == 32 * ((VALIDATOR_TREE_HEIGHT + 1) + BEACON_STATE_TREE_HEIGHT), "BeaconChainProofs.verifyValidatorFields: Proof has incorrect length" ); // Merkleize `validatorFields` to get the leaf to prove bytes32 validatorRoot = Merkle.merkleizeSha256(validatorFields); /// This proof combines two proofs, so its index accounts for the relative position of leaves in two trees: /// - beaconStateRoot /// | HEIGHT: BEACON_STATE_TREE_HEIGHT /// -- validatorContainerRoot /// | HEIGHT: VALIDATOR_TREE_HEIGHT + 1 /// ---- validatorRoot uint256 index = (VALIDATOR_CONTAINER_INDEX << (VALIDATOR_TREE_HEIGHT + 1)) | uint256(validatorIndex); require( Merkle.verifyInclusionSha256({ proof: validatorFieldsProof, root: beaconStateRoot, leaf: validatorRoot, index: index }), "BeaconChainProofs.verifyValidatorFields: Invalid merkle proof" ); } /** * * VALIDATOR BALANCE -> BALANCE CONTAINER ROOT -> BEACON BLOCK ROOT * */ /// @notice Verify a merkle proof of the beacon state's balances container against the beacon block root /// @dev This proof starts at the balance container root, proves through the beacon state root, and /// continues proving through the beacon block root. As a result, this proof will contain elements /// of a `StateRootProof` under the same block root, with the addition of proving the balances field /// within the beacon state. /// @dev This is used to make checkpoint proofs more efficient, as a checkpoint will verify multiple balances /// against the same balance container root. /// @param beaconBlockRoot merkle root of the beacon block /// @param proof a beacon balance container root and merkle proof of its inclusion under `beaconBlockRoot` function verifyBalanceContainer(bytes32 beaconBlockRoot, BalanceContainerProof calldata proof) internal view { require( proof.proof.length == 32 * (BEACON_BLOCK_HEADER_TREE_HEIGHT + BEACON_STATE_TREE_HEIGHT), "BeaconChainProofs.verifyBalanceContainer: Proof has incorrect length" ); /// This proof combines two proofs, so its index accounts for the relative position of leaves in two trees: /// - beaconBlockRoot /// | HEIGHT: BEACON_BLOCK_HEADER_TREE_HEIGHT /// -- beaconStateRoot /// | HEIGHT: BEACON_STATE_TREE_HEIGHT /// ---- balancesContainerRoot uint256 index = (STATE_ROOT_INDEX << (BEACON_STATE_TREE_HEIGHT)) | BALANCE_CONTAINER_INDEX; require( Merkle.verifyInclusionSha256({ proof: proof.proof, root: beaconBlockRoot, leaf: proof.balanceContainerRoot, index: index }), "BeaconChainProofs.verifyBalanceContainer: invalid balance container proof" ); } /// @notice Verify a merkle proof of a validator's balance against the beacon state's `balanceContainerRoot` /// @param balanceContainerRoot the merkle root of all validators' current balances /// @param validatorIndex the index of the validator whose balance we are proving /// @param proof the validator's associated balance root and a merkle proof of inclusion under `balanceContainerRoot` /// @return validatorBalanceGwei the validator's current balance (in gwei) function verifyValidatorBalance( bytes32 balanceContainerRoot, uint40 validatorIndex, BalanceProof calldata proof ) internal view returns (uint64 validatorBalanceGwei) { /// Note: the reason we use `BALANCE_TREE_HEIGHT + 1` here is because the merklization process for /// this container includes hashing the root of the balances tree with the length of the balances list require( proof.proof.length == 32 * (BALANCE_TREE_HEIGHT + 1), "BeaconChainProofs.verifyValidatorBalance: Proof has incorrect length" ); /// When merkleized, beacon chain balances are combined into groups of 4 called a `balanceRoot`. The merkle /// proof here verifies that this validator's `balanceRoot` is included in the `balanceContainerRoot` /// - balanceContainerRoot /// | HEIGHT: BALANCE_TREE_HEIGHT /// -- balanceRoot uint256 balanceIndex = uint256(validatorIndex / 4); require( Merkle.verifyInclusionSha256({ proof: proof.proof, root: balanceContainerRoot, leaf: proof.balanceRoot, index: balanceIndex }), "BeaconChainProofs.verifyValidatorBalance: Invalid merkle proof" ); /// Extract the individual validator's balance from the `balanceRoot` return getBalanceAtIndex(proof.balanceRoot, validatorIndex); } /** * @notice Parses a balanceRoot to get the uint64 balance of a validator. * @dev During merkleization of the beacon state balance tree, four uint64 values are treated as a single * leaf in the merkle tree. We use validatorIndex % 4 to determine which of the four uint64 values to * extract from the balanceRoot. * @param balanceRoot is the combination of 4 validator balances being proven for * @param validatorIndex is the index of the validator being proven for * @return The validator's balance, in Gwei */ function getBalanceAtIndex(bytes32 balanceRoot, uint40 validatorIndex) internal pure returns (uint64) { uint256 bitShiftAmount = (validatorIndex % 4) * 64; return Endian.fromLittleEndianUint64(bytes32((uint256(balanceRoot) << bitShiftAmount))); } /// @notice Indices for fields in the `Validator` container: /// 0: pubkey /// 1: withdrawal credentials /// 2: effective balance /// 3: slashed? /// 4: activation eligibility epoch /// 5: activation epoch /// 6: exit epoch /// 7: withdrawable epoch /// /// (See https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#validator) /// @dev Retrieves a validator's pubkey hash function getPubkeyHash(bytes32[] memory validatorFields) internal pure returns (bytes32) { return validatorFields[VALIDATOR_PUBKEY_INDEX]; } /// @dev Retrieves a validator's withdrawal credentials function getWithdrawalCredentials(bytes32[] memory validatorFields) internal pure returns (bytes32) { return validatorFields[VALIDATOR_WITHDRAWAL_CREDENTIALS_INDEX]; } /// @dev Retrieves a validator's effective balance (in gwei) function getEffectiveBalanceGwei(bytes32[] memory validatorFields) internal pure returns (uint64) { return Endian.fromLittleEndianUint64(validatorFields[VALIDATOR_BALANCE_INDEX]); } /// @dev Retrieves a validator's activation epoch function getActivationEpoch(bytes32[] memory validatorFields) internal pure returns (uint64) { return Endian.fromLittleEndianUint64(validatorFields[VALIDATOR_ACTIVATION_EPOCH_INDEX]); } /// @dev Retrieves true IFF a validator is marked slashed function isValidatorSlashed(bytes32[] memory validatorFields) internal pure returns (bool) { return validatorFields[VALIDATOR_SLASHED_INDEX] != 0; } /// @dev Retrieves a validator's exit epoch function getExitEpoch(bytes32[] memory validatorFields) internal pure returns (uint64) { return Endian.fromLittleEndianUint64(validatorFields[VALIDATOR_EXIT_EPOCH_INDEX]); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.20; import {IERC20} from "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC-20 standard. */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "../token/ERC20/IERC20.sol";
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol) pragma solidity ^0.8.20; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } function _contextSuffixLength() internal view virtual returns (uint256) { return 0; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol) pragma solidity ^0.8.20; /** * @dev Standard ERC-20 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens. */ interface IERC20Errors { /** * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. * @param balance Current balance for the interacting account. * @param needed Minimum amount required to perform a transfer. */ error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC20InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC20InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers. * @param spender Address that may be allowed to operate on tokens without being their owner. * @param allowance Amount of tokens a `spender` is allowed to operate with. * @param needed Minimum amount required to perform a transfer. */ error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC20InvalidApprover(address approver); /** * @dev Indicates a failure with the `spender` to be approved. Used in approvals. * @param spender Address that may be allowed to operate on tokens without being their owner. */ error ERC20InvalidSpender(address spender); } /** * @dev Standard ERC-721 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens. */ interface IERC721Errors { /** * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20. * Used in balance queries. * @param owner Address of the current owner of a token. */ error ERC721InvalidOwner(address owner); /** * @dev Indicates a `tokenId` whose `owner` is the zero address. * @param tokenId Identifier number of a token. */ error ERC721NonexistentToken(uint256 tokenId); /** * @dev Indicates an error related to the ownership over a particular token. Used in transfers. * @param sender Address whose tokens are being transferred. * @param tokenId Identifier number of a token. * @param owner Address of the current owner of a token. */ error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC721InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC721InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `operator`’s approval. Used in transfers. * @param operator Address that may be allowed to operate on tokens without being their owner. * @param tokenId Identifier number of a token. */ error ERC721InsufficientApproval(address operator, uint256 tokenId); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC721InvalidApprover(address approver); /** * @dev Indicates a failure with the `operator` to be approved. Used in approvals. * @param operator Address that may be allowed to operate on tokens without being their owner. */ error ERC721InvalidOperator(address operator); } /** * @dev Standard ERC-1155 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens. */ interface IERC1155Errors { /** * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. * @param balance Current balance for the interacting account. * @param needed Minimum amount required to perform a transfer. * @param tokenId Identifier number of a token. */ error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC1155InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC1155InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `operator`’s approval. Used in transfers. * @param operator Address that may be allowed to operate on tokens without being their owner. * @param owner Address of the current owner of a token. */ error ERC1155MissingApprovalForAll(address operator, address owner); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC1155InvalidApprover(address approver); /** * @dev Indicates a failure with the `operator` to be approved. Used in approvals. * @param operator Address that may be allowed to operate on tokens without being their owner. */ error ERC1155InvalidOperator(address operator); /** * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation. * Used in batch transfers. * @param idsLength Length of the array of token identifiers * @param valuesLength Length of the array of token amounts */ error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.20; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ```solidity * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Storage of the initializable contract. * * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions * when using with upgradeable contracts. * * @custom:storage-location erc7201:openzeppelin.storage.Initializable */ struct InitializableStorage { /** * @dev Indicates that the contract has been initialized. */ uint64 _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool _initializing; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00; /** * @dev The contract is already initialized. */ error InvalidInitialization(); /** * @dev The contract is not initializing. */ error NotInitializing(); /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint64 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. * * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in * production. * * Emits an {Initialized} event. */ modifier initializer() { // solhint-disable-next-line var-name-mixedcase InitializableStorage storage $ = _getInitializableStorage(); // Cache values to avoid duplicated sloads bool isTopLevelCall = !$._initializing; uint64 initialized = $._initialized; // Allowed calls: // - initialSetup: the contract is not in the initializing state and no previous version was // initialized // - construction: the contract is initialized at version 1 (no reininitialization) and the // current contract is just being deployed bool initialSetup = initialized == 0 && isTopLevelCall; bool construction = initialized == 1 && address(this).code.length == 0; if (!initialSetup && !construction) { revert InvalidInitialization(); } $._initialized = 1; if (isTopLevelCall) { $._initializing = true; } _; if (isTopLevelCall) { $._initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * A reinitializer may be used after the original initialization step. This is essential to configure modules that * are added through upgrades and that require initialization. * * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer` * cannot be nested. If one is invoked in the context of another, execution will revert. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. * * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization. * * Emits an {Initialized} event. */ modifier reinitializer(uint64 version) { // solhint-disable-next-line var-name-mixedcase InitializableStorage storage $ = _getInitializableStorage(); if ($._initializing || $._initialized >= version) { revert InvalidInitialization(); } $._initialized = version; $._initializing = true; _; $._initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { _checkInitializing(); _; } /** * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}. */ function _checkInitializing() internal view virtual { if (!_isInitializing()) { revert NotInitializing(); } } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. * * Emits an {Initialized} event the first time it is successfully executed. */ function _disableInitializers() internal virtual { // solhint-disable-next-line var-name-mixedcase InitializableStorage storage $ = _getInitializableStorage(); if ($._initializing) { revert InvalidInitialization(); } if ($._initialized != type(uint64).max) { $._initialized = type(uint64).max; emit Initialized(type(uint64).max); } } /** * @dev Returns the highest version that has been initialized. See {reinitializer}. */ function _getInitializedVersion() internal view returns (uint64) { return _getInitializableStorage()._initialized; } /** * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}. */ function _isInitializing() internal view returns (bool) { return _getInitializableStorage()._initializing; } /** * @dev Returns a pointer to the storage namespace. */ // solhint-disable-next-line var-name-mixedcase function _getInitializableStorage() private pure returns (InitializableStorage storage $) { assembly { $.slot := INITIALIZABLE_STORAGE } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol) pragma solidity ^0.8.20; /** * @dev External interface of AccessControl declared to support ERC-165 detection. */ interface IAccessControl { /** * @dev The `account` is missing a role. */ error AccessControlUnauthorizedAccount(address account, bytes32 neededRole); /** * @dev The caller of a function is not the expected one. * * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}. */ error AccessControlBadConfirmation(); /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role). * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `callerConfirmation`. */ function renounceRole(bytes32 role, address callerConfirmation) external; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol) pragma solidity ^0.8.20; import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import {Initializable} from "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` */ abstract contract ERC165Upgradeable is Initializable, IERC165 { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { return interfaceId == type(IERC165).interfaceId; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol) pragma solidity ^0.8.20; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } function _contextSuffixLength() internal view virtual returns (uint256) { return 0; } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; /** * @title Interface for the `PauserRegistry` contract. * @author Layr Labs, Inc. * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service */ interface IPauserRegistry { event PauserStatusChanged(address pauser, bool canPause); event UnpauserChanged(address previousUnpauser, address newUnpauser); /// @notice Mapping of addresses to whether they hold the pauser role. function isPauser(address pauser) external view returns (bool); /// @notice Unique address that holds the unpauser role. Capable of changing *both* the pauser and unpauser addresses. function unpauser() external view returns (address); }
// SPDX-License-Identifier: MIT // Adapted from OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Tree proofs. * * The tree and the proofs can be generated using our * https://github.com/OpenZeppelin/merkle-tree[JavaScript library]. * You will find a quickstart guide in the readme. * * WARNING: You should avoid using leaf values that are 64 bytes long prior to * hashing, or use a hash function other than keccak256 for hashing leaves. * This is because the concatenation of a sorted pair of internal nodes in * the merkle tree could be reinterpreted as a leaf value. * OpenZeppelin's JavaScript library generates merkle trees that are safe * against this attack out of the box. */ library Merkle { /** * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. The tree is built assuming `leaf` is * the 0 indexed `index`'th leaf from the bottom left of the tree. * * Note this is for a Merkle tree using the keccak/sha3 hash function */ function verifyInclusionKeccak( bytes memory proof, bytes32 root, bytes32 leaf, uint256 index ) internal pure returns (bool) { return processInclusionProofKeccak(proof, leaf, index) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. The tree is built assuming `leaf` is * the 0 indexed `index`'th leaf from the bottom left of the tree. * @dev If the proof length is 0 then the leaf hash is returned. * * _Available since v4.4._ * * Note this is for a Merkle tree using the keccak/sha3 hash function */ function processInclusionProofKeccak( bytes memory proof, bytes32 leaf, uint256 index ) internal pure returns (bytes32) { require(proof.length % 32 == 0, "Merkle.processInclusionProofKeccak: proof length should be a multiple of 32"); bytes32 computedHash = leaf; for (uint256 i = 32; i <= proof.length; i += 32) { if (index % 2 == 0) { // if ith bit of index is 0, then computedHash is a left sibling assembly { mstore(0x00, computedHash) mstore(0x20, mload(add(proof, i))) computedHash := keccak256(0x00, 0x40) index := div(index, 2) } } else { // if ith bit of index is 1, then computedHash is a right sibling assembly { mstore(0x00, mload(add(proof, i))) mstore(0x20, computedHash) computedHash := keccak256(0x00, 0x40) index := div(index, 2) } } } return computedHash; } /** * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. The tree is built assuming `leaf` is * the 0 indexed `index`'th leaf from the bottom left of the tree. * * Note this is for a Merkle tree using the sha256 hash function */ function verifyInclusionSha256( bytes memory proof, bytes32 root, bytes32 leaf, uint256 index ) internal view returns (bool) { return processInclusionProofSha256(proof, leaf, index) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. The tree is built assuming `leaf` is * the 0 indexed `index`'th leaf from the bottom left of the tree. * * _Available since v4.4._ * * Note this is for a Merkle tree using the sha256 hash function */ function processInclusionProofSha256( bytes memory proof, bytes32 leaf, uint256 index ) internal view returns (bytes32) { require( proof.length != 0 && proof.length % 32 == 0, "Merkle.processInclusionProofSha256: proof length should be a non-zero multiple of 32" ); bytes32[1] memory computedHash = [leaf]; for (uint256 i = 32; i <= proof.length; i += 32) { if (index % 2 == 0) { // if ith bit of index is 0, then computedHash is a left sibling assembly { mstore(0x00, mload(computedHash)) mstore(0x20, mload(add(proof, i))) if iszero(staticcall(sub(gas(), 2000), 2, 0x00, 0x40, computedHash, 0x20)) { revert(0, 0) } index := div(index, 2) } } else { // if ith bit of index is 1, then computedHash is a right sibling assembly { mstore(0x00, mload(add(proof, i))) mstore(0x20, mload(computedHash)) if iszero(staticcall(sub(gas(), 2000), 2, 0x00, 0x40, computedHash, 0x20)) { revert(0, 0) } index := div(index, 2) } } } return computedHash[0]; } /** * @notice this function returns the merkle root of a tree created from a set of leaves using sha256 as its hash function * @param leaves the leaves of the merkle tree * @return The computed Merkle root of the tree. * @dev A pre-condition to this function is that leaves.length is a power of two. If not, the function will merkleize the inputs incorrectly. */ function merkleizeSha256(bytes32[] memory leaves) internal pure returns (bytes32) { //there are half as many nodes in the layer above the leaves uint256 numNodesInLayer = leaves.length / 2; //create a layer to store the internal nodes bytes32[] memory layer = new bytes32[](numNodesInLayer); //fill the layer with the pairwise hashes of the leaves for (uint256 i = 0; i < numNodesInLayer; i++) { layer[i] = sha256(abi.encodePacked(leaves[2 * i], leaves[2 * i + 1])); } //the next layer above has half as many nodes numNodesInLayer /= 2; //while we haven't computed the root while (numNodesInLayer != 0) { //overwrite the first numNodesInLayer nodes in layer with the pairwise hashes of their children for (uint256 i = 0; i < numNodesInLayer; i++) { layer[i] = sha256(abi.encodePacked(layer[2 * i], layer[2 * i + 1])); } //the next layer above has half as many nodes numNodesInLayer /= 2; } //the first node in the layer is the root return layer[0]; } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library Endian { /** * @notice Converts a little endian-formatted uint64 to a big endian-formatted uint64 * @param lenum little endian-formatted uint64 input, provided as 'bytes32' type * @return n The big endian-formatted uint64 * @dev Note that the input is formatted as a 'bytes32' type (i.e. 256 bits), but it is immediately truncated to a uint64 (i.e. 64 bits) * through a right-shift/shr operation. */ function fromLittleEndianUint64(bytes32 lenum) internal pure returns (uint64 n) { // the number needs to be stored in little-endian encoding (ie in bytes 0-8) n = uint64(uint256(lenum >> 192)); // forgefmt: disable-next-item return (n >> 56) | ((0x00FF000000000000 & n) >> 40) | ((0x0000FF0000000000 & n) >> 24) | ((0x000000FF00000000 & n) >> 8) | ((0x00000000FF000000 & n) << 8) | ((0x0000000000FF0000 & n) << 24) | ((0x000000000000FF00 & n) << 40) | ((0x00000000000000FF & n) << 56); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC-165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[ERC]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
{ "remappings": [ "@openzeppelin-upgrades/=lib/eigenlayer-contracts/lib/openzeppelin-contracts-upgradeable/", "@openzeppelin/=lib/openzeppelin-contracts/", "@eigenlayer/=lib/eigenlayer-contracts/", "@openzeppelin-upgrades-v4.9.0/=lib/eigenlayer-contracts/lib/openzeppelin-contracts-upgradeable-v4.9.0/", "@openzeppelin-v4.9.0/=lib/eigenlayer-contracts/lib/openzeppelin-contracts-v4.9.0/", "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/", "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/", "ds-test/=lib/forge-std/lib/ds-test/src/", "eigenlayer-contracts/=lib/eigenlayer-contracts/", "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/", "forge-std/=lib/forge-std/src/", "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/", "openzeppelin-contracts-upgradeable-v4.9.0/=lib/eigenlayer-contracts/lib/openzeppelin-contracts-upgradeable-v4.9.0/", "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/", "openzeppelin-contracts-v4.9.0/=lib/eigenlayer-contracts/lib/openzeppelin-contracts-v4.9.0/", "openzeppelin-contracts/=lib/openzeppelin-contracts/", "openzeppelin/=lib/eigenlayer-contracts/lib/openzeppelin-contracts-upgradeable-v4.9.0/contracts/", "safe-smart-account/=lib/safe-smart-account/" ], "optimizer": { "enabled": true, "runs": 200 }, "metadata": { "useLiteralContent": false, "bytecodeHash": "ipfs", "appendCBOR": true }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "cancun", "viaIR": false, "libraries": {} }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AccessControlBadConfirmation","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bytes32","name":"neededRole","type":"bytes32"}],"name":"AccessControlUnauthorizedAccount","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerNotAuthorized","type":"error"},{"inputs":[{"internalType":"address","name":"expected","type":"address"},{"internalType":"address","name":"provided","type":"address"}],"name":"CallerNotStakingNodeManager","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"allowance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientAllowance","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientBalance","type":"error"},{"inputs":[{"internalType":"address","name":"approver","type":"address"}],"name":"ERC20InvalidApprover","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"ERC20InvalidReceiver","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"ERC20InvalidSender","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"}],"name":"ERC20InvalidSpender","type":"error"},{"inputs":[],"name":"InsufficientBalance","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"NoDirectETHDeposit","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"NotRewardsDistributor","type":"error"},{"inputs":[],"name":"Paused","type":"error"},{"inputs":[],"name":"TransferFailed","type":"error"},{"inputs":[],"name":"TransfersPaused","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"inputs":[],"name":"ZeroETH","type":"error"},{"inputs":[],"name":"ZeroShares","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalDepositedInPool","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"isPaused","type":"bool"}],"name":"DepositETHPausedUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"ethAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalDepositedInPool","type":"uint256"}],"name":"ETHWithdrawn","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"bool","name":"isWhitelisted","type":"bool"}],"name":"PauseWhitelistUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalDepositedInPool","type":"uint256"}],"name":"RewardsReceived","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[],"name":"TransfersUnpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"ethAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalDepositedInPool","type":"uint256"}],"name":"WithdrawnETHProcessed","type":"event"},{"inputs":[],"name":"BURNER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PAUSER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"UNPAUSER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"whitelistedForTransfers","type":"address[]"}],"name":"addToPauseWhitelist","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"convertToAssets","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"convertToShares","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"depositETH","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"depositsPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"admin","type":"address"},{"internalType":"address","name":"pauser","type":"address"},{"internalType":"address","name":"unpauser","type":"address"},{"internalType":"contract IStakingNodesManager","name":"stakingNodesManager","type":"address"},{"internalType":"contract IRewardsDistributor","name":"rewardsDistributor","type":"address"},{"internalType":"address[]","name":"pauseWhitelist","type":"address[]"}],"internalType":"struct ynETH.Init","name":"init","type":"tuple"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pauseDeposits","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"addr","type":"address"}],"name":"pauseWhiteList","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"previewDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"previewRedeem","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"processWithdrawnETH","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"receiveRewards","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address[]","name":"unlisted","type":"address[]"}],"name":"removeFromPauseWhitelist","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"callerConfirmation","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"rewardsDistributor","outputs":[{"internalType":"contract IRewardsDistributor","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"stakingNodesManager","outputs":[{"internalType":"contract IStakingNodesManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalDepositedInPool","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unpauseDeposits","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unpauseTransfers","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"ethAmount","type":"uint256"}],"name":"withdrawETH","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]
Contract Creation Code
608060405234801561000f575f80fd5b5061001861001d565b6100cf565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00805468010000000000000000900460ff161561006d5760405163f92ee8a960e01b815260040160405180910390fd5b80546001600160401b03908116146100cc5780546001600160401b0319166001600160401b0390811782556040519081527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50565b6121a880620000dd5f395ff3fe608060405260043610610236575f3560e01c806361fd0ae111610129578063a9059cbb116100a8578063e63ab1e91161006d578063e63ab1e91461068e578063e7b0504b146106c1578063ef8b30f714610631578063f14210a6146106d6578063fb1bb9de146106f5575f80fd5b8063a9059cbb146105f3578063b7b199c714610612578063c6e6f59214610631578063d547741f14610650578063dd62ed3e1461066f575f80fd5b80638ffbf6db116100ee5780638ffbf6db1461054b57806391d148541461056a57806395d89b4114610589578063a1a25e6e1461059d578063a217fddf146105e0575f80fd5b806361fd0ae1146104bc578063631cbe3c146104db57806363d8882a146104e357806370a08231146104f75780638936a91f14610537575f80fd5b8063282c51f3116101b55780633f2a55401161017a5780633f2a55401461042857806342966c681461045f578063443dc4281461047e5780634cdad506146102e557806360da3e831461049c575f80fd5b8063282c51f3146103895780632d2da806146103bc5780632f2ff15d146103cf578063313ce567146103ee57806336568abe14610409575f80fd5b8063095ea7b3116101fb578063095ea7b31461030457806318160ddd146103235780631ef2aac51461034357806323b872dd1461034b578063248a9ca31461036a575f80fd5b806301e1d1141461025857806301ffc9a71461027f57806302191980146102ae57806306fdde03146102c457806307a2d13a146102e5575f80fd5b3661025457604051636c897afd60e01b815260040160405180910390fd5b5f80fd5b348015610263575f80fd5b5061026c610715565b6040519081526020015b60405180910390f35b34801561028a575f80fd5b5061029e610299366004611b60565b610740565b6040519015158152602001610276565b3480156102b9575f80fd5b506102c2610774565b005b3480156102cf575f80fd5b506102d86107f8565b6040516102769190611b87565b3480156102f0575f80fd5b5061026c6102ff366004611bd3565b6108b8565b34801561030f575f80fd5b5061029e61031e366004611bfe565b6108c3565b34801561032e575f80fd5b505f805160206121138339815191525461026c565b6102c26108da565b348015610356575f80fd5b5061029e610365366004611c28565b6109ef565b348015610375575f80fd5b5061026c610384366004611bd3565b610a14565b348015610394575f80fd5b5061026c7f3c11d16cbaffd01df69ce1c404f6340ee057498f5f00246190ea54220576a84881565b61026c6103ca366004611c66565b610a34565b3480156103da575f80fd5b506102c26103e9366004611c81565b610b23565b3480156103f9575f80fd5b5060405160128152602001610276565b348015610414575f80fd5b506102c2610423366004611c81565b610b45565b348015610433575f80fd5b50600154610447906001600160a01b031681565b6040516001600160a01b039091168152602001610276565b34801561046a575f80fd5b506102c2610479366004611bd3565b610b7d565b348015610489575f80fd5b505f54610447906001600160a01b031681565b3480156104a7575f80fd5b5060015461029e90600160a01b900460ff1681565b3480156104c7575f80fd5b506102c26104d6366004611d90565b610bb5565b6102c2610bd6565b3480156104ee575f80fd5b506102c2610c53565b348015610502575f80fd5b5061026c610511366004611c66565b6001600160a01b03165f9081525f805160206120f3833981519152602052604090205490565b348015610542575f80fd5b506102c2610cb7565b348015610556575f80fd5b506102c2610565366004611d90565b610d32565b348015610575575f80fd5b5061029e610584366004611c81565b610d54565b348015610594575f80fd5b506102d8610d8a565b3480156105a8575f80fd5b5061029e6105b7366004611c66565b6001600160a01b03165f9081525f805160206120d3833981519152602052604090205460ff1690565b3480156105eb575f80fd5b5061026c5f81565b3480156105fe575f80fd5b5061029e61060d366004611bfe565b610dc8565b34801561061d575f80fd5b506102c261062c366004611dd2565b610dd5565b34801561063c575f80fd5b5061026c61064b366004611bd3565b6110cd565b34801561065b575f80fd5b506102c261066a366004611c81565b6110d8565b34801561067a575f80fd5b5061026c610689366004611e95565b6110f4565b348015610699575f80fd5b5061026c7f65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a81565b3480156106cc575f80fd5b5061026c60025481565b3480156106e1575f80fd5b506102c26106f0366004611bd3565b61113d565b348015610700575f80fd5b5061026c5f8051602061213383398151915281565b6002545f9081906107269082611ed5565b9050610730611264565b61073a9082611ed5565b92915050565b5f6001600160e01b03198216637965db0b60e01b148061073a57506301ffc9a760e01b6001600160e01b031983161461073a565b7f65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a61079e816112dd565b6001805460ff60a01b1916600160a01b908117918290556040517f35e03641f0c63f166bca10b4ee931a3c02be26ffb29a395ce012099d99ecb6cc926107ed92900460ff161515815260200190565b60405180910390a150565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0380546060915f805160206120f38339815191529161083690611ee8565b80601f016020809104026020016040519081016040528092919081815260200182805461086290611ee8565b80156108ad5780601f10610884576101008083540402835291602001916108ad565b820191905f5260205f20905b81548152906001019060200180831161089057829003601f168201915b505050505091505090565b5f61073a825f6112ea565b5f336108d081858561132e565b5060019392505050565b5f546001600160a01b031633148061097557505f8054906101000a90046001600160a01b03166001600160a01b0316637d1f8a816040518163ffffffff1660e01b81526004016020604051808303815f875af115801561093c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109609190611f20565b6001600160a01b0316336001600160a01b0316145b61099957604051631bb2e8ef60e21b81523360048201526024015b60405180910390fd5b3460025f8282546109aa9190611ed5565b90915550506002546040805134815260208101929092527f7be0d7fd798145f666ec52ac3f0d58a38be2081e9debf17f96e11c21c848ea2791015b60405180910390a1565b5f336109fc85828561133b565b610a07858585611398565b60019150505b9392505050565b5f9081525f80516020612153833981519152602052604090206001015490565b6001545f90600160a01b900460ff1615610a61576040516313d0ff5960e31b815260040160405180910390fd5b345f03610a81576040516335ed7e5760e11b815260040160405180910390fd5b34610a8b816110cd565b9150815f03610aad57604051639811e0c760e01b815260040160405180910390fd5b610ab783836113f5565b8060025f828254610ac89190611ed5565b9091555050600254604080518381526020810185905280820192909252516001600160a01b0385169133917f4e2ca0515ed1aef1395f66b5303bb5d6f1bf9d61a353fa53f73f8ac9973fa9f69181900360600190a350919050565b610b2c82610a14565b610b35816112dd565b610b3f8383611429565b50505050565b6001600160a01b0381163314610b6e5760405163334bd91960e11b815260040160405180910390fd5b610b7882826114ca565b505050565b7f3c11d16cbaffd01df69ce1c404f6340ee057498f5f00246190ea54220576a848610ba7816112dd565b610bb13383611543565b5050565b5f80516020612133833981519152610bcc816112dd565b610bb1825f611577565b6001546001600160a01b03163314610c035760405163df6752fd60e01b8152336004820152602401610990565b3460025f828254610c149190611ed5565b90915550506002546040805134815260208101929092527f61cb44cbea389abb97c617c7d16a62235c51f27da3406d3ec3c9ac87c0d0c82691016109e5565b5f80516020612133833981519152610c6a816112dd565b6001805460ff60a01b1916908190556040517f35e03641f0c63f166bca10b4ee931a3c02be26ffb29a395ce012099d99ecb6cc916107ed91600160a01b90910460ff161515815260200190565b5f80516020612133833981519152610cce816112dd565b7f7e7ba5b20f89141f0255e9704ce6ce6e55f5f28e4fc0d626fc76bedba3053201805460ff191690556040515f805160206120d3833981519152907f5b1b646968864ea75fad546d8c819e0de710df0bf61f658f6ba54dc587472e7b905f90a15050565b5f80516020612133833981519152610d49816112dd565b610bb1826001611577565b5f9182525f80516020612153833981519152602090815260408084206001600160a01b0393909316845291905290205460ff1690565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0480546060915f805160206120f38339815191529161083690611ee8565b5f336108d0818585611398565b80516001600160a01b038116610dfe5760405163d92e233d60e01b815260040160405180910390fd5b60208201516001600160a01b038116610e2a5760405163d92e233d60e01b815260040160405180910390fd5b60408301516001600160a01b038116610e565760405163d92e233d60e01b815260040160405180910390fd5b60608401516001600160a01b038116610e825760405163d92e233d60e01b815260040160405180910390fd5b60808501516001600160a01b038116610eae5760405163d92e233d60e01b815260040160405180910390fd5b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff16159067ffffffffffffffff165f81158015610ef35750825b90505f8267ffffffffffffffff166001148015610f0f5750303b155b905081158015610f1d575080155b15610f3b5760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff191660011785558315610f6557845460ff60401b1916600160401b1785555b610f6d611612565b610fb1604051806040016040528060058152602001640f2dc8aa8960db1b815250604051806040016040528060058152602001640f2dc8aa8960db1b81525061161c565b8a51610fbe905f90611429565b50610fed7f65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a8c60200151611429565b506110095f805160206121338339815191528c60400151611429565b5060608b01515f80546001600160a01b039283166001600160a01b03199182161790915560808d0151600180549190931691161781557f7e7ba5b20f89141f0255e9704ce6ce6e55f5f28e4fc0d626fc76bedba3053201805460ff1916909117905561107a8b60a001516001611577565b83156110c057845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b5050505050505050505050565b5f61073a825f61162e565b6110e182610a14565b6110ea816112dd565b610b3f83836114ca565b6001600160a01b039182165f9081527f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace016020908152604080832093909416825291909152205490565b5f546001600160a01b0316331461117b575f5460405163d95eb40f60e01b81526001600160a01b039091166004820152336024820152604401610990565b6002548181101561119f57604051631e9acf1760e31b815260040160405180910390fd5b5f6111aa8383611f3b565b60028190555f805460405192935090916001600160a01b039091169085908381818185875af1925050503d805f81146111fe576040519150601f19603f3d011682016040523d82523d5f602084013e611203565b606091505b5050905080611225576040516312171d8360e31b815260040160405180910390fd5b60408051858152602081018490527f72e1ec2b6bc1315b9dd8b8a5704a77cbac7378d6e44866f92d6985f0793dc4c2910160405180910390a150505050565b5f805f9054906101000a90046001600160a01b03166001600160a01b031663ff50abdc6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156112b4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112d89190611f4e565b905090565b6112e78133611678565b50565b5f806113015f805160206121138339815191525490565b9050805f03611313578391505061073a565b6113268461131f610715565b83866116b1565b949350505050565b610b7883838360016116fc565b5f61134684846110f4565b90505f198114610b3f578181101561138a57604051637dc7a0d960e11b81526001600160a01b03841660048201526024810182905260448101839052606401610990565b610b3f84848484035f6116fc565b6001600160a01b0383166113c157604051634b637e8f60e11b81525f6004820152602401610990565b6001600160a01b0382166113ea5760405163ec442f0560e01b81525f6004820152602401610990565b610b788383836117e0565b6001600160a01b03821661141e5760405163ec442f0560e01b81525f6004820152602401610990565b610bb15f83836117e0565b5f5f805160206121538339815191526114428484610d54565b6114c1575f848152602082815260408083206001600160a01b03871684529091529020805460ff191660011790556114773390565b6001600160a01b0316836001600160a01b0316857f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a4600191505061073a565b5f91505061073a565b5f5f805160206121538339815191526114e38484610d54565b156114c1575f848152602082815260408083206001600160a01b0387168085529252808320805460ff1916905551339287917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a4600191505061073a565b6001600160a01b03821661156c57604051634b637e8f60e11b81525f6004820152602401610990565b610bb1825f836117e0565b5f805160206120d38339815191525f5b8351811015610b3f575f8482815181106115a3576115a3611f65565b6020908102919091018101516001600160a01b0381165f818152868452604090819020805460ff19168915159081179091559051908152919350917fac6d52e87f8a8fc486e04600668caffa28c149f8286b136c0f327b4499b8c723910160405180910390a250600101611587565b61161a611889565b565b611624611889565b610bb182826118d2565b5f6116445f805160206121138339815191525490565b5f0361165157508161073a565b610a0d8361166a5f805160206121138339815191525490565b611672610715565b856116b1565b6116828282610d54565b610bb15760405163e2517d3f60e01b81526001600160a01b038216600482015260248101839052604401610990565b5f6116de6116be836118e4565b80156116d957505f84806116d4576116d4611f79565b868809115b151590565b6116e9868686611910565b6116f39190611ed5565b95945050505050565b5f805160206120f38339815191526001600160a01b0385166117335760405163e602df0560e01b81525f6004820152602401610990565b6001600160a01b03841661175c57604051634a1406b160e11b81525f6004820152602401610990565b6001600160a01b038086165f908152600183016020908152604080832093881683529290522083905581156117d957836001600160a01b0316856001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925856040516117d091815260200190565b60405180910390a35b5050505050565b7f7e7ba5b20f89141f0255e9704ce6ce6e55f5f28e4fc0d626fc76bedba3053201545f805160206120d38339815191529060ff16801561183857506001600160a01b0384165f9081526020829052604090205460ff16155b801561184c57506001600160a01b03841615155b801561186057506001600160a01b03831615155b1561187e57604051636ab17e0560e01b815260040160405180910390fd5b610b3f8484846119c6565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054600160401b900460ff1661161a57604051631afcd79f60e31b815260040160405180910390fd5b6118da611889565b610bb18282611aff565b5f60028260038111156118f9576118f9611f8d565b6119039190611fa1565b60ff166001149050919050565b5f838302815f1985870982811083820303915050805f036119445783828161193a5761193a611f79565b0492505050610a0d565b80841161195b5761195b6003851502601118611b4f565b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b5f805160206120f38339815191526001600160a01b038416611a005781816002015f8282546119f59190611ed5565b90915550611a709050565b6001600160a01b0384165f9081526020829052604090205482811015611a525760405163391434e360e21b81526001600160a01b03861660048201526024810182905260448101849052606401610990565b6001600160a01b0385165f9081526020839052604090209083900390555b6001600160a01b038316611a8e576002810180548390039055611aac565b6001600160a01b0383165f9081526020829052604090208054830190555b826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef84604051611af191815260200190565b60405180910390a350505050565b611b07611889565b5f805160206120f38339815191527f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace03611b408482612012565b5060048101610b3f8382612012565b634e487b715f52806020526024601cfd5b5f60208284031215611b70575f80fd5b81356001600160e01b031981168114610a0d575f80fd5b5f602080835283518060208501525f5b81811015611bb357858101830151858201604001528201611b97565b505f604082860101526040601f19601f8301168501019250505092915050565b5f60208284031215611be3575f80fd5b5035919050565b6001600160a01b03811681146112e7575f80fd5b5f8060408385031215611c0f575f80fd5b8235611c1a81611bea565b946020939093013593505050565b5f805f60608486031215611c3a575f80fd5b8335611c4581611bea565b92506020840135611c5581611bea565b929592945050506040919091013590565b5f60208284031215611c76575f80fd5b8135610a0d81611bea565b5f8060408385031215611c92575f80fd5b823591506020830135611ca481611bea565b809150509250929050565b634e487b7160e01b5f52604160045260245ffd5b60405160c0810167ffffffffffffffff81118282101715611ce657611ce6611caf565b60405290565b5f82601f830112611cfb575f80fd5b8135602067ffffffffffffffff80831115611d1857611d18611caf565b8260051b604051601f19603f83011681018181108482111715611d3d57611d3d611caf565b6040529384526020818701810194908101925087851115611d5c575f80fd5b6020870191505b84821015611d85578135611d7681611bea565b83529183019190830190611d63565b979650505050505050565b5f60208284031215611da0575f80fd5b813567ffffffffffffffff811115611db6575f80fd5b61132684828501611cec565b8035611dcd81611bea565b919050565b5f60208284031215611de2575f80fd5b813567ffffffffffffffff80821115611df9575f80fd5b9083019060c08286031215611e0c575f80fd5b611e14611cc3565b8235611e1f81611bea565b81526020830135611e2f81611bea565b60208201526040830135611e4281611bea565b6040820152611e5360608401611dc2565b6060820152611e6460808401611dc2565b608082015260a083013582811115611e7a575f80fd5b611e8687828601611cec565b60a08301525095945050505050565b5f8060408385031215611ea6575f80fd5b8235611eb181611bea565b91506020830135611ca481611bea565b634e487b7160e01b5f52601160045260245ffd5b8082018082111561073a5761073a611ec1565b600181811c90821680611efc57607f821691505b602082108103611f1a57634e487b7160e01b5f52602260045260245ffd5b50919050565b5f60208284031215611f30575f80fd5b8151610a0d81611bea565b8181038181111561073a5761073a611ec1565b5f60208284031215611f5e575f80fd5b5051919050565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601260045260245ffd5b634e487b7160e01b5f52602160045260245ffd5b5f60ff831680611fbf57634e487b7160e01b5f52601260045260245ffd5b8060ff84160691505092915050565b601f821115610b7857805f5260205f20601f840160051c81016020851015611ff35750805b601f840160051c820191505b818110156117d9575f8155600101611fff565b815167ffffffffffffffff81111561202c5761202c611caf565b6120408161203a8454611ee8565b84611fce565b602080601f831160018114612073575f841561205c5750858301515b5f19600386901b1c1916600185901b1785556120ca565b5f85815260208120601f198616915b828110156120a157888601518255948401946001909101908401612082565b50858210156120be57878501515f19600388901b60f8161c191681555b505060018460011b0185555b50505050505056fe7e7ba5b20f89141f0255e9704ce6ce6e55f5f28e4fc0d626fc76bedba305320052c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0052c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace02427da25fe773164f88948d3e215c94b6554e2ed5e5f203a821c9f2f6131cf75a02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800a264697066735822122034c087a61bb674f4958a98f5cf1bd52d2f584c4c96bab73fa37add66d2ce63c364736f6c63430008180033
Deployed Bytecode
0x608060405260043610610236575f3560e01c806361fd0ae111610129578063a9059cbb116100a8578063e63ab1e91161006d578063e63ab1e91461068e578063e7b0504b146106c1578063ef8b30f714610631578063f14210a6146106d6578063fb1bb9de146106f5575f80fd5b8063a9059cbb146105f3578063b7b199c714610612578063c6e6f59214610631578063d547741f14610650578063dd62ed3e1461066f575f80fd5b80638ffbf6db116100ee5780638ffbf6db1461054b57806391d148541461056a57806395d89b4114610589578063a1a25e6e1461059d578063a217fddf146105e0575f80fd5b806361fd0ae1146104bc578063631cbe3c146104db57806363d8882a146104e357806370a08231146104f75780638936a91f14610537575f80fd5b8063282c51f3116101b55780633f2a55401161017a5780633f2a55401461042857806342966c681461045f578063443dc4281461047e5780634cdad506146102e557806360da3e831461049c575f80fd5b8063282c51f3146103895780632d2da806146103bc5780632f2ff15d146103cf578063313ce567146103ee57806336568abe14610409575f80fd5b8063095ea7b3116101fb578063095ea7b31461030457806318160ddd146103235780631ef2aac51461034357806323b872dd1461034b578063248a9ca31461036a575f80fd5b806301e1d1141461025857806301ffc9a71461027f57806302191980146102ae57806306fdde03146102c457806307a2d13a146102e5575f80fd5b3661025457604051636c897afd60e01b815260040160405180910390fd5b5f80fd5b348015610263575f80fd5b5061026c610715565b6040519081526020015b60405180910390f35b34801561028a575f80fd5b5061029e610299366004611b60565b610740565b6040519015158152602001610276565b3480156102b9575f80fd5b506102c2610774565b005b3480156102cf575f80fd5b506102d86107f8565b6040516102769190611b87565b3480156102f0575f80fd5b5061026c6102ff366004611bd3565b6108b8565b34801561030f575f80fd5b5061029e61031e366004611bfe565b6108c3565b34801561032e575f80fd5b505f805160206121138339815191525461026c565b6102c26108da565b348015610356575f80fd5b5061029e610365366004611c28565b6109ef565b348015610375575f80fd5b5061026c610384366004611bd3565b610a14565b348015610394575f80fd5b5061026c7f3c11d16cbaffd01df69ce1c404f6340ee057498f5f00246190ea54220576a84881565b61026c6103ca366004611c66565b610a34565b3480156103da575f80fd5b506102c26103e9366004611c81565b610b23565b3480156103f9575f80fd5b5060405160128152602001610276565b348015610414575f80fd5b506102c2610423366004611c81565b610b45565b348015610433575f80fd5b50600154610447906001600160a01b031681565b6040516001600160a01b039091168152602001610276565b34801561046a575f80fd5b506102c2610479366004611bd3565b610b7d565b348015610489575f80fd5b505f54610447906001600160a01b031681565b3480156104a7575f80fd5b5060015461029e90600160a01b900460ff1681565b3480156104c7575f80fd5b506102c26104d6366004611d90565b610bb5565b6102c2610bd6565b3480156104ee575f80fd5b506102c2610c53565b348015610502575f80fd5b5061026c610511366004611c66565b6001600160a01b03165f9081525f805160206120f3833981519152602052604090205490565b348015610542575f80fd5b506102c2610cb7565b348015610556575f80fd5b506102c2610565366004611d90565b610d32565b348015610575575f80fd5b5061029e610584366004611c81565b610d54565b348015610594575f80fd5b506102d8610d8a565b3480156105a8575f80fd5b5061029e6105b7366004611c66565b6001600160a01b03165f9081525f805160206120d3833981519152602052604090205460ff1690565b3480156105eb575f80fd5b5061026c5f81565b3480156105fe575f80fd5b5061029e61060d366004611bfe565b610dc8565b34801561061d575f80fd5b506102c261062c366004611dd2565b610dd5565b34801561063c575f80fd5b5061026c61064b366004611bd3565b6110cd565b34801561065b575f80fd5b506102c261066a366004611c81565b6110d8565b34801561067a575f80fd5b5061026c610689366004611e95565b6110f4565b348015610699575f80fd5b5061026c7f65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a81565b3480156106cc575f80fd5b5061026c60025481565b3480156106e1575f80fd5b506102c26106f0366004611bd3565b61113d565b348015610700575f80fd5b5061026c5f8051602061213383398151915281565b6002545f9081906107269082611ed5565b9050610730611264565b61073a9082611ed5565b92915050565b5f6001600160e01b03198216637965db0b60e01b148061073a57506301ffc9a760e01b6001600160e01b031983161461073a565b7f65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a61079e816112dd565b6001805460ff60a01b1916600160a01b908117918290556040517f35e03641f0c63f166bca10b4ee931a3c02be26ffb29a395ce012099d99ecb6cc926107ed92900460ff161515815260200190565b60405180910390a150565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0380546060915f805160206120f38339815191529161083690611ee8565b80601f016020809104026020016040519081016040528092919081815260200182805461086290611ee8565b80156108ad5780601f10610884576101008083540402835291602001916108ad565b820191905f5260205f20905b81548152906001019060200180831161089057829003601f168201915b505050505091505090565b5f61073a825f6112ea565b5f336108d081858561132e565b5060019392505050565b5f546001600160a01b031633148061097557505f8054906101000a90046001600160a01b03166001600160a01b0316637d1f8a816040518163ffffffff1660e01b81526004016020604051808303815f875af115801561093c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109609190611f20565b6001600160a01b0316336001600160a01b0316145b61099957604051631bb2e8ef60e21b81523360048201526024015b60405180910390fd5b3460025f8282546109aa9190611ed5565b90915550506002546040805134815260208101929092527f7be0d7fd798145f666ec52ac3f0d58a38be2081e9debf17f96e11c21c848ea2791015b60405180910390a1565b5f336109fc85828561133b565b610a07858585611398565b60019150505b9392505050565b5f9081525f80516020612153833981519152602052604090206001015490565b6001545f90600160a01b900460ff1615610a61576040516313d0ff5960e31b815260040160405180910390fd5b345f03610a81576040516335ed7e5760e11b815260040160405180910390fd5b34610a8b816110cd565b9150815f03610aad57604051639811e0c760e01b815260040160405180910390fd5b610ab783836113f5565b8060025f828254610ac89190611ed5565b9091555050600254604080518381526020810185905280820192909252516001600160a01b0385169133917f4e2ca0515ed1aef1395f66b5303bb5d6f1bf9d61a353fa53f73f8ac9973fa9f69181900360600190a350919050565b610b2c82610a14565b610b35816112dd565b610b3f8383611429565b50505050565b6001600160a01b0381163314610b6e5760405163334bd91960e11b815260040160405180910390fd5b610b7882826114ca565b505050565b7f3c11d16cbaffd01df69ce1c404f6340ee057498f5f00246190ea54220576a848610ba7816112dd565b610bb13383611543565b5050565b5f80516020612133833981519152610bcc816112dd565b610bb1825f611577565b6001546001600160a01b03163314610c035760405163df6752fd60e01b8152336004820152602401610990565b3460025f828254610c149190611ed5565b90915550506002546040805134815260208101929092527f61cb44cbea389abb97c617c7d16a62235c51f27da3406d3ec3c9ac87c0d0c82691016109e5565b5f80516020612133833981519152610c6a816112dd565b6001805460ff60a01b1916908190556040517f35e03641f0c63f166bca10b4ee931a3c02be26ffb29a395ce012099d99ecb6cc916107ed91600160a01b90910460ff161515815260200190565b5f80516020612133833981519152610cce816112dd565b7f7e7ba5b20f89141f0255e9704ce6ce6e55f5f28e4fc0d626fc76bedba3053201805460ff191690556040515f805160206120d3833981519152907f5b1b646968864ea75fad546d8c819e0de710df0bf61f658f6ba54dc587472e7b905f90a15050565b5f80516020612133833981519152610d49816112dd565b610bb1826001611577565b5f9182525f80516020612153833981519152602090815260408084206001600160a01b0393909316845291905290205460ff1690565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0480546060915f805160206120f38339815191529161083690611ee8565b5f336108d0818585611398565b80516001600160a01b038116610dfe5760405163d92e233d60e01b815260040160405180910390fd5b60208201516001600160a01b038116610e2a5760405163d92e233d60e01b815260040160405180910390fd5b60408301516001600160a01b038116610e565760405163d92e233d60e01b815260040160405180910390fd5b60608401516001600160a01b038116610e825760405163d92e233d60e01b815260040160405180910390fd5b60808501516001600160a01b038116610eae5760405163d92e233d60e01b815260040160405180910390fd5b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff16159067ffffffffffffffff165f81158015610ef35750825b90505f8267ffffffffffffffff166001148015610f0f5750303b155b905081158015610f1d575080155b15610f3b5760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff191660011785558315610f6557845460ff60401b1916600160401b1785555b610f6d611612565b610fb1604051806040016040528060058152602001640f2dc8aa8960db1b815250604051806040016040528060058152602001640f2dc8aa8960db1b81525061161c565b8a51610fbe905f90611429565b50610fed7f65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a8c60200151611429565b506110095f805160206121338339815191528c60400151611429565b5060608b01515f80546001600160a01b039283166001600160a01b03199182161790915560808d0151600180549190931691161781557f7e7ba5b20f89141f0255e9704ce6ce6e55f5f28e4fc0d626fc76bedba3053201805460ff1916909117905561107a8b60a001516001611577565b83156110c057845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b5050505050505050505050565b5f61073a825f61162e565b6110e182610a14565b6110ea816112dd565b610b3f83836114ca565b6001600160a01b039182165f9081527f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace016020908152604080832093909416825291909152205490565b5f546001600160a01b0316331461117b575f5460405163d95eb40f60e01b81526001600160a01b039091166004820152336024820152604401610990565b6002548181101561119f57604051631e9acf1760e31b815260040160405180910390fd5b5f6111aa8383611f3b565b60028190555f805460405192935090916001600160a01b039091169085908381818185875af1925050503d805f81146111fe576040519150601f19603f3d011682016040523d82523d5f602084013e611203565b606091505b5050905080611225576040516312171d8360e31b815260040160405180910390fd5b60408051858152602081018490527f72e1ec2b6bc1315b9dd8b8a5704a77cbac7378d6e44866f92d6985f0793dc4c2910160405180910390a150505050565b5f805f9054906101000a90046001600160a01b03166001600160a01b031663ff50abdc6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156112b4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112d89190611f4e565b905090565b6112e78133611678565b50565b5f806113015f805160206121138339815191525490565b9050805f03611313578391505061073a565b6113268461131f610715565b83866116b1565b949350505050565b610b7883838360016116fc565b5f61134684846110f4565b90505f198114610b3f578181101561138a57604051637dc7a0d960e11b81526001600160a01b03841660048201526024810182905260448101839052606401610990565b610b3f84848484035f6116fc565b6001600160a01b0383166113c157604051634b637e8f60e11b81525f6004820152602401610990565b6001600160a01b0382166113ea5760405163ec442f0560e01b81525f6004820152602401610990565b610b788383836117e0565b6001600160a01b03821661141e5760405163ec442f0560e01b81525f6004820152602401610990565b610bb15f83836117e0565b5f5f805160206121538339815191526114428484610d54565b6114c1575f848152602082815260408083206001600160a01b03871684529091529020805460ff191660011790556114773390565b6001600160a01b0316836001600160a01b0316857f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a4600191505061073a565b5f91505061073a565b5f5f805160206121538339815191526114e38484610d54565b156114c1575f848152602082815260408083206001600160a01b0387168085529252808320805460ff1916905551339287917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a4600191505061073a565b6001600160a01b03821661156c57604051634b637e8f60e11b81525f6004820152602401610990565b610bb1825f836117e0565b5f805160206120d38339815191525f5b8351811015610b3f575f8482815181106115a3576115a3611f65565b6020908102919091018101516001600160a01b0381165f818152868452604090819020805460ff19168915159081179091559051908152919350917fac6d52e87f8a8fc486e04600668caffa28c149f8286b136c0f327b4499b8c723910160405180910390a250600101611587565b61161a611889565b565b611624611889565b610bb182826118d2565b5f6116445f805160206121138339815191525490565b5f0361165157508161073a565b610a0d8361166a5f805160206121138339815191525490565b611672610715565b856116b1565b6116828282610d54565b610bb15760405163e2517d3f60e01b81526001600160a01b038216600482015260248101839052604401610990565b5f6116de6116be836118e4565b80156116d957505f84806116d4576116d4611f79565b868809115b151590565b6116e9868686611910565b6116f39190611ed5565b95945050505050565b5f805160206120f38339815191526001600160a01b0385166117335760405163e602df0560e01b81525f6004820152602401610990565b6001600160a01b03841661175c57604051634a1406b160e11b81525f6004820152602401610990565b6001600160a01b038086165f908152600183016020908152604080832093881683529290522083905581156117d957836001600160a01b0316856001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925856040516117d091815260200190565b60405180910390a35b5050505050565b7f7e7ba5b20f89141f0255e9704ce6ce6e55f5f28e4fc0d626fc76bedba3053201545f805160206120d38339815191529060ff16801561183857506001600160a01b0384165f9081526020829052604090205460ff16155b801561184c57506001600160a01b03841615155b801561186057506001600160a01b03831615155b1561187e57604051636ab17e0560e01b815260040160405180910390fd5b610b3f8484846119c6565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054600160401b900460ff1661161a57604051631afcd79f60e31b815260040160405180910390fd5b6118da611889565b610bb18282611aff565b5f60028260038111156118f9576118f9611f8d565b6119039190611fa1565b60ff166001149050919050565b5f838302815f1985870982811083820303915050805f036119445783828161193a5761193a611f79565b0492505050610a0d565b80841161195b5761195b6003851502601118611b4f565b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b5f805160206120f38339815191526001600160a01b038416611a005781816002015f8282546119f59190611ed5565b90915550611a709050565b6001600160a01b0384165f9081526020829052604090205482811015611a525760405163391434e360e21b81526001600160a01b03861660048201526024810182905260448101849052606401610990565b6001600160a01b0385165f9081526020839052604090209083900390555b6001600160a01b038316611a8e576002810180548390039055611aac565b6001600160a01b0383165f9081526020829052604090208054830190555b826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef84604051611af191815260200190565b60405180910390a350505050565b611b07611889565b5f805160206120f38339815191527f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace03611b408482612012565b5060048101610b3f8382612012565b634e487b715f52806020526024601cfd5b5f60208284031215611b70575f80fd5b81356001600160e01b031981168114610a0d575f80fd5b5f602080835283518060208501525f5b81811015611bb357858101830151858201604001528201611b97565b505f604082860101526040601f19601f8301168501019250505092915050565b5f60208284031215611be3575f80fd5b5035919050565b6001600160a01b03811681146112e7575f80fd5b5f8060408385031215611c0f575f80fd5b8235611c1a81611bea565b946020939093013593505050565b5f805f60608486031215611c3a575f80fd5b8335611c4581611bea565b92506020840135611c5581611bea565b929592945050506040919091013590565b5f60208284031215611c76575f80fd5b8135610a0d81611bea565b5f8060408385031215611c92575f80fd5b823591506020830135611ca481611bea565b809150509250929050565b634e487b7160e01b5f52604160045260245ffd5b60405160c0810167ffffffffffffffff81118282101715611ce657611ce6611caf565b60405290565b5f82601f830112611cfb575f80fd5b8135602067ffffffffffffffff80831115611d1857611d18611caf565b8260051b604051601f19603f83011681018181108482111715611d3d57611d3d611caf565b6040529384526020818701810194908101925087851115611d5c575f80fd5b6020870191505b84821015611d85578135611d7681611bea565b83529183019190830190611d63565b979650505050505050565b5f60208284031215611da0575f80fd5b813567ffffffffffffffff811115611db6575f80fd5b61132684828501611cec565b8035611dcd81611bea565b919050565b5f60208284031215611de2575f80fd5b813567ffffffffffffffff80821115611df9575f80fd5b9083019060c08286031215611e0c575f80fd5b611e14611cc3565b8235611e1f81611bea565b81526020830135611e2f81611bea565b60208201526040830135611e4281611bea565b6040820152611e5360608401611dc2565b6060820152611e6460808401611dc2565b608082015260a083013582811115611e7a575f80fd5b611e8687828601611cec565b60a08301525095945050505050565b5f8060408385031215611ea6575f80fd5b8235611eb181611bea565b91506020830135611ca481611bea565b634e487b7160e01b5f52601160045260245ffd5b8082018082111561073a5761073a611ec1565b600181811c90821680611efc57607f821691505b602082108103611f1a57634e487b7160e01b5f52602260045260245ffd5b50919050565b5f60208284031215611f30575f80fd5b8151610a0d81611bea565b8181038181111561073a5761073a611ec1565b5f60208284031215611f5e575f80fd5b5051919050565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601260045260245ffd5b634e487b7160e01b5f52602160045260245ffd5b5f60ff831680611fbf57634e487b7160e01b5f52601260045260245ffd5b8060ff84160691505092915050565b601f821115610b7857805f5260205f20601f840160051c81016020851015611ff35750805b601f840160051c820191505b818110156117d9575f8155600101611fff565b815167ffffffffffffffff81111561202c5761202c611caf565b6120408161203a8454611ee8565b84611fce565b602080601f831160018114612073575f841561205c5750858301515b5f19600386901b1c1916600185901b1785556120ca565b5f85815260208120601f198616915b828110156120a157888601518255948401946001909101908401612082565b50858210156120be57878501515f19600388901b60f8161c191681555b505060018460011b0185555b50505050505056fe7e7ba5b20f89141f0255e9704ce6ce6e55f5f28e4fc0d626fc76bedba305320052c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0052c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace02427da25fe773164f88948d3e215c94b6554e2ed5e5f203a821c9f2f6131cf75a02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800a264697066735822122034c087a61bb674f4958a98f5cf1bd52d2f584c4c96bab73fa37add66d2ce63c364736f6c63430008180033
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 30 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|
Loading...
Loading
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.