Verified contractExactBUSL-1.1
EigenYieldsVault
Address0x211b563d769b07bb4a867459262fccac548044a6
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.33
- Same code
Only this contract
Details
- Compiler
- solc 0.8.33+commit.64118f21
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,487,808
- Creation transaction
- 0xb9d4a4c67c…49fa780395
39 files
- src/EigenYieldsVault.solmain41.7 KB
- lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol8.35 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol1.22 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol5.2 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol1.17 KB
- lib/openzeppelin-contracts/contracts/access/IAccessControl.sol3.34 KB
- lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol9.28 KB
- lib/openzeppelin-contracts/contracts/utils/Arrays.sol20.91 KB
- lib/openzeppelin-contracts/contracts/utils/Bytes.sol11.08 KB
- lib/openzeppelin-contracts/contracts/utils/Comparators.sol443 B
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin-contracts/contracts/utils/SlotDerivation.sol5.32 KB
- lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol4.18 KB
- lib/openzeppelin-contracts/contracts/utils/Strings.sol19.88 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol11.9 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol4.25 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol32.35 KB
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol2.61 KB
- lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol29.63 KB
- lib/openzeppelin-contracts/contracts/utils/types/Time.sol5.16 KB
- src/EigenYieldsPausable.sol7.24 KB
- src/EigenYieldsPausableStorage.sol957 B
- src/EigenYieldsVaultBase.sol13.67 KB
- src/EigenYieldsVaultStorage.sol2.65 KB
- src/interfaces/IAccountant.sol8.61 KB
- src/interfaces/IEigenYieldsPausable.sol2.94 KB
- src/interfaces/IEigenYieldsVault.sol23.17 KB
- src/interfaces/IEigenYieldsVaultDeposit.sol8.41 KB
- src/interfaces/IEigenYieldsVaultRedeem.sol8.99 KB
- src/interfaces/IEigenYieldsVaultSettlement.sol12.68 KB
- src/libraries/AuthLibrary.sol6.61 KB
- src/libraries/ERC4626Math.sol4.68 KB
- src/libraries/ModulesLibrary.sol1.64 KB
- src/libraries/PausableFlows.sol1.8 KB
- src/libraries/RolesLibrary.sol1.96 KB
- src/libraries/SeriesAccounting.sol12.64 KB
- src/libraries/TimelockRegistry.sol5.87 KB
src/EigenYieldsVault.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.27;
/*
_______ _ __ ___ _ _
| ____(_) __ _ ___ _ __ \ \ / (_) ___| | __| |___
| _| | |/ _` |/ _ \ '_ \ \ V /| |/ _ \ |/ _` / __|
| |___| | (_| | __/ | | | | | | | __/ | (_| \__ \
|_____|_|\__, |\___|_| |_| |_| |_|\___|_|\__,_|___/
|___/
*/
import {Time} from "openzeppelin-contracts/contracts/utils/types/Time.sol";
import {IAccountant} from "@eigenyields-vault/interfaces/IAccountant.sol";
import {IEigenYieldsVault} from "@eigenyields-vault/interfaces/IEigenYieldsVault.sol";
import {IEigenYieldsVaultDeposit} from "@eigenyields-vault/interfaces/IEigenYieldsVaultDeposit.sol";
import {IEigenYieldsVaultRedeem} from "@eigenyields-vault/interfaces/IEigenYieldsVaultRedeem.sol";
import {IEigenYieldsVaultSettlement} from "@eigenyields-vault/interfaces/IEigenYieldsVaultSettlement.sol";
import {ModulesLibrary} from "@eigenyields-vault/libraries/ModulesLibrary.sol";
import {PausableFlows} from "@eigenyields-vault/libraries/PausableFlows.sol";
import {RolesLibrary} from "@eigenyields-vault/libraries/RolesLibrary.sol";
import {SeriesAccounting} from "@eigenyields-vault/libraries/SeriesAccounting.sol";
import {EigenYieldsPausable} from "@eigenyields-vault/EigenYieldsPausable.sol";
import {EigenYieldsVaultBase} from "@eigenyields-vault/EigenYieldsVaultBase.sol";
import {EigenYieldsVaultStorageData} from "@eigenyields-vault/EigenYieldsVaultStorage.sol";
/**
* @dev Functions that use routeToModule() may have parameters that appear unused
* but are actually passed through to the delegated implementation via calldata
*/
contract EigenYieldsVault is IEigenYieldsVault, EigenYieldsVaultBase, EigenYieldsPausable {
/*//////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////*/
/**
* @notice Modifier to check if a share class id is valid
* @param _classId The share class id
*/
modifier onlyValidShareClass(uint8 _classId) {
// check if share class id is valid or not
if (_classId > _getStorage().shareClassesId || _classId == 0) {
revert InvalidShareClass();
}
_;
}
/**
* @notice Modifier to check if a share class and series id are valid
* @param _classId The share class id
* @param _seriesId The share series id
*/
modifier onlyValidShareClassAndSeries(uint8 _classId, uint32 _seriesId) {
EigenYieldsVaultStorageData storage sd = _getStorage();
// check if share class id is valid or not
if (_classId > sd.shareClassesId || _classId == 0) {
revert InvalidShareClass();
}
// check if share series id is valid or not
// series that haven't been created yet or that have been consolidated are considered invalid
IEigenYieldsVault.ShareClass storage shareClass = sd.shareClasses[_classId];
if (
_seriesId > shareClass.shareSeriesId
|| (_seriesId > SeriesAccounting.LEAD_SERIES_ID && _seriesId <= shareClass.lastConsolidatedSeriesId)
) {
revert InvalidShareSeries();
}
_;
}
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/**
* @notice Constructor.
* @param _batchDuration The duration of a batch.
*/
constructor(uint48 _batchDuration) EigenYieldsVaultBase(_batchDuration) {}
/*//////////////////////////////////////////////////////////////
INITIALIZER
//////////////////////////////////////////////////////////////*/
/**
* @notice Initializes the vault with the given parameters.
* @param initParams Struct containing all initialization parameters.
*/
function initialize(InitializationParams calldata initParams) public initializer {
bootstrapVault(initParams);
}
/*//////////////////////////////////////////////////////////////
VIEW FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IEigenYieldsVault
function startTimeStamp() external view returns (uint48) {
return _getStorage().startTimeStamp;
}
/// @inheritdoc IEigenYieldsVault
function currentBatch() external view returns (uint48) {
return currentBatchId(_getStorage());
}
/// @inheritdoc IEigenYieldsVault
function shareClasses() external view returns (uint8) {
return _getStorage().shareClassesId;
}
/// @inheritdoc IEigenYieldsVault
function shareSeriesId(uint8 _classId) external view onlyValidShareClass(_classId) returns (uint32) {
return _getStorage().shareClasses[_classId].shareSeriesId;
}
/// @inheritdoc IEigenYieldsVault
function lastConsolidatedSeriesId(uint8 _classId) external view returns (uint32) {
return _getStorage().shareClasses[_classId].lastConsolidatedSeriesId;
}
/// @inheritdoc IEigenYieldsVault
function name() external view returns (string memory) {
return _getStorage().name;
}
/// @inheritdoc IEigenYieldsVault
function manager() external view returns (address) {
return _getStorage().manager;
}
/// @inheritdoc IEigenYieldsVault
function underlyingToken() external view returns (address) {
return _getStorage().underlyingToken;
}
/// @inheritdoc IEigenYieldsVault
function custodian() external view returns (address) {
return _getStorage().custodian;
}
/// @inheritdoc IEigenYieldsVault
function vaultTreasury() external view returns (address) {
return IAccountant(_getStorage().accountant).vaultTreasury();
}
/// @inheritdoc IEigenYieldsVault
function operationsMultisig() external view returns (address) {
return _getStorage().operationsMultisig;
}
/// @inheritdoc IEigenYieldsVault
function oracle() external view returns (address) {
return _getStorage().oracle;
}
/// @inheritdoc IEigenYieldsVault
function guardian() external view returns (address) {
return _getStorage().guardian;
}
/// @inheritdoc IEigenYieldsVault
function authSigner() external view returns (address) {
return _getStorage().authSigner;
}
/// @inheritdoc IEigenYieldsVault
function accountant() external view returns (address) {
return _getStorage().accountant;
}
/// @inheritdoc IEigenYieldsVault
function managementFee(uint8 _classId) external view onlyValidShareClass(_classId) returns (uint32) {
return _getStorage().shareClasses[_classId].shareClassParams.managementFee;
}
/// @inheritdoc IEigenYieldsVault
function performanceFee(uint8 _classId) external view onlyValidShareClass(_classId) returns (uint32) {
return _getStorage().shareClasses[_classId].shareClassParams.performanceFee;
}
/// @inheritdoc IEigenYieldsVault
function noticePeriod(uint8 _classId) external view onlyValidShareClass(_classId) returns (uint48) {
return _getStorage().shareClasses[_classId].shareClassParams.noticePeriod;
}
/// @inheritdoc IEigenYieldsVault
function lockInPeriod(uint8 _classId) external view onlyValidShareClass(_classId) returns (uint48) {
return _getStorage().shareClasses[_classId].shareClassParams.lockInPeriod;
}
/// @inheritdoc IEigenYieldsVault
function minDepositAmount(uint8 _classId) external view onlyValidShareClass(_classId) returns (uint256) {
return _getStorage().shareClasses[_classId].shareClassParams.minDepositAmount;
}
/// @inheritdoc IEigenYieldsVault
function minUserBalance(uint8 _classId) external view onlyValidShareClass(_classId) returns (uint256) {
return _getStorage().shareClasses[_classId].shareClassParams.minUserBalance;
}
/// @inheritdoc IEigenYieldsVault
function maxDepositCap(uint8 _classId) external view onlyValidShareClass(_classId) returns (uint256) {
return _getStorage().shareClasses[_classId].shareClassParams.maxDepositCap;
}
/// @inheritdoc IEigenYieldsVault
function minRedeemAmount(uint8 _classId) external view onlyValidShareClass(_classId) returns (uint256) {
return _getStorage().shareClasses[_classId].shareClassParams.minRedeemAmount;
}
/// @inheritdoc IEigenYieldsVault
function userLockInPeriod(uint8 _classId, address _user)
external
view
onlyValidShareClass(_classId)
returns (uint48)
{
return _getStorage().shareClasses[_classId].userLockInPeriod[_user];
}
/// @inheritdoc IEigenYieldsVault
function redeemableAmount(address _user) external view returns (uint256) {
return _getStorage().redeemableAmount[_user];
}
/// @inheritdoc IEigenYieldsVault
function isDepositAuthEnabled() external view returns (bool) {
return _getStorage().isDepositAuthEnabled;
}
/// @inheritdoc IEigenYieldsVault
function isSettlementAuthEnabled() external view returns (bool) {
return _getStorage().isSettlementAuthEnabled;
}
/// @inheritdoc IEigenYieldsVault
function totalAssets() external view returns (uint256) {
return computeTotalAssets(_getStorage());
}
/// @inheritdoc IEigenYieldsVault
function totalAssetsOfClass(uint8 _classId) external view onlyValidShareClass(_classId) returns (uint256[] memory) {
IEigenYieldsVault.ShareClass storage shareClass = _getStorage().shareClasses[_classId];
uint32 seriesCount = shareClass.shareSeriesId;
uint32 lastConsolidated = shareClass.lastConsolidatedSeriesId;
uint32 len = seriesCount - lastConsolidated + 1;
uint256[] memory result = new uint256[](len);
for (uint32 i; i < len; i++) {
uint32 sid = i > SeriesAccounting.LEAD_SERIES_ID ? lastConsolidated + i : SeriesAccounting.LEAD_SERIES_ID;
result[i] = seriesAssets(shareClass, sid);
}
return result;
}
/// @inheritdoc IEigenYieldsVault
function totalAssetsPerClass(uint8 _classId) external view onlyValidShareClass(_classId) returns (uint256) {
return classAssets(_getStorage().shareClasses[_classId], _classId);
}
/// @inheritdoc IEigenYieldsVault
function totalAssetsPerSeries(uint8 _classId, uint32 _seriesId)
external
view
onlyValidShareClassAndSeries(_classId, _seriesId)
returns (uint256)
{
return seriesAssets(_getStorage().shareClasses[_classId], _seriesId);
}
/// @inheritdoc IEigenYieldsVault
function totalSharesPerSeries(uint8 _classId, uint32 _seriesId)
external
view
onlyValidShareClassAndSeries(_classId, _seriesId)
returns (uint256)
{
return seriesShares(_getStorage().shareClasses[_classId], _seriesId);
}
/// @inheritdoc IEigenYieldsVault
function assetsPerClassOf(uint8 _classId, address _user)
external
view
onlyValidShareClass(_classId)
returns (uint256)
{
return userClassAssets(_getStorage().shareClasses[_classId], _classId, _user);
}
/// @inheritdoc IEigenYieldsVault
function assetsOf(uint8 _classId, uint32 _seriesId, address _user)
external
view
onlyValidShareClassAndSeries(_classId, _seriesId)
returns (uint256)
{
return userAssetsInSeries(_getStorage().shareClasses[_classId], _classId, _seriesId, _user);
}
/// @inheritdoc IEigenYieldsVault
function sharesOf(uint8 _classId, uint32 _seriesId, address _user)
external
view
onlyValidShareClassAndSeries(_classId, _seriesId)
returns (uint256)
{
return userSharesInSeries(_getStorage().shareClasses[_classId], _seriesId, _user);
}
/// @inheritdoc IEigenYieldsVault
function pricePerShare(uint8 _classId, uint32 _seriesId)
external
view
onlyValidShareClassAndSeries(_classId, _seriesId)
returns (uint256)
{
IEigenYieldsVault.ShareClass storage shareClass = _getStorage().shareClasses[_classId];
return calcSharePrice(seriesAssets(shareClass, _seriesId), seriesShares(shareClass, _seriesId));
}
/// @inheritdoc IEigenYieldsVault
function highWaterMark(uint8 _classId, uint32 _seriesId)
external
view
onlyValidShareClassAndSeries(_classId, _seriesId)
returns (uint256)
{
return _getStorage().shareClasses[_classId].shareSeries[_seriesId].highWaterMark;
}
/// @inheritdoc IEigenYieldsVault
function totalAmountToDeposit(uint8 _classId) external view onlyValidShareClass(_classId) returns (uint256) {
return pendingDeposits(_getStorage(), _classId);
}
/// @inheritdoc IEigenYieldsVault
function totalAmountToDepositAt(uint8 _classId, uint48 _batchId)
external
view
onlyValidShareClass(_classId)
returns (uint256)
{
return _getStorage().shareClasses[_classId].depositRequests[_batchId].totalAmountToDeposit;
}
/// @inheritdoc IEigenYieldsVault
function depositRequestOf(uint8 _classId, address _user) external view returns (uint256 _totalAmountToDeposit) {
return userDepositRequest(_getStorage(), _classId, _user);
}
/// @inheritdoc IEigenYieldsVault
function depositRequestOfAt(uint8 _classId, address _user, uint48 _batchId)
external
view
returns (uint256 _amountToDeposit)
{
return _getStorage().shareClasses[_classId].depositRequests[_batchId].depositRequest[_user];
}
/// @inheritdoc IEigenYieldsVault
function redeemRequestOf(uint8 _classId, address _user) external view returns (uint256 _totalAmountToRedeem) {
EigenYieldsVaultStorageData storage sd = _getStorage();
IEigenYieldsVault.ShareClass storage shareClass = sd.shareClasses[_classId];
return userPendingAssets(shareClass, currentBatchId(sd), _user, userClassAssets(shareClass, _classId, _user));
}
/// @inheritdoc IEigenYieldsVault
function redeemRequestOfAt(uint8 _classId, address _user, uint48 _batchId)
external
view
returns (uint256 _amountShareToRedeem)
{
return _getStorage().shareClasses[_classId].redeemRequests[_batchId].redeemRequest[_user];
}
/// @inheritdoc IEigenYieldsVault
function usersToDepositAt(uint8 _classId, uint48 _batchId) external view returns (address[] memory) {
bytes32[] memory bytesUsers =
_getStorage().shareClasses[_classId].depositRequests[_batchId].usersToDeposit._inner._values;
address[] memory users = new address[](bytesUsers.length);
assembly {
users := bytesUsers
}
return users;
}
/// @inheritdoc IEigenYieldsVault
function usersToRedeemAt(uint8 _classId, uint48 _batchId) external view returns (address[] memory) {
bytes32[] memory bytesUsers =
_getStorage().shareClasses[_classId].redeemRequests[_batchId].usersToRedeem._inner._values;
address[] memory users = new address[](bytesUsers.length);
assembly {
users := bytesUsers
}
return users;
}
/// @inheritdoc IEigenYieldsVault
function totalFeeAmountToCollect() external view returns (uint256 _totalFeeAmountToCollect) {
EigenYieldsVaultStorageData storage sd = _getStorage();
uint8 numClasses = sd.shareClassesId;
for (uint8 classId = 1; classId <= numClasses; classId++) {
IEigenYieldsVault.ShareClass storage shareClass = sd.shareClasses[classId];
_totalFeeAmountToCollect += userClassAssets(shareClass, classId, SeriesAccounting.MANAGEMENT_FEE_RECIPIENT);
_totalFeeAmountToCollect += userClassAssets(shareClass, classId, SeriesAccounting.PERFORMANCE_FEE_RECIPIENT);
}
}
/*//////////////////////////////////////////////////////////////
SETTER FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IEigenYieldsVault
function setIsDepositAuthEnabled(bool _isDepositAuthEnabled)
external
override(IEigenYieldsVault)
onlyRole(RolesLibrary.MANAGER)
{
_getStorage().isDepositAuthEnabled = _isDepositAuthEnabled;
emit IsDepositAuthEnabledSet(_isDepositAuthEnabled);
}
/// @inheritdoc IEigenYieldsVault
function setIsSettlementAuthEnabled(bool _isSettlementAuthEnabled)
external
override(IEigenYieldsVault)
onlyRole(RolesLibrary.MANAGER)
{
_getStorage().isSettlementAuthEnabled = _isSettlementAuthEnabled;
emit IsSettlementAuthEnabledSet(_isSettlementAuthEnabled);
}
/// @inheritdoc IEigenYieldsVault
function setVaultTreasury(address _vaultTreasury)
external
override(IEigenYieldsVault)
onlyRole(RolesLibrary.OPERATIONS_MULTISIG)
{
IAccountant(_getStorage().accountant).setVaultTreasury(_vaultTreasury);
emit VaultTreasurySet(_vaultTreasury);
}
/// @inheritdoc IEigenYieldsVault
function createShareClass(ShareClassParams memory _shareClassParams)
external
onlyRole(RolesLibrary.OPERATIONS_MULTISIG)
returns (uint8 _classId)
{
if (
_shareClassParams.managementFee > MAXIMUM_MANAGEMENT_FEE
|| _shareClassParams.performanceFee > MAXIMUM_PERFORMANCE_FEE || _shareClassParams.minDepositAmount == 0
|| _shareClassParams.minRedeemAmount == 0
) {
revert InvalidShareClassParams();
}
return addShareClass(_getStorage(), _shareClassParams);
}
/*//////////////////////////////////////////////////////////////
TIMELOCK FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Queues a new minimum deposit amount to be set after the timelock period
* @param _classId The ID of the share class to set the minimum deposit amount for.
* @param _minDepositAmount The new minimum deposit amount to queue.
* @dev Only callable by the MANAGER role.
*/
function queueMinDepositAmount(uint8 _classId, uint256 _minDepositAmount)
external
onlyValidShareClass(_classId)
onlyRole(RolesLibrary.MANAGER)
{
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_DEPOSIT);
}
/**
* @notice Queues a new minimum user balance to be set after the timelock period.
* @param _classId The ID of the share class to set the minimum user balance for.
* @param _minUserBalance The new minimum user balance to queue.
* @dev Only callable by the MANAGER role.
*/
function queueMinUserBalance(uint8 _classId, uint256 _minUserBalance)
external
onlyValidShareClass(_classId)
onlyRole(RolesLibrary.MANAGER)
{
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_DEPOSIT);
}
/**
* @notice Queues a new maximum deposit cap to be set after the timelock period.
* @param _classId The ID of the share class to set the maximum deposit cap for.
* @param _maxDepositCap The new maximum deposit cap to queue.
* @dev Only callable by the MANAGER role.
*/
function queueMaxDepositCap(uint8 _classId, uint256 _maxDepositCap)
external
onlyValidShareClass(_classId)
onlyRole(RolesLibrary.MANAGER)
{
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_DEPOSIT);
}
/**
* @notice Queues a new notice period to be set after the timelock period.
* @param _classId The ID of the share class to set the notice period for.
* @param _noticePeriod The new notice period to queue.
* @dev Only callable by the MANAGER role.
*/
function queueNoticePeriod(uint8 _classId, uint48 _noticePeriod)
external
onlyValidShareClass(_classId)
onlyRole(RolesLibrary.MANAGER)
{
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_REDEEM);
}
/**
* @notice Queues a new lock in period to be set after the timelock period.
* @param _classId The ID of the share class to set the lock in period for.
* @param _lockInPeriod The new lock in period to queue.
* @dev Only callable by the MANAGER role.
*/
function queueLockInPeriod(uint8 _classId, uint48 _lockInPeriod)
external
onlyValidShareClass(_classId)
onlyRole(RolesLibrary.MANAGER)
{
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_REDEEM);
}
/**
* @notice Queues a new minimum redeem amount to be set after the timelock period.
* @param _classId The ID of the share class to set the minimum redeem amount for.
* @param _minRedeemAmount The new minimum redeem amount to queue.
* @dev Only callable by the MANAGER role.
*/
function queueMinRedeemAmount(uint8 _classId, uint256 _minRedeemAmount)
external
onlyValidShareClass(_classId)
onlyRole(RolesLibrary.MANAGER)
{
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_REDEEM);
}
/**
* @notice Queues a new management fee to be set after the timelock period.
* @param _classId The ID of the share class to set the management fee for.
* @param _managementFee The new management fee to queue.
* @dev Only callable by the OPERATIONS_MULTISIG role.
*/
function queueManagementFee(uint8 _classId, uint32 _managementFee)
external
onlyValidShareClass(_classId)
onlyRole(RolesLibrary.OPERATIONS_MULTISIG)
{
routeToModule(ModulesLibrary.FEE_MANAGER);
}
/**
* @notice Queues a new performance fee to be set after the timelock period.
* @param _classId The ID of the share class to set the performance fee for.
* @param _performanceFee The new performance fee to queue.
* @dev Only callable by the OPERATIONS_MULTISIG role.
*/
function queuePerformanceFee(uint8 _classId, uint32 _performanceFee)
external
onlyValidShareClass(_classId)
onlyRole(RolesLibrary.OPERATIONS_MULTISIG)
{
routeToModule(ModulesLibrary.FEE_MANAGER);
}
/**
* @notice Sets the minimum deposit amount to the queued value after the timelock period.
* @param _classId The ID of the share class to set the minimum deposit amount for.
* @dev Only callable by the MANAGER role.
*/
function setMinDepositAmount(uint8 _classId) external onlyValidShareClass(_classId) onlyRole(RolesLibrary.MANAGER) {
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_DEPOSIT);
}
/**
* @notice Sets the minimum user balance to the queued value after the timelock period.
* @param _classId The ID of the share class to set the minimum user balance for.
* @dev Only callable by the MANAGER role.
*/
function setMinUserBalance(uint8 _classId) external onlyValidShareClass(_classId) onlyRole(RolesLibrary.MANAGER) {
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_DEPOSIT);
}
/**
* @notice Sets the maximum deposit cap to the queued value after the timelock period.
* @param _classId The ID of the share class to set the maximum deposit cap for.
* @dev Only callable by the MANAGER role.
*/
function setMaxDepositCap(uint8 _classId) external onlyValidShareClass(_classId) onlyRole(RolesLibrary.MANAGER) {
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_DEPOSIT);
}
/**
* @notice Sets the notice period to the queued value after the timelock period.
* @param _classId The ID of the share class to set the notice period for.
* @dev Only callable by the MANAGER role.
*/
function setNoticePeriod(uint8 _classId) external onlyValidShareClass(_classId) onlyRole(RolesLibrary.MANAGER) {
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_REDEEM);
}
/**
* @notice Sets the lock in period to the queued value after the timelock period.
* @param _classId The ID of the share class to set the lock in period for.
* @dev Only callable by the MANAGER role.
*/
function setLockInPeriod(uint8 _classId) external onlyValidShareClass(_classId) onlyRole(RolesLibrary.MANAGER) {
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_REDEEM);
}
/**
* @notice Sets the minimum redeem amount to the queued value after the timelock period.
* @param _classId The ID of the share class to set the minimum redeem amount for.
* @dev Only callable by the MANAGER role.
*/
function setMinRedeemAmount(uint8 _classId) external onlyValidShareClass(_classId) onlyRole(RolesLibrary.MANAGER) {
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_REDEEM);
}
/**
* @notice Sets the management fee to the queued value after the timelock period.
* @param _classId The ID of the share class to set the management fee for.
* @dev Only callable by the OPERATIONS_MULTISIG role.
*/
function setManagementFee(uint8 _classId)
external
onlyValidShareClass(_classId)
onlyRole(RolesLibrary.OPERATIONS_MULTISIG)
{
routeToModule(ModulesLibrary.FEE_MANAGER);
}
/**
* @notice Sets the performance fee to the queued value after the timelock period.
* @param _classId The ID of the share class to set the performance fee for.
* @dev Only callable by the OPERATIONS_MULTISIG role.
*/
function setPerformanceFee(uint8 _classId)
external
onlyValidShareClass(_classId)
onlyRole(RolesLibrary.OPERATIONS_MULTISIG)
{
routeToModule(ModulesLibrary.FEE_MANAGER);
}
/*//////////////////////////////////////////////////////////////
FEE FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Collects all pending fees.
* @return _managementFeesToCollect The total management fees collected.
* @return _performanceFeesToCollect The total performance fees collected.
* @dev Only callable by the ACCOUNTANT role.
*/
function collectFees()
external
onlyRole(RolesLibrary.ACCOUNTANT)
returns (uint256 _managementFeesToCollect, uint256 _performanceFeesToCollect)
{
routeToModule(ModulesLibrary.FEE_MANAGER);
}
/*//////////////////////////////////////////////////////////////
DEPOSIT FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Requests a deposit of assets.
* @param _requestDepositParams The parameters for the deposit request.
* @return _batchId The batch ID of the deposit.
* @dev Only callable when the deposit request flow is not paused.
*/
function requestDeposit(IEigenYieldsVaultDeposit.RequestDepositParams calldata _requestDepositParams)
external
onlyValidShareClass(_requestDepositParams.classId)
whenFlowNotPaused(PausableFlows.DEPOSIT_REQUEST_FLOW)
returns (uint48 _batchId)
{
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_DEPOSIT);
}
/**
* @notice Deposits assets synchronously into the vault, minting shares immediately.
* @param _requestDepositParams The parameters for the deposit (same as requestDeposit).
* @return _shares The number of shares minted to the caller.
* @dev Only callable when totalAssets is valid for the specified class.
*/
function syncDeposit(IEigenYieldsVaultDeposit.RequestDepositParams calldata _requestDepositParams)
external
onlyValidShareClass(_requestDepositParams.classId)
whenFlowNotPaused(PausableFlows.DEPOSIT_REQUEST_FLOW)
returns (uint256 _shares)
{
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_DEPOSIT);
}
/**
* @notice Checks if total assets are valid for synchronous operations for a specific class.
* @param _classId The share class ID to check.
* @return true if sync flows are allowed, false otherwise.
*/
function isTotalAssetsValid(uint8 _classId) external view override returns (bool) {
return isAssetsValid(_getStorage(), _classId);
}
/*//////////////////////////////////////////////////////////////
REDEEM FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Requests a redeem of shares.
* @param _redeemRequestParams The parameters for the redeem request.
* @return _batchId The batch ID of the redeem.
* @dev Only callable when the redeem request flow is not paused.
*/
function requestRedeem(IEigenYieldsVaultRedeem.RedeemRequestParams calldata _redeemRequestParams)
external
onlyValidShareClass(_redeemRequestParams.classId)
whenFlowNotPaused(PausableFlows.REDEEM_REQUEST_FLOW)
returns (uint48 _batchId)
{
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_REDEEM);
}
/**
* @notice Redeems shares synchronously from the vault, transferring assets immediately.
* @param _redeemRequestParams The parameters for the redeem (same as requestRedeem).
* @return _assets The amount of assets transferred to the caller.
* @dev Only callable when totalAssets is valid.
*/
function syncRedeem(IEigenYieldsVaultRedeem.RedeemRequestParams calldata _redeemRequestParams)
external
onlyValidShareClass(_redeemRequestParams.classId)
whenFlowNotPaused(PausableFlows.REDEEM_REQUEST_FLOW)
returns (uint256 _assets)
{
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_REDEEM);
}
/**
* @notice Withdraws the redeemable amount for the user.
* @dev Only callable when the withdraw flow is not paused.
*/
function withdrawRedeemableAmount() external whenFlowNotPaused(PausableFlows.WITHDRAW_FLOW) {
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_REDEEM);
}
/**
* @notice Withdraws excess assets from the vault and sends back to custodian.
* @dev Only callable by the MANAGER role.
*/
function withdrawExcessAssets() external onlyRole(RolesLibrary.MANAGER) {
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_REDEEM);
}
/*//////////////////////////////////////////////////////////////
SETTLEMENT FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Settles all pending deposits up to the current batch.
* @param _settlementParams The parameters for the settlement.
* @dev Only callable by the ORACLE role.
*/
function settleDeposit(IEigenYieldsVaultSettlement.SettlementParams calldata _settlementParams)
external
onlyRole(RolesLibrary.ORACLE)
onlyValidShareClass(_settlementParams.classId)
whenFlowNotPaused(PausableFlows.SETTLE_DEPOSIT_FLOW)
{
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_SETTLEMENT);
}
/**
* @notice Settles all pending redeems up to the current batch.
* @param _settlementParams The parameters for the settlement.
* @dev Only callable by the ORACLE role.
*/
function settleRedeem(IEigenYieldsVaultSettlement.SettlementParams calldata _settlementParams)
external
onlyRole(RolesLibrary.ORACLE)
onlyValidShareClass(_settlementParams.classId)
whenFlowNotPaused(PausableFlows.SETTLE_REDEEM_FLOW)
{
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_SETTLEMENT);
}
/**
* @notice Forces a redeem for a user.
* @param _user The user to force redeem for.
* @dev Only callable by the MANAGER role.
*/
function forceRedeem(address _user) external onlyRole(RolesLibrary.MANAGER) {
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_SETTLEMENT);
}
/**
* @notice Queues a new sync expiration batches value to be set after the timelock period.
* @param _expirationBatches The number of batches sync flows remain valid.
* @dev Only callable by the MANAGER role.
* @dev Setting _expirationBatches to 0 will disable sync flows (only valid in the exact batch where settlement occurred).
*/
function queueSyncExpirationBatches(uint48 _expirationBatches) external onlyRole(RolesLibrary.MANAGER) {
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_SETTLEMENT);
}
/**
* @notice Sets the sync expiration batches to the queued value after the timelock period.
* @dev Only callable by the MANAGER role.
*/
function setSyncExpirationBatches() external onlyRole(RolesLibrary.MANAGER) {
routeToModule(ModulesLibrary.EIGEN_YIELDS_VAULT_SETTLEMENT);
}
/*//////////////////////////////////////////////////////////////
MIGRATION FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Migrates the operations multisig.
* @param _newOperationsMultisig The new operations multisig address.
* @dev Only callable by the VAULT_FACTORY role.
*/
function migrateOperationsMultisig(address _newOperationsMultisig) external onlyRole(RolesLibrary.VAULT_FACTORY) {
routeToModule(ModulesLibrary.MIGRATION_MANAGER);
}
/**
* @notice Migrates the oracle.
* @param _newOracle The new oracle address.
* @dev Only callable by the VAULT_FACTORY role.
*/
function migrateOracle(address _newOracle) external onlyRole(RolesLibrary.VAULT_FACTORY) {
routeToModule(ModulesLibrary.MIGRATION_MANAGER);
}
/**
* @notice Migrates the guardian.
* @param _newGuardian The new guardian address.
* @dev Only callable by the VAULT_FACTORY role.
*/
function migrateGuardian(address _newGuardian) external onlyRole(RolesLibrary.VAULT_FACTORY) {
routeToModule(ModulesLibrary.MIGRATION_MANAGER);
}
/**
* @notice Migrates the authentication signer.
* @param _newAuthSigner The new authentication signer address.
* @dev Only callable by the VAULT_FACTORY role.
*/
function migrateAuthSigner(address _newAuthSigner) external onlyRole(RolesLibrary.VAULT_FACTORY) {
routeToModule(ModulesLibrary.MIGRATION_MANAGER);
}
/**
* @notice Migrates the module implementation.
* @param _module The module selector to migrate.
* @param _newImplementation The new implementation address for the module.
* @dev Only callable by the VAULT_FACTORY role.
*/
function migrateModules(bytes4 _module, address _newImplementation) external onlyRole(RolesLibrary.VAULT_FACTORY) {
routeToModule(ModulesLibrary.MIGRATION_MANAGER);
}
/*//////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @dev Sets up vault storage, roles, and the default share class during proxy initialization.
* @param initParams Struct containing all initialization parameters.
*/
function bootstrapVault(InitializationParams calldata initParams) internal onlyInitializing {
EigenYieldsVaultStorageData storage sd = _getStorage();
__AccessControl_init();
// Validate that no required address is zero and fee/amount params are within bounds
bool addressesValid = initParams.operationsMultisig != address(0) && initParams.vaultFactory != address(0)
&& initParams.oracle != address(0) && initParams.guardian != address(0)
&& initParams.authSigner != address(0) && initParams.userInitializationParams.underlyingToken != address(0)
&& initParams.userInitializationParams.custodian != address(0) && initParams.accountant != address(0)
&& initParams.moduleInitializationParams.eigenYieldsVaultDepositImplementation != address(0)
&& initParams.moduleInitializationParams.eigenYieldsVaultRedeemImplementation != address(0)
&& initParams.moduleInitializationParams.eigenYieldsVaultSettlementImplementation != address(0)
&& initParams.moduleInitializationParams.feeManagerImplementation != address(0)
&& initParams.moduleInitializationParams.migrationManagerImplementation != address(0);
bool paramsValid = initParams.userInitializationParams.shareClassParams.managementFee <= MAXIMUM_MANAGEMENT_FEE
&& initParams.userInitializationParams.shareClassParams.performanceFee <= MAXIMUM_PERFORMANCE_FEE
&& initParams.userInitializationParams.shareClassParams.minDepositAmount != 0
&& initParams.userInitializationParams.shareClassParams.minRedeemAmount != 0;
if (!addressesValid || !paramsValid) {
revert InvalidInitializationParams();
}
// Persist core configuration
sd.operationsMultisig = initParams.operationsMultisig;
sd.manager = initParams.manager;
sd.oracle = initParams.oracle;
sd.guardian = initParams.guardian;
sd.authSigner = initParams.authSigner;
sd.accountant = initParams.accountant;
sd.syncExpirationBatches = initParams.userInitializationParams.syncExpirationBatches;
sd.name = initParams.userInitializationParams.name;
sd.underlyingToken = initParams.userInitializationParams.underlyingToken;
sd.custodian = initParams.userInitializationParams.custodian;
sd.isDepositAuthEnabled = true;
sd.isSettlementAuthEnabled = true;
sd.startTimeStamp = Time.timestamp();
// Register module implementations
sd.moduleImplementations[ModulesLibrary.EIGEN_YIELDS_VAULT_DEPOSIT] =
initParams.moduleInitializationParams.eigenYieldsVaultDepositImplementation;
sd.moduleImplementations[ModulesLibrary.EIGEN_YIELDS_VAULT_REDEEM] =
initParams.moduleInitializationParams.eigenYieldsVaultRedeemImplementation;
sd.moduleImplementations[ModulesLibrary.EIGEN_YIELDS_VAULT_SETTLEMENT] =
initParams.moduleInitializationParams.eigenYieldsVaultSettlementImplementation;
sd.moduleImplementations[ModulesLibrary.FEE_MANAGER] =
initParams.moduleInitializationParams.feeManagerImplementation;
sd.moduleImplementations[ModulesLibrary.MIGRATION_MANAGER] =
initParams.moduleInitializationParams.migrationManagerImplementation;
// Grant access control roles
_grantRole(RolesLibrary.OPERATIONS_MULTISIG, initParams.operationsMultisig);
_grantRole(RolesLibrary.VAULT_FACTORY, initParams.vaultFactory);
_grantRole(RolesLibrary.MANAGER, initParams.manager);
_grantRole(RolesLibrary.ORACLE, initParams.oracle);
_grantRole(RolesLibrary.GUARDIAN, initParams.guardian);
_grantRole(RolesLibrary.ACCOUNTANT, initParams.accountant);
// Initialize pausable flow roles
initDepositRoles(initParams.manager, initParams.guardian, initParams.operationsMultisig);
initRedeemRoles(initParams.manager, initParams.guardian, initParams.operationsMultisig);
// Initialize reentrancy guard
__ReentrancyGuard_init();
// Create the default share class
addShareClass(sd, initParams.userInitializationParams.shareClassParams);
}
/**
* @dev Registers a new share class and initialises its lead series.
* @param sd The vault storage struct.
* @param shareClassParams The parameters for the new share class.
* @return classId The ID assigned to the new share class.
*/
function addShareClass(EigenYieldsVaultStorageData storage sd, ShareClassParams memory shareClassParams)
internal
returns (uint8 classId)
{
// assign next class id
classId = ++sd.shareClassesId;
// persist share class configuration
IEigenYieldsVault.ShareClass storage shareClass = sd.shareClasses[classId];
shareClass.shareClassParams = shareClassParams;
// initialise lead series high water mark
shareClass.shareSeries[SeriesAccounting.LEAD_SERIES_ID].highWaterMark = SeriesAccounting.PRICE_DENOMINATOR;
emit ShareClassCreated(classId, shareClassParams);
return classId;
}
/**
* @dev Forwards the current call to the implementation registered for the given module selector.
* Uses assembly delegatecall so calldata is passed through verbatim.
* @param module The four-byte module selector used to look up the implementation address.
*/
function routeToModule(bytes4 module) internal {
_delegate(module);
}
/**
* @dev Low-level delegatecall dispatcher. Passes full calldata to the module implementation
* and propagates the return value or revert reason unchanged.
* @param _module The module selector used to resolve the implementation address.
*/
function _delegate(bytes4 _module) internal {
address _implementation = _getStorage().moduleImplementations[_module];
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), _implementation, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "@openzeppelin/contracts/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 {
}
/// @inheritdoc IERC165
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` from `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;
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "@openzeppelin/contracts/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;
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "@openzeppelin/contracts/utils/StorageSlot.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
* by the {ReentrancyGuardTransient} variant in v6.0.
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
using StorageSlot for bytes32;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
/**
* @dev A `view` only version of {nonReentrant}. Use to block view functions
* from being called, preventing reading from inconsistent contract state.
*
* CAUTION: This is a "view" modifier and does not change the reentrancy
* status. Use it only on view functions. For payable or non-payable functions,
* use the standard {nonReentrant} modifier instead.
*/
modifier nonReentrantView() {
_nonReentrantBeforeView();
_;
}
function _nonReentrantBeforeView() private view {
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "@openzeppelin/contracts/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 {
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
lib/openzeppelin-contracts/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)
pragma solidity >=0.8.4;
/**
* @dev External interface of AccessControl declared to support ERC-165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted to signal this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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 reinitialization) 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 Pointer to storage slot. Allows integrators to override it with a custom storage location.
*
* NOTE: Consider following the ERC-7201 formula to derive storage locations.
*/
function _initializableStorageSlot() internal pure virtual returns (bytes32) {
return INITIALIZABLE_STORAGE;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
bytes32 slot = _initializableStorageSlot();
assembly {
$.slot := slot
}
}
}
lib/openzeppelin-contracts/contracts/utils/Arrays.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Arrays.sol)
// This file was procedurally generated from scripts/generate/templates/Arrays.js.
pragma solidity ^0.8.20;
import {Comparators} from "./Comparators.sol";
import {SlotDerivation} from "./SlotDerivation.sol";
import {StorageSlot} from "./StorageSlot.sol";
import {Math} from "./math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
using SlotDerivation for bytes32;
using StorageSlot for bytes32;
/**
* @dev Sort an array of uint256 (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
uint256[] memory array,
function(uint256, uint256) pure returns (bool) comp
) internal pure returns (uint256[] memory) {
_quickSort(_begin(array), _end(array), comp);
return array;
}
/**
* @dev Variant of {sort} that sorts an array of uint256 in increasing order.
*/
function sort(uint256[] memory array) internal pure returns (uint256[] memory) {
sort(array, Comparators.lt);
return array;
}
/**
* @dev Sort an array of address (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
address[] memory array,
function(address, address) pure returns (bool) comp
) internal pure returns (address[] memory) {
sort(_castToUint256Array(array), _castToUint256Comp(comp));
return array;
}
/**
* @dev Variant of {sort} that sorts an array of address in increasing order.
*/
function sort(address[] memory array) internal pure returns (address[] memory) {
sort(_castToUint256Array(array), Comparators.lt);
return array;
}
/**
* @dev Sort an array of bytes32 (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
bytes32[] memory array,
function(bytes32, bytes32) pure returns (bool) comp
) internal pure returns (bytes32[] memory) {
sort(_castToUint256Array(array), _castToUint256Comp(comp));
return array;
}
/**
* @dev Variant of {sort} that sorts an array of bytes32 in increasing order.
*/
function sort(bytes32[] memory array) internal pure returns (bytes32[] memory) {
sort(_castToUint256Array(array), Comparators.lt);
return array;
}
/**
* @dev Performs a quick sort of a segment of memory. The segment sorted starts at `begin` (inclusive), and stops
* at end (exclusive). Sorting follows the `comp` comparator.
*
* Invariant: `begin <= end`. This is the case when initially called by {sort} and is preserved in subcalls.
*
* IMPORTANT: Memory locations between `begin` and `end` are not validated/zeroed. This function should
* be used only if the limits are within a memory array.
*/
function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure {
unchecked {
if (end - begin < 0x40) return;
// Use first element as pivot
uint256 pivot = _mload(begin);
// Position where the pivot should be at the end of the loop
uint256 pos = begin;
for (uint256 it = begin + 0x20; it < end; it += 0x20) {
if (comp(_mload(it), pivot)) {
// If the value stored at the iterator's position comes before the pivot, we increment the
// position of the pivot and move the value there.
pos += 0x20;
_swap(pos, it);
}
}
_swap(begin, pos); // Swap pivot into place
_quickSort(begin, pos, comp); // Sort the left side of the pivot
_quickSort(pos + 0x20, end, comp); // Sort the right side of the pivot
}
}
/**
* @dev Pointer to the memory location of the first element of `array`.
*/
function _begin(uint256[] memory array) private pure returns (uint256 ptr) {
assembly ("memory-safe") {
ptr := add(array, 0x20)
}
}
/**
* @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word
* that comes just after the last element of the array.
*/
function _end(uint256[] memory array) private pure returns (uint256 ptr) {
unchecked {
return _begin(array) + array.length * 0x20;
}
}
/**
* @dev Load memory word (as a uint256) at location `ptr`.
*/
function _mload(uint256 ptr) private pure returns (uint256 value) {
assembly {
value := mload(ptr)
}
}
/**
* @dev Swaps the elements memory location `ptr1` and `ptr2`.
*/
function _swap(uint256 ptr1, uint256 ptr2) private pure {
assembly {
let value1 := mload(ptr1)
let value2 := mload(ptr2)
mstore(ptr1, value2)
mstore(ptr2, value1)
}
}
/// @dev Helper: low level cast address memory array to uint256 memory array
function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast bytes32 memory array to uint256 memory array
function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast address comp function to uint256 comp function
function _castToUint256Comp(
function(address, address) pure returns (bool) input
) private pure returns (function(uint256, uint256) pure returns (bool) output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast bytes32 comp function to uint256 comp function
function _castToUint256Comp(
function(bytes32, bytes32) pure returns (bool) input
) private pure returns (function(uint256, uint256) pure returns (bool) output) {
assembly {
output := input
}
}
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* NOTE: The `array` is expected to be sorted in ascending order, and to
* contain no repeated elements.
*
* IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks
* support for repeated elements in the array. The {lowerBound} function should
* be used instead.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && unsafeAccess(array, low - 1).value == element) {
return low - 1;
} else {
return low;
}
}
/**
* @dev Searches an `array` sorted in ascending order and returns the first
* index that contains a value greater or equal than `element`. If no such index
* exists (i.e. all values in the array are strictly less than `element`), the array
* length is returned. Time complexity O(log n).
*
* See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
*/
function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value < element) {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
} else {
high = mid;
}
}
return low;
}
/**
* @dev Searches an `array` sorted in ascending order and returns the first
* index that contains a value strictly greater than `element`. If no such index
* exists (i.e. all values in the array are strictly less than `element`), the array
* length is returned. Time complexity O(log n).
*
* See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].
*/
function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value > element) {
high = mid;
} else {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
}
}
return low;
}
/**
* @dev Same as {lowerBound}, but with an array in memory.
*/
function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeMemoryAccess(array, mid) < element) {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
} else {
high = mid;
}
}
return low;
}
/**
* @dev Same as {upperBound}, but with an array in memory.
*/
function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeMemoryAccess(array, mid) > element) {
high = mid;
} else {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
}
}
return low;
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getAddressSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getBytes32Slot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getUint256Slot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(bytes[] storage arr, uint256 pos) internal pure returns (StorageSlot.BytesSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getBytesSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(string[] storage arr, uint256 pos) internal pure returns (StorageSlot.StringSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getStringSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(bytes[] memory arr, uint256 pos) internal pure returns (bytes memory res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(string[] memory arr, uint256 pos) internal pure returns (string memory res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(address[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(bytes32[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(uint256[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(bytes[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(string[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
}
lib/openzeppelin-contracts/contracts/utils/Bytes.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Bytes.sol)
pragma solidity ^0.8.24;
import {Math} from "./math/Math.sol";
/**
* @dev Bytes operations.
*/
library Bytes {
/**
* @dev Forward search for `s` in `buffer`
* * If `s` is present in the buffer, returns the index of the first instance
* * If `s` is not present in the buffer, returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf[Javascript's `Array.indexOf`]
*/
function indexOf(bytes memory buffer, bytes1 s) internal pure returns (uint256) {
return indexOf(buffer, s, 0);
}
/**
* @dev Forward search for `s` in `buffer` starting at position `pos`
* * If `s` is present in the buffer (at or after `pos`), returns the index of the next instance
* * If `s` is not present in the buffer (at or after `pos`), returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf[Javascript's `Array.indexOf`]
*/
function indexOf(bytes memory buffer, bytes1 s, uint256 pos) internal pure returns (uint256) {
uint256 length = buffer.length;
for (uint256 i = pos; i < length; ++i) {
if (bytes1(_unsafeReadBytesOffset(buffer, i)) == s) {
return i;
}
}
return type(uint256).max;
}
/**
* @dev Backward search for `s` in `buffer`
* * If `s` is present in the buffer, returns the index of the last instance
* * If `s` is not present in the buffer, returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf[Javascript's `Array.lastIndexOf`]
*/
function lastIndexOf(bytes memory buffer, bytes1 s) internal pure returns (uint256) {
return lastIndexOf(buffer, s, type(uint256).max);
}
/**
* @dev Backward search for `s` in `buffer` starting at position `pos`
* * If `s` is present in the buffer (at or before `pos`), returns the index of the previous instance
* * If `s` is not present in the buffer (at or before `pos`), returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf[Javascript's `Array.lastIndexOf`]
*/
function lastIndexOf(bytes memory buffer, bytes1 s, uint256 pos) internal pure returns (uint256) {
unchecked {
uint256 length = buffer.length;
for (uint256 i = Math.min(Math.saturatingAdd(pos, 1), length); i > 0; --i) {
if (bytes1(_unsafeReadBytesOffset(buffer, i - 1)) == s) {
return i - 1;
}
}
return type(uint256).max;
}
}
/**
* @dev Copies the content of `buffer`, from `start` (included) to the end of `buffer` into a new bytes object in
* memory.
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
*/
function slice(bytes memory buffer, uint256 start) internal pure returns (bytes memory) {
return slice(buffer, start, buffer.length);
}
/**
* @dev Copies the content of `buffer`, from `start` (included) to `end` (excluded) into a new bytes object in
* memory. The `end` argument is truncated to the length of the `buffer`.
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
*/
function slice(bytes memory buffer, uint256 start, uint256 end) internal pure returns (bytes memory) {
// sanitize
uint256 length = buffer.length;
end = Math.min(end, length);
start = Math.min(start, end);
// allocate and copy
bytes memory result = new bytes(end - start);
assembly ("memory-safe") {
mcopy(add(result, 0x20), add(add(buffer, 0x20), start), sub(end, start))
}
return result;
}
/**
* @dev Moves the content of `buffer`, from `start` (included) to the end of `buffer` to the start of that buffer.
*
* NOTE: This function modifies the provided buffer in place. If you need to preserve the original buffer, use {slice} instead
*/
function splice(bytes memory buffer, uint256 start) internal pure returns (bytes memory) {
return splice(buffer, start, buffer.length);
}
/**
* @dev Moves the content of `buffer`, from `start` (included) to end (excluded) to the start of that buffer. The
* `end` argument is truncated to the length of the `buffer`.
*
* NOTE: This function modifies the provided buffer in place. If you need to preserve the original buffer, use {slice} instead
*/
function splice(bytes memory buffer, uint256 start, uint256 end) internal pure returns (bytes memory) {
// sanitize
uint256 length = buffer.length;
end = Math.min(end, length);
start = Math.min(start, end);
// allocate and copy
assembly ("memory-safe") {
mcopy(add(buffer, 0x20), add(add(buffer, 0x20), start), sub(end, start))
mstore(buffer, sub(end, start))
}
return buffer;
}
/**
* @dev Concatenate an array of bytes into a single bytes object.
*
* For fixed bytes types, we recommend using the solidity built-in `bytes.concat` or (equivalent)
* `abi.encodePacked`.
*
* NOTE: this could be done in assembly with a single loop that expands starting at the FMP, but that would be
* significantly less readable. It might be worth benchmarking the savings of the full-assembly approach.
*/
function concat(bytes[] memory buffers) internal pure returns (bytes memory) {
uint256 length = 0;
for (uint256 i = 0; i < buffers.length; ++i) {
length += buffers[i].length;
}
bytes memory result = new bytes(length);
uint256 offset = 0x20;
for (uint256 i = 0; i < buffers.length; ++i) {
bytes memory input = buffers[i];
assembly ("memory-safe") {
mcopy(add(result, offset), add(input, 0x20), mload(input))
}
unchecked {
offset += input.length;
}
}
return result;
}
/**
* @dev Returns true if the two byte buffers are equal.
*/
function equal(bytes memory a, bytes memory b) internal pure returns (bool) {
return a.length == b.length && keccak256(a) == keccak256(b);
}
/**
* @dev Reverses the byte order of a bytes32 value, converting between little-endian and big-endian.
* Inspired in https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel[Reverse Parallel]
*/
function reverseBytes32(bytes32 value) internal pure returns (bytes32) {
value = // swap bytes
((value >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |
((value & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
value = // swap 2-byte long pairs
((value >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |
((value & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
value = // swap 4-byte long pairs
((value >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |
((value & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);
value = // swap 8-byte long pairs
((value >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |
((value & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);
return (value >> 128) | (value << 128); // swap 16-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 128-bit values.
function reverseBytes16(bytes16 value) internal pure returns (bytes16) {
value = // swap bytes
((value & 0xFF00FF00FF00FF00FF00FF00FF00FF00) >> 8) |
((value & 0x00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
value = // swap 2-byte long pairs
((value & 0xFFFF0000FFFF0000FFFF0000FFFF0000) >> 16) |
((value & 0x0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
value = // swap 4-byte long pairs
((value & 0xFFFFFFFF00000000FFFFFFFF00000000) >> 32) |
((value & 0x00000000FFFFFFFF00000000FFFFFFFF) << 32);
return (value >> 64) | (value << 64); // swap 8-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 64-bit values.
function reverseBytes8(bytes8 value) internal pure returns (bytes8) {
value = ((value & 0xFF00FF00FF00FF00) >> 8) | ((value & 0x00FF00FF00FF00FF) << 8); // swap bytes
value = ((value & 0xFFFF0000FFFF0000) >> 16) | ((value & 0x0000FFFF0000FFFF) << 16); // swap 2-byte long pairs
return (value >> 32) | (value << 32); // swap 4-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 32-bit values.
function reverseBytes4(bytes4 value) internal pure returns (bytes4) {
value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8); // swap bytes
return (value >> 16) | (value << 16); // swap 2-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 16-bit values.
function reverseBytes2(bytes2 value) internal pure returns (bytes2) {
return (value >> 8) | (value << 8);
}
/**
* @dev Counts the number of leading zero bits a bytes array. Returns `8 * buffer.length`
* if the buffer is all zeros.
*/
function clz(bytes memory buffer) internal pure returns (uint256) {
for (uint256 i = 0; i < buffer.length; i += 0x20) {
bytes32 chunk = _unsafeReadBytesOffset(buffer, i);
if (chunk != bytes32(0)) {
return Math.min(8 * i + Math.clz(uint256(chunk)), 8 * buffer.length);
}
}
return 8 * buffer.length;
}
/**
* @dev Reads a bytes32 from a bytes array without bounds checking.
*
* NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
* assembly block as such would prevent some optimizations.
*/
function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
value := mload(add(add(buffer, 0x20), offset))
}
}
}
lib/openzeppelin-contracts/contracts/utils/Comparators.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Comparators.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides a set of functions to compare values.
*
* _Available since v5.1._
*/
library Comparators {
function lt(uint256 a, uint256 b) internal pure returns (bool) {
return a < b;
}
function gt(uint256 a, uint256 b) internal pure returns (bool) {
return a > b;
}
}
lib/openzeppelin-contracts/contracts/utils/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
lib/openzeppelin-contracts/contracts/utils/SlotDerivation.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/SlotDerivation.sol)
// This file was procedurally generated from scripts/generate/templates/SlotDerivation.js.
pragma solidity ^0.8.20;
/**
* @dev Library for computing storage (and transient storage) locations from namespaces and deriving slots
* corresponding to standard patterns. The derivation method for array and mapping matches the storage layout used by
* the solidity language / compiler.
*
* See https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays[Solidity docs for mappings and dynamic arrays.].
*
* Example usage:
* ```solidity
* contract Example {
* // Add the library methods
* using StorageSlot for bytes32;
* using SlotDerivation for bytes32;
*
* // Declare a namespace
* string private constant _NAMESPACE = "<namespace>"; // eg. OpenZeppelin.Slot
*
* function setValueInNamespace(uint256 key, address newValue) internal {
* _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value = newValue;
* }
*
* function getValueInNamespace(uint256 key) internal view returns (address) {
* return _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value;
* }
* }
* ```
*
* TIP: Consider using this library along with {StorageSlot}.
*
* NOTE: This library provides a way to manipulate storage locations in a non-standard way. Tooling for checking
* upgrade safety will ignore the slots accessed through this library.
*
* _Available since v5.1._
*/
library SlotDerivation {
/**
* @dev Derive an ERC-7201 slot from a string (namespace).
*/
function erc7201Slot(string memory namespace) internal pure returns (bytes32 slot) {
assembly ("memory-safe") {
mstore(0x00, sub(keccak256(add(namespace, 0x20), mload(namespace)), 1))
slot := and(keccak256(0x00, 0x20), not(0xff))
}
}
/**
* @dev Add an offset to a slot to get the n-th element of a structure or an array.
*/
function offset(bytes32 slot, uint256 pos) internal pure returns (bytes32 result) {
unchecked {
return bytes32(uint256(slot) + pos);
}
}
/**
* @dev Derive the location of the first element in an array from the slot where the length is stored.
*/
function deriveArray(bytes32 slot) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, slot)
result := keccak256(0x00, 0x20)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, address key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, and(key, shr(96, not(0))))
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bool key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, iszero(iszero(key)))
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bytes32 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, uint256 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, int256 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, string memory key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
let length := mload(key)
let begin := add(key, 0x20)
let end := add(begin, length)
let cache := mload(end)
mstore(end, slot)
result := keccak256(begin, add(length, 0x20))
mstore(end, cache)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bytes memory key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
let length := mload(key)
let begin := add(key, 0x20)
let end := add(begin, length)
let cache := mload(end)
mstore(end, slot)
result := keccak256(begin, add(length, 0x20))
mstore(end, cache)
}
}
}
lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
lib/openzeppelin-contracts/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Strings.sol)
pragma solidity ^0.8.24;
import {Math} from "./math/Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {SignedMath} from "./math/SignedMath.sol";
import {Bytes} from "./Bytes.sol";
/**
* @dev String operations.
*/
library Strings {
using SafeCast for *;
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
uint256 private constant SPECIAL_CHARS_LOOKUP =
(1 << 0x08) | // backspace
(1 << 0x09) | // tab
(1 << 0x0a) | // newline
(1 << 0x0c) | // form feed
(1 << 0x0d) | // carriage return
(1 << 0x22) | // double quote
(1 << 0x5c); // backslash
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev The string being parsed contains characters that are not in scope of the given base.
*/
error StringsInvalidChar();
/**
* @dev The string being parsed is not a properly formatted address.
*/
error StringsInvalidAddressFormat();
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly ("memory-safe") {
ptr := add(add(buffer, 0x20), length)
}
while (true) {
ptr--;
assembly ("memory-safe") {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
* representation, according to EIP-55.
*/
function toChecksumHexString(address addr) internal pure returns (string memory) {
bytes memory buffer = bytes(toHexString(addr));
// hash the hex part of buffer (skip length + 2 bytes, length 40)
uint256 hashValue;
assembly ("memory-safe") {
hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
}
for (uint256 i = 41; i > 1; --i) {
// possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
// case shift by xoring with 0x20
buffer[i] ^= 0x20;
}
hashValue >>= 4;
}
return string(buffer);
}
/**
* @dev Converts a `bytes` buffer to its ASCII `string` hexadecimal representation.
*/
function toHexString(bytes memory input) internal pure returns (string memory) {
unchecked {
bytes memory buffer = new bytes(2 * input.length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 0; i < input.length; ++i) {
uint8 v = uint8(input[i]);
buffer[2 * i + 2] = HEX_DIGITS[v >> 4];
buffer[2 * i + 3] = HEX_DIGITS[v & 0xf];
}
return string(buffer);
}
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return Bytes.equal(bytes(a), bytes(b));
}
/**
* @dev Parse a decimal string and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input) internal pure returns (uint256) {
return parseUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
uint256 result = 0;
for (uint256 i = begin; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 9) return (false, 0);
result *= 10;
result += chr;
}
return (true, result);
}
/**
* @dev Parse a decimal string and returns the value as a `int256`.
*
* Requirements:
* - The string must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input) internal pure returns (int256) {
return parseInt(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
(bool success, int256 value) = tryParseInt(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
* the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
}
uint256 private constant ABS_MIN_INT256 = 2 ** 255;
/**
* @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character or if the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, int256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseIntUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseIntUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, int256 value) {
bytes memory buffer = bytes(input);
// Check presence of a negative sign.
bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
bool positiveSign = sign == bytes1("+");
bool negativeSign = sign == bytes1("-");
uint256 offset = (positiveSign || negativeSign).toUint();
(bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);
if (absSuccess && absValue < ABS_MIN_INT256) {
return (true, negativeSign ? -int256(absValue) : int256(absValue));
} else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
return (true, type(int256).min);
} else return (false, 0);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input) internal pure returns (uint256) {
return parseHexUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseHexUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
* invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseHexUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseHexUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
// skip 0x prefix if present
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 offset = hasPrefix.toUint() * 2;
uint256 result = 0;
for (uint256 i = begin + offset; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 15) return (false, 0);
result *= 16;
unchecked {
// Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
// This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.
result += chr;
}
}
return (true, result);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input) internal pure returns (address) {
return parseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
(bool success, address value) = tryParseAddress(input, begin, end);
if (!success) revert StringsInvalidAddressFormat();
return value;
}
/**
* @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
* formatted address. See {parseAddress-string} requirements.
*/
function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
return tryParseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
* formatted address. See {parseAddress-string-uint256-uint256} requirements.
*/
function tryParseAddress(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, address value) {
if (end > bytes(input).length || begin > end) return (false, address(0));
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 expectedLength = 40 + hasPrefix.toUint() * 2;
// check that input is the correct length
if (end - begin == expectedLength) {
// length guarantees that this does not overflow, and value is at most type(uint160).max
(bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
return (s, address(uint160(v)));
} else {
return (false, address(0));
}
}
function _tryParseChr(bytes1 chr) private pure returns (uint8) {
uint8 value = uint8(chr);
// Try to parse `chr`:
// - Case 1: [0-9]
// - Case 2: [a-f]
// - Case 3: [A-F]
// - otherwise not supported
unchecked {
if (value > 47 && value < 58) value -= 48;
else if (value > 96 && value < 103) value -= 87;
else if (value > 64 && value < 71) value -= 55;
else return type(uint8).max;
}
return value;
}
/**
* @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.
*
* WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.
*
* NOTE: This function escapes all unicode characters, and not just the ones in ranges defined in section 2.5 of
* RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). ECMAScript's `JSON.parse` does recover escaped unicode
* characters that are not in this range, but other tooling may provide different results.
*/
function escapeJSON(string memory input) internal pure returns (string memory) {
bytes memory buffer = bytes(input);
bytes memory output = new bytes(2 * buffer.length); // worst case scenario
uint256 outputLength = 0;
for (uint256 i; i < buffer.length; ++i) {
bytes1 char = bytes1(_unsafeReadBytesOffset(buffer, i));
if (((SPECIAL_CHARS_LOOKUP & (1 << uint8(char))) != 0)) {
output[outputLength++] = "\\";
if (char == 0x08) output[outputLength++] = "b";
else if (char == 0x09) output[outputLength++] = "t";
else if (char == 0x0a) output[outputLength++] = "n";
else if (char == 0x0c) output[outputLength++] = "f";
else if (char == 0x0d) output[outputLength++] = "r";
else if (char == 0x5c) output[outputLength++] = "\\";
else if (char == 0x22) {
// solhint-disable-next-line quotes
output[outputLength++] = '"';
}
} else {
output[outputLength++] = char;
}
}
// write the actual length and deallocate unused memory
assembly ("memory-safe") {
mstore(output, outputLength)
mstore(0x40, add(output, shl(5, shr(5, add(outputLength, 63)))))
}
return string(output);
}
/**
* @dev Reads a bytes32 from a bytes array without bounds checking.
*
* NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
* assembly block as such would prevent some optimizations.
*/
function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
value := mload(add(add(buffer, 0x20), offset))
}
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature derives the `address(0)`.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction
* is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash
* invalidation or nonces for replay protection.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(
bytes32 hash,
bytes memory signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly ("memory-safe") {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Variant of {tryRecover} that takes a signature in calldata
*/
function tryRecoverCalldata(
bytes32 hash,
bytes calldata signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, calldata slices would work here, but are
// significantly more expensive (length check) than using calldataload in assembly.
assembly ("memory-safe") {
r := calldataload(signature.offset)
s := calldataload(add(signature.offset, 0x20))
v := byte(0, calldataload(add(signature.offset, 0x40)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction
* is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash
* invalidation or nonces for replay protection.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Variant of {recover} that takes a signature in calldata
*/
function recoverCalldata(bytes32 hash, bytes calldata signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecoverCalldata(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Parse a signature into its `v`, `r` and `s` components. Supports 65-byte and 64-byte (ERC-2098)
* formats. Returns (0,0,0) for invalid signatures. Consider skipping {tryRecover} or {recover} if so.
*/
function parse(bytes memory signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
assembly ("memory-safe") {
// Check the signature length
switch mload(signature)
// - case 65: r,s,v signature (standard)
case 65 {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)
case 64 {
let vs := mload(add(signature, 0x40))
r := mload(add(signature, 0x20))
s := and(vs, shr(1, not(0)))
v := add(shr(255, vs), 27)
}
default {
r := 0
s := 0
v := 0
}
}
}
/**
* @dev Variant of {parse} that takes a signature in calldata
*/
function parseCalldata(bytes calldata signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
assembly ("memory-safe") {
// Check the signature length
switch signature.length
// - case 65: r,s,v signature (standard)
case 65 {
r := calldataload(signature.offset)
s := calldataload(add(signature.offset, 0x20))
v := byte(0, calldataload(add(signature.offset, 0x40)))
}
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)
case 64 {
let vs := calldataload(add(signature.offset, 0x20))
r := calldataload(signature.offset)
s := and(vs, shr(1, not(0)))
v := add(shr(255, vs), 27)
}
default {
r := 0
s := 0
v := 0
}
}
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/cryptography/MessageHashUtils.sol)
pragma solidity ^0.8.24;
import {Strings} from "../Strings.sol";
/**
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
*
* The library provides methods for generating a hash of a message that conforms to the
* https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
* specifications.
*/
library MessageHashUtils {
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing a bytes32 `messageHash` with
* `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
* hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
*
* NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
* keccak256, although any bytes32 value can be safely used because the final digest will
* be re-hashed.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
}
}
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing an arbitrary `message` with
* `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
* hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
return
keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
}
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x00` (data with intended validator).
*
* The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
* `validator` address. Then hashing the result.
*
* See {ECDSA-recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(hex"19_00", validator, data));
}
/**
* @dev Variant of {toDataWithIntendedValidatorHash-address-bytes} optimized for cases where `data` is a bytes32.
*/
function toDataWithIntendedValidatorHash(
address validator,
bytes32 messageHash
) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
mstore(0x00, hex"19_00")
mstore(0x02, shl(96, validator))
mstore(0x16, messageHash)
digest := keccak256(0x00, 0x36)
}
}
/**
* @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).
*
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
*
* See {ECDSA-recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, hex"19_01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
digest := keccak256(ptr, 0x42)
}
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
/**
* @dev Counts the number of leading zero bits in a uint256.
*/
function clz(uint256 x) internal pure returns (uint256) {
return ternary(x == 0, 256, 255 - log2(x));
}
}
lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @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, int256 a, int256 b) internal pure returns (int256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
}
}
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
// Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
// taking advantage of the most significant (or "sign" bit) in two's complement representation.
// This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
// the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
int256 mask = n >> 255;
// A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
return uint256((n + mask) ^ mask);
}
}
}
lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
import {Arrays} from "../Arrays.sol";
import {Math} from "../math/Math.sol";
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
* - Set can be cleared (all elements removed) in O(n).
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* The following types are supported:
*
* - `bytes32` (`Bytes32Set`) since v3.3.0
* - `address` (`AddressSet`) since v3.3.0
* - `uint256` (`UintSet`) since v3.3.0
* - `string` (`StringSet`) since v5.4.0
* - `bytes` (`BytesSet`) since v5.4.0
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: This function has an unbounded cost that scales with set size. Developers should keep in mind that
* using it may render the function uncallable if the set grows to the point where clearing it consumes too much
* gas to fit in a block.
*/
function _clear(Set storage set) private {
uint256 len = _length(set);
for (uint256 i = 0; i < len; ++i) {
delete set._positions[set._values[i]];
}
Arrays.unsafeSetLength(set._values, 0);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
/**
* @dev Return a slice of the set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set, uint256 start, uint256 end) private view returns (bytes32[] memory) {
unchecked {
end = Math.min(end, _length(set));
start = Math.min(start, end);
uint256 len = end - start;
bytes32[] memory result = new bytes32[](len);
for (uint256 i = 0; i < len; ++i) {
result[i] = Arrays.unsafeAccess(set._values, start + i).value;
}
return result;
}
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(Bytes32Set storage set) internal {
_clear(set._inner);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
/**
* @dev Return a slice of the set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set, uint256 start, uint256 end) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner, start, end);
bytes32[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(AddressSet storage set) internal {
_clear(set._inner);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
/**
* @dev Return a slice of the set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set, uint256 start, uint256 end) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner, start, end);
address[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(UintSet storage set) internal {
_clear(set._inner);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
/**
* @dev Return a slice of the set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set, uint256 start, uint256 end) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner, start, end);
uint256[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
struct StringSet {
// Storage of set values
string[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(string value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(StringSet storage set, string memory value) internal returns (bool) {
if (!contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(StringSet storage set, string memory value) internal returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
string memory lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(StringSet storage set) internal {
uint256 len = length(set);
for (uint256 i = 0; i < len; ++i) {
delete set._positions[set._values[i]];
}
Arrays.unsafeSetLength(set._values, 0);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(StringSet storage set, string memory value) internal view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(StringSet storage set) internal view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(StringSet storage set, uint256 index) internal view returns (string memory) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(StringSet storage set) internal view returns (string[] memory) {
return set._values;
}
/**
* @dev Return a slice of the set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(StringSet storage set, uint256 start, uint256 end) internal view returns (string[] memory) {
unchecked {
end = Math.min(end, length(set));
start = Math.min(start, end);
uint256 len = end - start;
string[] memory result = new string[](len);
for (uint256 i = 0; i < len; ++i) {
result[i] = Arrays.unsafeAccess(set._values, start + i).value;
}
return result;
}
}
struct BytesSet {
// Storage of set values
bytes[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(BytesSet storage set, bytes memory value) internal returns (bool) {
if (!contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(BytesSet storage set, bytes memory value) internal returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes memory lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(BytesSet storage set) internal {
uint256 len = length(set);
for (uint256 i = 0; i < len; ++i) {
delete set._positions[set._values[i]];
}
Arrays.unsafeSetLength(set._values, 0);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(BytesSet storage set, bytes memory value) internal view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(BytesSet storage set) internal view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(BytesSet storage set, uint256 index) internal view returns (bytes memory) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(BytesSet storage set) internal view returns (bytes[] memory) {
return set._values;
}
/**
* @dev Return a slice of the set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(BytesSet storage set, uint256 start, uint256 end) internal view returns (bytes[] memory) {
unchecked {
end = Math.min(end, length(set));
start = Math.min(start, end);
uint256 len = end - start;
bytes[] memory result = new bytes[](len);
for (uint256 i = 0; i < len; ++i) {
result[i] = Arrays.unsafeAccess(set._values, start + i).value;
}
return result;
}
}
}
lib/openzeppelin-contracts/contracts/utils/types/Time.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/types/Time.sol)
pragma solidity ^0.8.20;
import {Math} from "../math/Math.sol";
import {SafeCast} from "../math/SafeCast.sol";
/**
* @dev This library provides helpers for manipulating time-related objects.
*
* It uses the following types:
* - `uint48` for timepoints
* - `uint32` for durations
*
* While the library doesn't provide specific types for timepoints and duration, it does provide:
* - a `Delay` type to represent duration that can be programmed to change value automatically at a given point
* - additional helper functions
*/
library Time {
using Time for *;
/**
* @dev Get the block timestamp as a Timepoint.
*/
function timestamp() internal view returns (uint48) {
return SafeCast.toUint48(block.timestamp);
}
/**
* @dev Get the block number as a Timepoint.
*/
function blockNumber() internal view returns (uint48) {
return SafeCast.toUint48(block.number);
}
// ==================================================== Delay =====================================================
/**
* @dev A `Delay` is a uint32 duration that can be programmed to change value automatically at a given point in the
* future. The "effect" timepoint describes when the transitions happens from the "old" value to the "new" value.
* This allows updating the delay applied to some operation while keeping some guarantees.
*
* In particular, the {update} function guarantees that if the delay is reduced, the old delay still applies for
* some time. For example if the delay is currently 7 days to do an upgrade, the admin should not be able to set
* the delay to 0 and upgrade immediately. If the admin wants to reduce the delay, the old delay (7 days) should
* still apply for some time.
*
*
* The `Delay` type is 112 bits long, and packs the following:
*
* ```
* | [uint48]: effect date (timepoint)
* | | [uint32]: value before (duration)
* ↓ ↓ ↓ [uint32]: value after (duration)
* 0xAAAAAAAAAAAABBBBBBBBCCCCCCCC
* ```
*
* NOTE: The {get} and {withUpdate} functions operate using timestamps. Block number based delays are not currently
* supported.
*/
type Delay is uint112;
/**
* @dev Wrap a duration into a Delay to add the one-step "update in the future" feature
*/
function toDelay(uint32 duration) internal pure returns (Delay) {
return Delay.wrap(duration);
}
/**
* @dev Get the value at a given timepoint plus the pending value and effect timepoint if there is a scheduled
* change after this timepoint. If the effect timepoint is 0, then the pending value should not be considered.
*/
function _getFullAt(
Delay self,
uint48 timepoint
) private pure returns (uint32 valueBefore, uint32 valueAfter, uint48 effect) {
(valueBefore, valueAfter, effect) = self.unpack();
return effect <= timepoint ? (valueAfter, 0, 0) : (valueBefore, valueAfter, effect);
}
/**
* @dev Get the current value plus the pending value and effect timepoint if there is a scheduled change. If the
* effect timepoint is 0, then the pending value should not be considered.
*/
function getFull(Delay self) internal view returns (uint32 valueBefore, uint32 valueAfter, uint48 effect) {
return _getFullAt(self, timestamp());
}
/**
* @dev Get the current value.
*/
function get(Delay self) internal view returns (uint32) {
(uint32 delay, , ) = self.getFull();
return delay;
}
/**
* @dev Update a Delay object so that it takes a new duration after a timepoint that is automatically computed to
* enforce the old delay at the moment of the update. Returns the updated Delay object and the timestamp when the
* new delay becomes effective.
*/
function withUpdate(
Delay self,
uint32 newValue,
uint32 minSetback
) internal view returns (Delay updatedDelay, uint48 effect) {
uint32 value = self.get();
uint32 setback = uint32(Math.max(minSetback, value > newValue ? value - newValue : 0));
effect = timestamp() + setback;
return (pack(value, newValue, effect), effect);
}
/**
* @dev Split a delay into its components: valueBefore, valueAfter and effect (transition timepoint).
*/
function unpack(Delay self) internal pure returns (uint32 valueBefore, uint32 valueAfter, uint48 effect) {
uint112 raw = Delay.unwrap(self);
valueAfter = uint32(raw);
valueBefore = uint32(raw >> 32);
effect = uint48(raw >> 64);
return (valueBefore, valueAfter, effect);
}
/**
* @dev pack the components into a Delay object.
*/
function pack(uint32 valueBefore, uint32 valueAfter, uint48 effect) internal pure returns (Delay) {
return Delay.wrap((uint112(effect) << 64) | (uint112(valueBefore) << 32) | uint112(valueAfter));
}
}
src/EigenYieldsPausable.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.27;
/*
_______ _ __ ___ _ _
| ____(_) __ _ ___ _ __ \ \ / (_) ___| | __| |___
| _| | |/ _` |/ _ \ '_ \ \ V /| |/ _ \ |/ _` / __|
| |___| | (_| | __/ | | | | | | | __/ | (_| \__ \
|_____|_|\__, |\___|_| |_| |_| |_|\___|_|\__,_|___/
|___/
*/
import {
AccessControlUpgradeable
} from "openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol";
import {IEigenYieldsPausable} from "@eigenyields-vault/interfaces/IEigenYieldsPausable.sol";
import {PausableFlows} from "@eigenyields-vault/libraries/PausableFlows.sol";
import {RolesLibrary} from "@eigenyields-vault/libraries/RolesLibrary.sol";
import {
EigenYieldsPausableStorage,
EigenYieldsPausableStorageData
} from "@eigenyields-vault/EigenYieldsPausableStorage.sol";
abstract contract EigenYieldsPausable is IEigenYieldsPausable, AccessControlUpgradeable {
/*//////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////*/
/**
* @notice Reverts if the specified flow is currently paused.
* @param _pausableFlow The flow identifier to check.
*/
modifier whenFlowNotPaused(bytes4 _pausableFlow) {
requireActive(_pausableFlow);
_;
}
/**
* @notice Reverts if the specified flow is currently active (not paused).
* @param _pausableFlow The flow identifier to check.
*/
modifier whenFlowPaused(bytes4 _pausableFlow) {
requirePaused(_pausableFlow);
_;
}
/*//////////////////////////////////////////////////////////////
VIEW FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IEigenYieldsPausable
function isFlowPaused(bytes4 _pausableFlow) external view returns (bool _isPaused) {
return loadPauseData().flowsPauseStates[_pausableFlow];
}
/*//////////////////////////////////////////////////////////////
PAUSING FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IEigenYieldsPausable
function pause(bytes4 _pausableFlow) external onlyRole(_pausableFlow) {
setPaused(_pausableFlow);
}
/// @inheritdoc IEigenYieldsPausable
function unpause(bytes4 _pausableFlow) external onlyRole(_pausableFlow) {
clearPaused(_pausableFlow);
}
/// @inheritdoc IEigenYieldsPausable
function pauseAll() external onlyRole(RolesLibrary.GUARDIAN) {
haltAllFlows();
}
/*//////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @dev Marks a flow as paused in storage and emits the pause event.
* @param flowId The flow identifier to pause.
*/
function setPaused(bytes4 flowId) internal {
EigenYieldsPausableStorageData storage ps = loadPauseData();
if (ps.flowsPauseStates[flowId]) revert FlowIsCurrentlyPaused();
ps.flowsPauseStates[flowId] = true;
emit FlowPaused(flowId, msg.sender);
}
/**
* @dev Removes the paused flag from a flow and emits the unpause event.
* @param flowId The flow identifier to unpause.
*/
function clearPaused(bytes4 flowId) internal {
EigenYieldsPausableStorageData storage ps = loadPauseData();
if (!ps.flowsPauseStates[flowId]) revert FlowIsCurrentlyUnpaused();
ps.flowsPauseStates[flowId] = false;
emit FlowUnpaused(flowId, msg.sender);
}
/**
* @dev Sets all known flow pause flags to true in a single operation.
*/
function haltAllFlows() internal {
EigenYieldsPausableStorageData storage ps = loadPauseData();
ps.flowsPauseStates[PausableFlows.DEPOSIT_REQUEST_FLOW] = true;
ps.flowsPauseStates[PausableFlows.REDEEM_REQUEST_FLOW] = true;
ps.flowsPauseStates[PausableFlows.SETTLE_DEPOSIT_FLOW] = true;
ps.flowsPauseStates[PausableFlows.SETTLE_REDEEM_FLOW] = true;
ps.flowsPauseStates[PausableFlows.WITHDRAW_FLOW] = true;
emit AllFlowsPaused();
}
/**
* @dev Reverts if the specified flow is currently paused.
* @param flowId The flow identifier to check.
*/
function requireActive(bytes4 flowId) internal view {
if (loadPauseData().flowsPauseStates[flowId]) revert FlowIsCurrentlyPaused();
}
/**
* @dev Reverts if the specified flow is currently active (not paused).
* @param flowId The flow identifier to check.
*/
function requirePaused(bytes4 flowId) internal view {
if (!loadPauseData().flowsPauseStates[flowId]) revert FlowIsCurrentlyUnpaused();
}
/**
* @dev Sets up roles and initial pause states for the deposit and settle-deposit flows.
* @param manager Address of the manager role.
* @param guardian Address of the guardian role.
* @param operationsMultisig Address of the operations multisig role.
*/
function initDepositRoles(address manager, address guardian, address operationsMultisig) internal onlyInitializing {
loadPauseData().flowsPauseStates[PausableFlows.DEPOSIT_REQUEST_FLOW] = true;
loadPauseData().flowsPauseStates[PausableFlows.SETTLE_DEPOSIT_FLOW] = true;
_grantRole(PausableFlows.DEPOSIT_REQUEST_FLOW, manager);
_grantRole(PausableFlows.DEPOSIT_REQUEST_FLOW, guardian);
_grantRole(PausableFlows.DEPOSIT_REQUEST_FLOW, operationsMultisig);
_grantRole(PausableFlows.SETTLE_DEPOSIT_FLOW, manager);
_grantRole(PausableFlows.SETTLE_DEPOSIT_FLOW, guardian);
_grantRole(PausableFlows.SETTLE_DEPOSIT_FLOW, operationsMultisig);
}
/**
* @dev Sets up roles and initial pause states for the redeem, settle-redeem and withdraw flows.
* @param manager Address of the manager role.
* @param guardian Address of the guardian role.
* @param operationsMultisig Address of the operations multisig role.
*/
function initRedeemRoles(address manager, address guardian, address operationsMultisig) internal onlyInitializing {
loadPauseData().flowsPauseStates[PausableFlows.REDEEM_REQUEST_FLOW] = true;
loadPauseData().flowsPauseStates[PausableFlows.SETTLE_REDEEM_FLOW] = true;
_grantRole(PausableFlows.REDEEM_REQUEST_FLOW, manager);
_grantRole(PausableFlows.REDEEM_REQUEST_FLOW, guardian);
_grantRole(PausableFlows.REDEEM_REQUEST_FLOW, operationsMultisig);
_grantRole(PausableFlows.SETTLE_REDEEM_FLOW, manager);
_grantRole(PausableFlows.SETTLE_REDEEM_FLOW, guardian);
_grantRole(PausableFlows.SETTLE_REDEEM_FLOW, operationsMultisig);
_grantRole(PausableFlows.WITHDRAW_FLOW, guardian);
}
/**
* @dev Loads the pausable storage struct via the storage library.
* @return _sd Reference to the pausable storage data.
*/
function loadPauseData() internal pure returns (EigenYieldsPausableStorageData storage _sd) {
_sd = EigenYieldsPausableStorage.load();
}
}
src/EigenYieldsPausableStorage.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.27;
/*
_______ _ __ ___ _ _
| ____(_) __ _ ___ _ __ \ \ / (_) ___| | __| |___
| _| | |/ _` |/ _ \ '_ \ \ V /| |/ _ \ |/ _` / __|
| |___| | (_| | __/ | | | | | | | __/ | (_| \__ \
|_____|_|\__, |\___|_| |_| |_| |_|\___|_|\__,_|___/
|___/
*/
/**
* @notice Data layout for the EigenYields pausable storage.
* @param flowsPauseStates The pause states for each pausable flow.
*/
struct EigenYieldsPausableStorageData {
mapping(bytes4 _pausableFlow => bool isPaused) flowsPauseStates;
}
library EigenYieldsPausableStorage {
uint256 private constant STORAGE_POSITION = uint256(keccak256("storage.eigenyields.pausable.flows")) - 1;
function load() internal pure returns (EigenYieldsPausableStorageData storage sd) {
uint256 _position = STORAGE_POSITION;
assembly {
sd.slot := _position
}
}
}
src/EigenYieldsVaultBase.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.27;
/*
_______ _ __ ___ _ _
| ____(_) __ _ ___ _ __ \ \ / (_) ___| | __| |___
| _| | |/ _` |/ _ \ '_ \ \ V /| |/ _ \ |/ _` / __|
| |___| | (_| | __/ | | | | | | | __/ | (_| \__ \
|_____|_|\__, |\___|_| |_| |_| |_|\___|_|\__,_|___/
|___/
*/
import {Math} from "openzeppelin-contracts/contracts/utils/math/Math.sol";
import {
ReentrancyGuardUpgradeable
} from "openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol";
import {Time} from "openzeppelin-contracts/contracts/utils/types/Time.sol";
import {IEigenYieldsVault} from "@eigenyields-vault/interfaces/IEigenYieldsVault.sol";
import {ERC4626Math} from "@eigenyields-vault/libraries/ERC4626Math.sol";
import {SeriesAccounting} from "@eigenyields-vault/libraries/SeriesAccounting.sol";
import {EigenYieldsVaultStorage, EigenYieldsVaultStorageData} from "@eigenyields-vault/EigenYieldsVaultStorage.sol";
contract EigenYieldsVaultBase is ReentrancyGuardUpgradeable {
using Math for uint256;
/**
* @notice Maximum allowed management fee expressed in basis points.
*/
uint32 public constant MAXIMUM_MANAGEMENT_FEE = 1000; // 10%
/**
* @notice Maximum allowed performance fee expressed in basis points.
*/
uint32 public constant MAXIMUM_PERFORMANCE_FEE = 5000; // 50%
/**
* @notice Length of each batch cycle measured in seconds.
*/
uint48 public immutable BATCH_DURATION;
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/**
* @notice Raised when constructor receives parameters that fail validation.
*/
error InvalidConstructorParams();
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/**
* @notice Sets up the vault base with a fixed batch duration.
* @param batchDuration_ Number of seconds each batch cycle spans
* @dev Reverts with InvalidConstructorParams if batch duration is zero
*/
constructor(uint48 batchDuration_) {
if (batchDuration_ == 0) {
revert InvalidConstructorParams();
}
BATCH_DURATION = batchDuration_;
}
/*//////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @dev Sums assets across all share classes in the vault.
* @param sd Vault storage reference.
* @return Total asset value held across all classes.
*/
function computeTotalAssets(EigenYieldsVaultStorageData storage sd) internal view returns (uint256) {
uint256 assetSum;
uint8 numClasses = sd.shareClassesId;
for (uint8 classId = 1; classId <= numClasses; classId++) {
IEigenYieldsVault.ShareClass storage shareClass = sd.shareClasses[classId];
assetSum += classAssets(shareClass, classId);
}
return assetSum;
}
/**
* @dev Aggregates assets held in all series belonging to a share class.
* @param shareClass Reference to the share class storage.
* @param classId Identifier of the share class.
* @return Total assets summed over all active series.
*/
function classAssets(IEigenYieldsVault.ShareClass storage shareClass, uint8 classId)
internal
view
returns (uint256)
{
uint32 highestSeriesId = shareClass.shareSeriesId;
uint256 assetSum;
for (uint32 seriesId; seriesId <= highestSeriesId; seriesId++) {
// accumulate assets from each active series
assetSum += seriesAssets(shareClass, seriesId);
if (seriesId == SeriesAccounting.LEAD_SERIES_ID) {
seriesId = shareClass.lastConsolidatedSeriesId;
}
}
return assetSum;
}
/**
* @dev Reads the total assets recorded for a specific series.
* @param shareClass The share class that owns the series.
* @param seriesId Identifier of the series to query.
* @return Asset balance of the specified series.
*/
function seriesAssets(IEigenYieldsVault.ShareClass storage shareClass, uint32 seriesId)
internal
view
returns (uint256)
{
return shareClass.shareSeries[seriesId].totalAssets;
}
/**
* @dev Reads the total shares recorded for a specific series.
* @param shareClass The share class that owns the series.
* @param seriesId Identifier of the series to query.
* @return Share supply of the specified series.
*/
function seriesShares(IEigenYieldsVault.ShareClass storage shareClass, uint32 seriesId)
internal
view
returns (uint256)
{
return shareClass.shareSeries[seriesId].totalShares;
}
/**
* @dev Returns the share balance of a user within a given series.
* @param shareClass The share class that contains the series.
* @param seriesId Identifier of the series.
* @param user Account whose shares are queried.
* @return Share balance of the user in the specified series.
*/
function userSharesInSeries(IEigenYieldsVault.ShareClass storage shareClass, uint32 seriesId, address user)
internal
view
returns (uint256)
{
return shareClass.shareSeries[seriesId].sharesOf[user];
}
/**
* @dev Converts a user's share balance in a series to an equivalent asset value.
* @param shareClass The share class containing the series.
* @param classId Identifier of the share class (not used in the calculation; present for signature consistency).
* @param seriesId Identifier of the series.
* @param user Account to evaluate.
* @return Asset value corresponding to the user's share position.
*/
function userAssetsInSeries(
IEigenYieldsVault.ShareClass storage shareClass,
uint8 classId,
uint32 seriesId,
address user
) internal view returns (uint256) {
return ERC4626Math.previewRedeem(
userSharesInSeries(shareClass, seriesId, user),
seriesAssets(shareClass, seriesId),
seriesShares(shareClass, seriesId)
);
}
/**
* @dev Sums asset values for a user across all series of a share class.
* @param shareClass The share class to scan.
* @param classId Identifier of the share class.
* @param user Account to evaluate.
* @return Aggregate asset value the user holds in this class.
*/
function userClassAssets(IEigenYieldsVault.ShareClass storage shareClass, uint8 classId, address user)
internal
view
returns (uint256)
{
uint256 total;
uint32 highestSeriesId = shareClass.shareSeriesId;
for (uint32 seriesId; seriesId <= highestSeriesId; seriesId++) {
// sum user assets from each active series
total += userAssetsInSeries(shareClass, classId, seriesId, user);
if (seriesId == SeriesAccounting.LEAD_SERIES_ID) {
seriesId = shareClass.lastConsolidatedSeriesId;
}
}
return total;
}
/**
* @dev Computes the sequential batch index for the current timestamp.
* @param sd Vault storage reference.
* @return Index of the current batch.
*/
function currentBatchId(EigenYieldsVaultStorageData storage sd) internal view returns (uint48) {
return (Time.timestamp() - sd.startTimeStamp) / BATCH_DURATION;
}
/**
* @dev Returns the batch ID of the most recent settlement across deposit and redeem flows for a class.
* @param sd Vault storage reference.
* @param classId Identifier of the share class.
* @return The higher of deposit settle ID and redeem settle ID for the class.
*/
function lastSettledBatch(EigenYieldsVaultStorageData storage sd, uint8 classId) internal view returns (uint48) {
IEigenYieldsVault.ShareClass storage shareClass = sd.shareClasses[classId];
uint48 depositSettle = shareClass.depositSettleId;
uint48 redeemSettle = shareClass.redeemSettleId;
return depositSettle > redeemSettle ? depositSettle : redeemSettle;
}
/**
* @dev Checks whether the vault's valuation is recent enough to allow sync operations.
* @param sd Vault storage reference.
* @param classId Identifier of the share class.
* @return True when sync flows are permitted, false otherwise.
*/
function isAssetsValid(EigenYieldsVaultStorageData storage sd, uint8 classId) internal view returns (bool) {
uint48 lastSettlement = lastSettledBatch(sd, classId);
if (lastSettlement == 0) {
return false;
}
uint48 batchNow = currentBatchId(sd);
return batchNow <= lastSettlement + sd.syncExpirationBatches;
}
/**
* @dev Calculates the price per share for the lead series of a share class.
* @param shareClass Reference to the share class.
* @param classId Identifier of the share class.
* @return Price per share of the lead series.
*/
function leadSharePrice(IEigenYieldsVault.ShareClass storage shareClass, uint8 classId)
internal
view
returns (uint256)
{
return calcSharePrice(
seriesAssets(shareClass, SeriesAccounting.LEAD_SERIES_ID),
seriesShares(shareClass, SeriesAccounting.LEAD_SERIES_ID)
);
}
/**
* @dev Sums all queued deposit amounts from the last settled batch up to the current batch.
* @param sd Vault storage reference.
* @param classId Identifier of the share class.
* @return Cumulative unsettled deposit amount pending for the class.
*/
function pendingDeposits(EigenYieldsVaultStorageData storage sd, uint8 classId) internal view returns (uint256) {
uint256 depositSum;
IEigenYieldsVault.ShareClass storage shareClass = sd.shareClasses[classId];
uint48 batchNow = currentBatchId(sd);
uint48 fromBatch = shareClass.depositSettleId;
for (fromBatch; fromBatch <= batchNow; fromBatch++) {
depositSum += shareClass.depositRequests[fromBatch].totalAmountToDeposit;
}
return depositSum;
}
/**
* @dev Aggregates a user's pending deposit requests from the last settled batch to now.
* @param sd Vault storage reference.
* @param classId Identifier of the share class.
* @param user Account to query.
* @return Total pending deposit amount for the user.
*/
function userDepositRequest(EigenYieldsVaultStorageData storage sd, uint8 classId, address user)
internal
view
returns (uint256)
{
uint256 requestTotal;
uint48 batchNow = currentBatchId(sd);
IEigenYieldsVault.ShareClass storage shareClass = sd.shareClasses[classId];
uint48 fromBatch = shareClass.depositSettleId;
for (fromBatch; fromBatch <= batchNow; fromBatch++) {
requestTotal += shareClass.depositRequests[fromBatch].depositRequest[user];
}
return requestTotal;
}
/**
* @dev Calculates how many of a user's assets are locked in pending redeem requests.
* @param shareClass The share class containing the redeem requests.
* @param batchNow The current batch ID.
* @param user Account to evaluate.
* @param totalUserAssets Total asset value the user holds in this class.
* @return pendingAssets The portion of user's assets earmarked for pending redemptions.
*/
function userPendingAssets(
IEigenYieldsVault.ShareClass storage shareClass,
uint48 batchNow,
address user,
uint256 totalUserAssets
) internal view returns (uint256 pendingAssets) {
uint48 fromBatch = shareClass.redeemSettleId;
uint256 remainingAssets = totalUserAssets;
// iterate through unsettled batches and accumulate assets earmarked for redemption
for (uint48 batchId = fromBatch; batchId <= batchNow; batchId++) {
// each redeem request represents a proportion of user assets at settlement time
uint256 batchPendingAssets =
ERC4626Math.previewMintUnits(shareClass.redeemRequests[batchId].redeemRequest[user], remainingAssets);
// remaining assets decrease as prior redeem batches are accounted for
remainingAssets -= batchPendingAssets;
pendingAssets += batchPendingAssets;
}
}
/**
* @dev Derives the price per share given total assets and total shares.
* @param assets Total assets in the series.
* @param shares Total shares outstanding in the series.
* @return Price per share scaled by PRICE_DENOMINATOR.
*/
function calcSharePrice(uint256 assets, uint256 shares) internal pure returns (uint256) {
uint256 price = SeriesAccounting.PRICE_DENOMINATOR;
if (shares > 0) {
price = assets.mulDiv(SeriesAccounting.PRICE_DENOMINATOR, shares, Math.Rounding.Ceil);
}
return price;
}
/**
* @dev Loads the canonical storage struct for the vault via the storage library.
* @return _sd Reference to the vault's storage data.
*/
function _getStorage() internal pure returns (EigenYieldsVaultStorageData storage _sd) {
_sd = EigenYieldsVaultStorage.load();
}
}
src/EigenYieldsVaultStorage.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.27;
/*
_______ _ __ ___ _ _
| ____(_) __ _ ___ _ __ \ \ / (_) ___| | __| |___
| _| | |/ _` |/ _ \ '_ \ \ V /| |/ _ \ |/ _` / __|
| |___| | (_| | __/ | | | | | | | __/ | (_| \__ \
|_____|_|\__, |\___|_| |_| |_| |_|\___|_|\__,_|___/
|___/
*/
import {IEigenYieldsVault} from "@eigenyields-vault/interfaces/IEigenYieldsVault.sol";
import {TimelockRegistry} from "@eigenyields-vault/libraries/TimelockRegistry.sol";
/**
* @notice Data layout for the EigenYields vault storage.
* @param name The name of the vault.
* @param isDepositAuthEnabled Whether the deposit authentication is enabled.
* @param isSettlementAuthEnabled Whether the settlement authentication is enabled.
* @param shareClassesId The number of share classes.
* @param startTimeStamp The start timestamp of the vault.
* @param operationsMultisig The operations multisig address.
* @param manager The manager address.
* @param oracle The oracle address.
* @param guardian The guardian address.
* @param authSigner The auth signer address.
* @param underlyingToken The underlying token address.
* @param custodian The custodian address.
* @param accountant The accountant address.
* @param totalAmountToDeposit The total amount to deposit.
* @param totalAmountToWithdraw The total amount to withdraw.
* @param shareClasses The share classes.
* @param timelocks The timelocks.
* @param moduleImplementations The module implementations.
* @param redeemableAmount The redeemable amount for each user.
*/
struct EigenYieldsVaultStorageData {
string name;
bool isDepositAuthEnabled;
bool isSettlementAuthEnabled;
uint8 shareClassesId;
uint48 startTimeStamp;
address operationsMultisig;
address manager;
address oracle;
address guardian;
address authSigner;
address underlyingToken;
address custodian;
address accountant;
uint256 totalAmountToDeposit;
uint256 totalAmountToWithdraw;
mapping(uint8 classId => IEigenYieldsVault.ShareClass) shareClasses;
mapping(bytes4 => TimelockRegistry.Timelock) timelocks;
mapping(bytes4 => address) moduleImplementations;
mapping(address user => uint256) redeemableAmount;
uint48 syncExpirationBatches;
}
library EigenYieldsVaultStorage {
uint256 private constant STORAGE_POSITION = uint256(keccak256("storage.eigenyields.vault")) - 1;
function load() internal pure returns (EigenYieldsVaultStorageData storage sd) {
uint256 _position = STORAGE_POSITION;
assembly {
sd.slot := _position
}
}
}
src/interfaces/IAccountant.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.27;
/*
_______ _ __ ___ _ _
| ____(_) __ _ ___ _ __ \ \ / (_) ___| | __| |___
| _| | |/ _` |/ _ \ '_ \ \ V /| |/ _ \ |/ _` / __|
| |___| | (_| | __/ | | | | | | | __/ | (_| \__ \
|_____|_|\__, |\___|_| |_| |_| |_|\___|_|\__,_|___/
|___/
*/
import {EnumerableSet} from "openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol";
interface IAccountant {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/**
* @notice Emitted when the operations multisig is set.
* @param operationsMultisig The new operations multisig.
*/
event OperationsMultisigSet(address operationsMultisig);
/**
* @notice Emitted when the vault factory is set.
* @param vaultFactory The new vault factory.
*/
event VaultFactorySet(address vaultFactory);
/**
* @notice Emitted when the EigenYields treasury is set.
* @param eigenYieldsTreasury The new EigenYields treasury.
*/
event EigenYieldsTreasurySet(address eigenYieldsTreasury);
/**
* @notice Emitted when the vault treasury is set.
* @param vault The vault.
* @param vaultTreasury The new vault treasury.
*/
event VaultTreasurySet(address vault, address vaultTreasury);
/**
* @notice Emitted when the management fee cut is set.
* @param vault The vault.
* @param managementFeeCut The new management fee cut.
*/
event ManagementFeeCutSet(address vault, uint32 managementFeeCut);
/**
* @notice Emitted when the performance fee cut is set.
* @param vault The vault.
* @param performanceFeeCut The new performance fee cut.
*/
event PerformanceFeeCutSet(address vault, uint32 performanceFeeCut);
/**
* @notice Emitted when the operator fee cut is set.
* @param vault The vault.
* @param operatorFeeCut The new operator fee cut.
*/
event OperatorFeeCutSet(address vault, uint32 operatorFeeCut);
/**
* @notice Emitted when the operator allocations are set.
* @param vault The vault.
* @param operator The operator.
* @param allocatedAmount The allocated amount.
*/
event OperatorAllocationsSet(address vault, address operator, uint256 allocatedAmount);
/**
* @notice Emitted when operator fees are distributed to an operator.
* @param vault The vault.
* @param operator The operator receiving the fee.
* @param operatorFee The fee amount distributed to the operator.
*/
event OperatorFeeDistributed(address vault, address operator, uint256 operatorFee);
/**
* @notice Emitted when fees are collected.
* @param vault The vault.
* @param managementFeesToCollect The management fees to collect.
* @param performanceFeesToCollect The performance fees to collect.
* @param vaultFee The vault fee split
* @param eigenYieldsFee The EigenYields fee split
* @param operatorsFee The fees for the operators.
*/
event FeesCollected(
address vault,
uint256 managementFeesToCollect,
uint256 performanceFeesToCollect,
uint256 vaultFee,
uint256 eigenYieldsFee,
uint256[] operatorsFee
);
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/**
* @notice Emitted when the initialization params are invalid.
*/
error InvalidInitializationParams();
/**
* @notice Emitted when the vault is invalid.
*/
error InvalidVault();
/**
* @notice Emitted when the manager is invalid.
*/
error InvalidManager();
/**
* @notice Emitted when the vault treasury is invalid.
*/
error InvalidVaultTreasury();
/**
* @notice Emitted when the vault treasury is not set.
*/
error VaultTreasuryNotSet();
/**
* @notice Emitted when fees are not collected.
*/
error FeesNotCollected();
/**
* @notice Emitted when the operator fee cut is invalid.
*/
error InvalidOperatorFeeCut();
/**
* @notice Emitted when the operator allocation input is invalid.
*/
error InvalidOperatorAllocation();
/*//////////////////////////////////////////////////////////////
STRUCTS
//////////////////////////////////////////////////////////////*/
/**
* @notice Initialization params.
* @param operationsMultisig The operations multisig.
* @param eigenYieldsTreasury The EigenYields treasury.
*/
struct InitializationParams {
address operationsMultisig;
address eigenYieldsTreasury;
}
/**
* @notice Operator allocations.
* @param totalOperatorAllocations The total operator allocations.
* @param operators The operators.
* @param allocatedAmount The allocated amount by each operator.
*/
struct OperatorAllocations {
uint256 totalOperatorAllocations;
EnumerableSet.AddressSet operators;
mapping(address operator => uint256 allocatedAmount) allocatedAmount;
}
/*//////////////////////////////////////////////////////////////
VIEW FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Returns the vault treasury of the caller.
* @return The vault treasury.
*/
function vaultTreasury() external view returns (address);
/*//////////////////////////////////////////////////////////////
SETTER FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Initializes the vault treasury.
* @param _vault The vault to initialize the treasury for.
* @param _vaultTreasury The new vault treasury.
*/
function initializeVaultTreasury(address _vault, address _vaultTreasury) external;
/**
* @notice Sets the operations multisig.
* @param _operationsMultisig The new operations multisig.
*/
function setOperationsMultisig(address _operationsMultisig) external;
/**
* @notice Sets the vault factory.
* @param _vaultFactory The new vault factory.
*/
function setVaultFactory(address _vaultFactory) external;
/**
* @notice Sets the EigenYields treasury.
* @param _eigenYieldsTreasury The new EigenYields treasury.
*/
function setEigenYieldsTreasury(address _eigenYieldsTreasury) external;
/**
* @notice Sets the vault treasury.
* @param _vaultTreasury The new vault treasury.
*/
function setVaultTreasury(address _vaultTreasury) external;
/**
* @notice Sets the EigenYields AVS.
* @param _eigenYieldsAvs The new EigenYields AVS.
*/
function setEigenYieldsAvs(address _eigenYieldsAvs) external;
/**
* @notice Sets the management fee cut.
* @param _vault The vault to set the management fee cut for.
* @param _managementFeeCut The new management fee cut.
*/
function setManagementFeeCut(address _vault, uint32 _managementFeeCut) external;
/**
* @notice Sets the performance fee cut.
* @param _vault The vault to set the performance fee cut for.
* @param _performanceFeeCut The new performance fee cut.
*/
function setPerformanceFeeCut(address _vault, uint32 _performanceFeeCut) external;
/**
* @notice Sets the operator fee cut.
* @param _vault The vault to set the operator fee cut for.
* @param _operatorFeeCut The new operator fee cut.
*/
function setOperatorFeeCut(address _vault, uint32 _operatorFeeCut) external;
/**
* @notice Sets the operator allocations.
* @param _vault The vault to set the operator allocations for.
* @param _operator The operator to set the allocations for.
* @param _allocatedAmount The new allocated amount.
*/
function setOperatorAllocations(address _vault, address _operator, uint256 _allocatedAmount) external;
/*//////////////////////////////////////////////////////////////
FEE FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Collects all pending fees from a given vault.
* @param _vault The vault to collect fees from.
*/
function collectFees(address _vault) external;
}
src/interfaces/IEigenYieldsPausable.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.27;
/*
_______ _ __ ___ _ _
| ____(_) __ _ ___ _ __ \ \ / (_) ___| | __| |___
| _| | |/ _` |/ _ \ '_ \ \ V /| |/ _ \ |/ _` / __|
| |___| | (_| | __/ | | | | | | | __/ | (_| \__ \
|_____|_|\__, |\___|_| |_| |_| |_|\___|_|\__,_|___/
|___/
*/
interface IEigenYieldsPausable {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/**
* @notice Emitted when a flow is paused
* @param _pausableFlow The flow identifier
* @param _pauser The address that paused the flow
*/
event FlowPaused(bytes4 _pausableFlow, address _pauser);
/**
* @notice Emitted when a flow is unpaused
* @param _pausableFlow The flow identifier
* @param _unpauser The address that unpaused the flow
*/
event FlowUnpaused(bytes4 _pausableFlow, address _unpauser);
/**
* @notice Emitted when all flows are paused
*/
event AllFlowsPaused();
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/**
* @notice Emitted when a flow is currently paused
*/
error FlowIsCurrentlyPaused();
/**
* @notice Emitted when a flow is currently unpaused
*/
error FlowIsCurrentlyUnpaused();
/*//////////////////////////////////////////////////////////////
VIEW FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Checks if a specific flow is currently paused
* @param _pausableFlow The flow identifier to check
* @return True if the flow is paused, false otherwise
*/
function isFlowPaused(bytes4 _pausableFlow) external view returns (bool);
/*//////////////////////////////////////////////////////////////
PAUSING FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Pauses a specific flow to prevent its execution
* @param _pausableFlow The flow identifier to pause
* @dev Only callable by users with the flow-specific role. Reverts if flow is already paused.
*/
function pause(bytes4 _pausableFlow) external;
/**
* @notice Unpauses a specific flow to allow its execution
* @param _pausableFlow The flow identifier to unpause
* @dev Only callable by users with the flow-specific role. Reverts if flow is not paused.
*/
function unpause(bytes4 _pausableFlow) external;
/**
* @notice Pauses all flows to prevent their execution
* @dev Only callable by users with the guardian role. Reverts if all flows are already paused.
*/
function pauseAll() external;
}
src/interfaces/IEigenYieldsVault.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.27;
/*
_______ _ __ ___ _ _
| ____(_) __ _ ___ _ __ \ \ / (_) ___| | __| |___
| _| | |/ _` |/ _ \ '_ \ \ V /| |/ _ \ |/ _` / __|
| |___| | (_| | __/ | | | | | | | __/ | (_| \__ \
|_____|_|\__, |\___|_| |_| |_| |_|\___|_|\__,_|___/
|___/
*/
import {EnumerableSet} from "openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol";
import {AuthLibrary} from "@eigenyields-vault/libraries/AuthLibrary.sol";
interface IEigenYieldsVault {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/**
* @notice Emitted when the deposit authentication is enabled.
*/
event IsDepositAuthEnabledSet(bool isDepositAuthEnabled);
/**
* @notice Emitted when the settlement authentication is enabled.
*/
event IsSettlementAuthEnabledSet(bool isSettlementAuthEnabled);
/**
* @notice Emitted when the vault treasury is set.
*/
event VaultTreasurySet(address vaultTreasury);
/**
* @notice Emitted when the share class is created.
*/
event ShareClassCreated(uint8 classId, ShareClassParams shareClassParams);
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/**
* @notice Emitted when the initialization params are invalid.
*/
error InvalidInitializationParams();
/**
* @notice Emitted when the auth signer is invalid.
*/
error InvalidAuthSigner();
/**
* @notice Emitted when the share class is invalid.
*/
error InvalidShareClass();
/**
* @notice Emitted when the share series is invalid.
*/
error InvalidShareSeries();
/**
* @notice Emitted when the share class params are invalid.
*/
error InvalidShareClassParams();
/*//////////////////////////////////////////////////////////////
STRUCTS
//////////////////////////////////////////////////////////////*/
/**
* @notice Initialization params.
* @param _operationsMultisig The operations multisig address.
* @param _vaultFactory The vault factory address.
* @param _manager The manager address.
* @param _oracle The oracle address.
* @param _guardian The guardian address.
* @param _authSigner The auth signer address.
* @param _accountant The accountant proxy address.
* @param _userInitializationParams The user initialization params.
* @param _moduleInitializationParams The module initialization params.
*/
struct InitializationParams {
address operationsMultisig;
address vaultFactory;
address manager;
address oracle;
address guardian;
address authSigner;
address accountant;
UserInitializationParams userInitializationParams;
ModuleInitializationParams moduleInitializationParams;
}
/**
* @notice Initialization params provided by the user.
* @param _name The name of the vault.
* @param _configId The config ID of the vault.
* @param _underlyingToken The underlying token address.
* @param _custodian The custodian address in which vault funds are stored.
* @param _vaultTreasury The vault treasury address in which fees are collected.
* @param _syncExpirationBatches The number of batches sync flows remain valid after valuation update.
* @param _shareClassParams The share class params for default share class.
* @param _authSignature The auth signature to deploy the vault.
*/
struct UserInitializationParams {
string name;
string configId;
address underlyingToken;
address custodian;
address vaultTreasury;
uint48 syncExpirationBatches;
ShareClassParams shareClassParams;
AuthLibrary.AuthSignature authSignature;
}
/**
* @notice Initialization params for the modules.
* @param _eigenYieldsVaultDepositImplementation The EigenYields vault deposit implementation address.
* @param _eigenYieldsVaultRedeemImplementation The EigenYields vault redeem implementation address.
* @param _eigenYieldsVaultSettlementImplementation The EigenYields vault settlement implementation address.
* @param _feeManagerImplementation The fee manager implementation address.
* @param _migrationManagerImplementation The migration manager implementation address.
*/
struct ModuleInitializationParams {
address eigenYieldsVaultDepositImplementation;
address eigenYieldsVaultRedeemImplementation;
address eigenYieldsVaultSettlementImplementation;
address feeManagerImplementation;
address migrationManagerImplementation;
}
/**
* @notice Parameters for a share class.
* @param _managementFee The management fee rate in basis points.
* @param _performanceFee The performance fee rate in basis points.
* @param _noticePeriod The notice period in batches.
* @param _lockInPeriod The lock in period in batches.
* @param _minDepositAmount The minimum deposit amount.
* @param _minUserBalance The minimum user balance.
* @param _maxDepositCap The maximum deposit cap.
* @param _minRedeemAmount The minimum redeem amount.
* @dev all amounts are denominated in underlying token decimals.
*/
struct ShareClassParams {
uint32 managementFee;
uint32 performanceFee;
uint48 noticePeriod;
uint48 lockInPeriod;
uint256 minDepositAmount;
uint256 minUserBalance;
uint256 maxDepositCap;
uint256 minRedeemAmount;
}
/**
* @notice Structure for a share class.
* @param _shareSeriesId The number of share series created for the share class.
* @param _lastConsolidatedSeriesId The ID of the last consolidated share series.
* @param _lastFeePaidId The last Batch ID in which fees were paid.
* @param _depositSettleId The last Batch ID in which deposits were settled.
* @param _redeemSettleId The last Batch ID in which redemptions were settled.
* @param _shareClassParams The parameters for the share class.
* @param _shareSeries All share series for the share class.
* @param _depositRequests The deposit requests made for the share class.
* @param _redeemRequests The redemption requests made for the share class.
* @param _userLockInPeriod The lock in period for each user in the share class.
*/
struct ShareClass {
uint32 shareSeriesId;
uint32 lastConsolidatedSeriesId;
uint48 lastFeePaidId;
uint48 depositSettleId;
uint48 redeemSettleId;
ShareClassParams shareClassParams;
mapping(uint32 => ShareSeries) shareSeries;
mapping(uint48 batchId => DepositRequests) depositRequests;
mapping(uint48 batchId => RedeemRequests) redeemRequests;
mapping(address user => uint48) userLockInPeriod;
}
/**
* @notice Structure for a share series.
* @param _totalAssets The total assets in the share series.
* @param _totalShares The total shares in the share series.
* @param _highWaterMark The high water mark of the share series.
* @param _users The users in the share series.
* @param _sharesOf The shares of each user in the share series.
* @dev assets and shares are denominated in underlying token decimals.
* @dev if a share series is consolidated, the values inside this mapping are cleared out.
*/
struct ShareSeries {
uint256 totalAssets;
uint256 totalShares;
uint256 highWaterMark;
EnumerableSet.AddressSet users;
mapping(address => uint256) sharesOf;
}
/**
* @notice Structure for the deposit requests for a share class.
* @param _totalAmountToDeposit The total amount to deposit for the share class.
* @param _usersToDeposit The users to deposit for the share class.
* @param _depositRequest The deposit request for each user in the share class.
* @dev deposit requests are amounts denominated in underlying token decimals.
* @dev deposit request values are cleared out after settlement.
*/
struct DepositRequests {
uint256 totalAmountToDeposit;
EnumerableSet.AddressSet usersToDeposit;
mapping(address => uint256) depositRequest;
}
/**
* @notice Structure for the redemption requests for a share class.
* @param _usersToRedeem The users to redeem for the share class.
* @param _redeemRequest The redemption request for each user in the share class.
* @dev redemption requests are in share units (percentage of remaining total user assets in share class)
* denominated in TOTAL_SHARE_UNITS (1e18).
* @dev redemption request values are cleared out after settlement.
*/
struct RedeemRequests {
EnumerableSet.AddressSet usersToRedeem;
mapping(address => uint256) redeemRequest;
}
/*//////////////////////////////////////////////////////////////
VIEW FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Returns the start time of the vault.
* @return The start time.
*/
function startTimeStamp() external view returns (uint48);
/**
* @notice Returns the current batch ID based on the elapsed time since start.
* @return The current batch ID.
*/
function currentBatch() external view returns (uint48);
/**
* @notice Returns the number of share classes in the vault.
* @return The number of share classes.
*/
function shareClasses() external view returns (uint8);
/**
* @notice Returns the max series ID of the share class.
* @param _classId The ID of the share class.
* @return The max series ID of the share class.
*/
function shareSeriesId(uint8 _classId) external view returns (uint32);
/**
* @notice Returns the last consolidated series ID of the share class.
* @param _classId The ID of the share class.
* @return The last consolidated series ID of the share class.
*/
function lastConsolidatedSeriesId(uint8 _classId) external view returns (uint32);
/**
* @notice Returns the name of the vault.
* @return The name.
*/
function name() external view returns (string memory);
/**
* @notice Returns the manager of the vault.
* @return The manager.
*/
function manager() external view returns (address);
/**
* @notice Returns the underlying token of the vault.
* @return The underlying token.
*/
function underlyingToken() external view returns (address);
/**
* @notice Returns the custodian of the vault.
* @return The custodian.
*/
function custodian() external view returns (address);
/**
* @notice Returns the vault treasury of the vault.
* @return The vault treasury.
*/
function vaultTreasury() external view returns (address);
/**
* @notice Checks if total assets are valid for synchronous operations for a specific class.
* @param _classId The share class ID to check.
* @return true if sync flows are allowed, false otherwise.
*/
function isTotalAssetsValid(uint8 _classId) external view returns (bool);
/**
* @notice Returns the operations multisig of the vault.
* @return The operations multisig.
*/
function operationsMultisig() external view returns (address);
/**
* @notice Returns the oracle of the vault.
* @return The oracle.
*/
function oracle() external view returns (address);
/**
* @notice Returns the guardian of the vault.
* @return The guardian.
*/
function guardian() external view returns (address);
/**
* @notice Returns the KYC authentication signer of the vault.
* @return The KYC authentication signer.
*/
function authSigner() external view returns (address);
/**
* @notice Returns the accountant of the vault.
* @return The accountant.
*/
function accountant() external view returns (address);
/**
* @notice Returns the management fee of the vault.
* @param _classId The ID of the share class.
* @return The management fee.
*/
function managementFee(uint8 _classId) external view returns (uint32);
/**
* @notice Returns the performance fee of the vault.
* @param _classId The ID of the share class.
* @return The performance fee.
*/
function performanceFee(uint8 _classId) external view returns (uint32);
/**
* @notice Returns the notice period of the vault.
* @param _classId The ID of the share class.
* @return The notice period.
*/
function noticePeriod(uint8 _classId) external view returns (uint48);
/**
* @notice Returns the lock in period of the vault.
* @param _classId The ID of the share class.
* @return The lock in period.
*/
function lockInPeriod(uint8 _classId) external view returns (uint48);
/**
* @notice Returns the minimum deposit amount.
* @param _classId The ID of the share class.
* @return The minimum deposit amount of the share class.
*/
function minDepositAmount(uint8 _classId) external view returns (uint256);
/**
* @notice Returns the minimum user balance.
* @param _classId The ID of the share class.
* @return The minimum user balance of the share class.
*/
function minUserBalance(uint8 _classId) external view returns (uint256);
/**
* @notice Returns the maximum deposit cap.
* @param _classId The ID of the share class.
* @return The maximum deposit cap of the share class.
*/
function maxDepositCap(uint8 _classId) external view returns (uint256);
/**
* @notice Returns the minimum redeem amount.
* @param _classId The ID of the share class.
* @return The minimum redeem amount of the share class.
*/
function minRedeemAmount(uint8 _classId) external view returns (uint256);
/**
* @notice Returns the user lock in period.
* @param _classId The ID of the share class.
* @param _user The address of the user.
* @return The user lock in period.
*/
function userLockInPeriod(uint8 _classId, address _user) external view returns (uint48);
/**
* @notice Returns the amount of assets claimable by a user.
* @param _user The address of the user.
* @return The amount of assets claimable by the user.
*/
function redeemableAmount(address _user) external view returns (uint256);
/**
* @notice Returns whether authentication is enabled for deposits.
* @return The status of the authentication for deposits.
*/
function isDepositAuthEnabled() external view returns (bool);
/**
* @notice Returns whether authentication is enabled for settlements.
* @return The status of the authentication for settlements.
*/
function isSettlementAuthEnabled() external view returns (bool);
/**
* @notice Returns the total assets currently held by the vault.
* @return The total assets.
*/
function totalAssets() external view returns (uint256);
/**
* @notice Returns the total assets in the vault for a given class.
* @param _classId The ID of the share class.
* @return The total assets in the vault for the given class.
*/
function totalAssetsOfClass(uint8 _classId) external view returns (uint256[] memory);
/**
* @notice Returns the total assets in the vault for a given class.
* @param _classId The ID of the share class.
* @return The total assets in the vault for the given class.
*/
function totalAssetsPerClass(uint8 _classId) external view returns (uint256);
/**
* @notice Returns the total assets in the vault for a given series.
* @param _classId The ID of the share class.
* @param _seriesId The ID of the share series.
* @return The total assets in the vault for the given series.
*/
function totalAssetsPerSeries(uint8 _classId, uint32 _seriesId) external view returns (uint256);
/**
* @notice Returns the total shares in the vault for a given series.
* @param _classId The ID of the share class.
* @param _seriesId The ID of the share series.
* @return The total shares in the vault for the given series.
*/
function totalSharesPerSeries(uint8 _classId, uint32 _seriesId) external view returns (uint256);
/**
* @notice Returns the total assets of a user in a given class.
* @param _classId The ID of the share class.
* @param _user The address of the user.
* @return The total assets of a user in a given class.
*/
function assetsPerClassOf(uint8 _classId, address _user) external view returns (uint256);
/**
* @notice Returns the amount of assets claimable by a user based on their shares.
* @param _classId The ID of the share class.
* @param _seriesId The ID of the share series.
* @param _user The address of the user.
* @return The amount of assets claimable by the user.
*/
function assetsOf(uint8 _classId, uint32 _seriesId, address _user) external view returns (uint256);
/**
* @notice Returns the number of shares owned by a user.
* @param _classId The ID of the share class.
* @param _seriesId The ID of the share series.
* @param _user The address of the user.
* @return The number of shares owned by the user.
*/
function sharesOf(uint8 _classId, uint32 _seriesId, address _user) external view returns (uint256);
/**
* @notice Returns the current price per share of the vault.
* @param _classId The ID of the share class.
* @param _seriesId The ID of the share series.
* @return The current price per share.
*/
function pricePerShare(uint8 _classId, uint32 _seriesId) external view returns (uint256);
/**
* @notice Returns the current high water mark of the vault.
* @param _classId The ID of the share class.
* @param _seriesId The ID of the share series.
* @return The current high water mark.
*/
function highWaterMark(uint8 _classId, uint32 _seriesId) external view returns (uint256);
/**
* @notice Returns the total amount of unsettled deposit requests for a given class.
* @param _classId The ID of the share class.
* @return The total amount of unsettled deposit requests for the given class.
* @dev Please note that this function will return the deposit amount for all batches including the current batch.
* However, if these deposit requests are settled in this batch, the amount requested in this batch will NOT be settled.
* It will be settled in the next settlement batch. So if you're using this function to check for the deposit request for settlement,
* please be aware of this nuance.
*/
function totalAmountToDeposit(uint8 _classId) external view returns (uint256);
/**
* @notice Returns the total amount of unsettled deposit requests for a given class at a given batch.
* @param _classId The ID of the share class.
* @param _batchId The ID of the batch.
* @return The total amount of unsettled deposit requests for the given class at the given batch.
*/
function totalAmountToDepositAt(uint8 _classId, uint48 _batchId) external view returns (uint256);
/**
* @notice Returns the deposit request of a user.
* @param _classId The ID of the share class.
* @param _user The user to query.
* @return The deposit request of the user.
*/
function depositRequestOf(uint8 _classId, address _user) external view returns (uint256);
/**
* @notice Returns the deposit request of a user at a given batch.
* @param _classId The ID of the share class.
* @param _user The user to query.
* @param _batchId The ID of the batch.
* @return The deposit request of the user at the given batch.
*/
function depositRequestOfAt(uint8 _classId, address _user, uint48 _batchId) external view returns (uint256);
/**
* @notice Returns the redeem request of a user.
* @param _classId The ID of the share class.
* @param _user The user to query.
* @return The redeem request of the user.
*/
function redeemRequestOf(uint8 _classId, address _user) external view returns (uint256);
/**
* @notice Returns the redeem request of a user at a given batch.
* @param _classId The ID of the share class.
* @param _user The user to query.
* @param _batchId The ID of the batch.
* @return The redeem request of the user at the given batch.
*/
function redeemRequestOfAt(uint8 _classId, address _user, uint48 _batchId) external view returns (uint256);
/**
* @notice Returns the users to deposit at a given batch.
* @param _classId The ID of the share class.
* @param _batchId The ID of the batch.
* @return The users to deposit at the given batch.
*/
function usersToDepositAt(uint8 _classId, uint48 _batchId) external view returns (address[] memory);
/**
* @notice Returns the users to redeem at a given batch.
* @param _classId The ID of the share class.
* @param _batchId The ID of the batch.
* @return The users to redeem at the given batch.
*/
function usersToRedeemAt(uint8 _classId, uint48 _batchId) external view returns (address[] memory);
/**
* @notice Returns the total fee amount to collect.
* @return The total fee amount to collect.
*/
function totalFeeAmountToCollect() external view returns (uint256);
/*//////////////////////////////////////////////////////////////
SETTER FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Sets whether authentication is enabled for deposits.
* @param _isDepositAuthEnabled The new status of the authentication for deposits.
*/
function setIsDepositAuthEnabled(bool _isDepositAuthEnabled) external;
/**
* @notice Sets whether authentication is enabled for settlements.
* @param _isSettlementAuthEnabled The new status of the authentication for settlements.
*/
function setIsSettlementAuthEnabled(bool _isSettlementAuthEnabled) external;
/**
* @notice Sets the vault treasury.
* @param _vaultTreasury The new vault treasury.
*/
function setVaultTreasury(address _vaultTreasury) external;
/**
* @notice Creates a new share class.
* @param _shareClassParams The parameters for the share class.
*/
function createShareClass(ShareClassParams memory _shareClassParams) external returns (uint8 _classId);
}
src/interfaces/IEigenYieldsVaultDeposit.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.27;
/*
_______ _ __ ___ _ _
| ____(_) __ _ ___ _ __ \ \ / (_) ___| | __| |___
| _| | |/ _` |/ _ \ '_ \ \ V /| |/ _ \ |/ _` / __|
| |___| | (_| | __/ | | | | | | | __/ | (_| \__ \
|_____|_|\__, |\___|_| |_| |_| |_|\___|_|\__,_|___/
|___/
*/
import {AuthLibrary} from "@eigenyields-vault/libraries/AuthLibrary.sol";
interface IEigenYieldsVaultDeposit {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/**
* @notice Emitted when a new minimum deposit amount is queued.
* @param classId The ID of the share class.
* @param minDepositAmount The new minimum deposit amount.
*/
event NewMinDepositAmountQueued(uint8 classId, uint256 minDepositAmount);
/**
* @notice Emitted when a new minimum user balance is queued.
* @param classId The ID of the share class.
* @param minUserBalance The new minimum user balance.
*/
event NewMinUserBalanceQueued(uint8 classId, uint256 minUserBalance);
/**
* @notice Emitted when a new maximum deposit cap is queued.
* @param classId The ID of the share class.
* @param maxDepositCap The new maximum deposit cap.
*/
event NewMaxDepositCapQueued(uint8 classId, uint256 maxDepositCap);
/**
* @notice Emitted when a new minimum deposit amount is set.
* @param classId The ID of the share class.
* @param minDepositAmount The new minimum deposit amount.
*/
event NewMinDepositAmountSet(uint8 classId, uint256 minDepositAmount);
/**
* @notice Emitted when a new minimum user balance is set.
* @param classId The ID of the share class.
* @param minUserBalance The new minimum user balance.
*/
event NewMinUserBalanceSet(uint8 classId, uint256 minUserBalance);
/**
* @notice Emitted when a new maximum deposit cap is set.
* @param classId The ID of the share class.
* @param maxDepositCap The new maximum deposit cap.
*/
event NewMaxDepositCapSet(uint8 classId, uint256 maxDepositCap);
/**
* @notice Emitted when a deposit request is made.
* @param classId The ID of the share class.
* @param batchId The batch ID of the deposit request.
* @param user The user making the deposit request.
* @param amount The amount of the deposit request.
*/
event DepositRequest(uint8 classId, uint48 batchId, address indexed user, uint256 amount);
/**
* @notice Emitted when a synchronous deposit is made.
* @param classId The ID of the share class.
* @param allocator The address making the deposit.
* @param amount The amount deposited.
* @param shares The number of shares minted.
* @param seriesId The series ID where shares were minted.
* @param batchId The batch ID when the deposit occurred.
* @param totalAssets The total assets in the series after the deposit.
* @param totalShares The total shares in the series after the deposit.
*/
event SyncDeposit(
uint8 indexed classId,
address indexed allocator,
uint256 amount,
uint256 shares,
uint32 seriesId,
uint48 batchId,
uint256 totalAssets,
uint256 totalShares
);
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/**
* @notice Emitted when the minimum deposit amount is invalid.
*/
error InvalidMinDepositAmount();
/**
* @notice Emitted when the deposit is insufficient.
*/
error InsufficientDeposit();
/**
* @notice Emitted when the deposit is less than the minimum deposit amount.
*/
error DepositLessThanMinDepositAmount(uint256 minDepositAmount);
/**
* @notice Emitted when the deposit is less than the minimum user balance.
*/
error DepositLessThanMinUserBalance(uint256 minUserBalance);
/**
* @notice Emitted when the deposit exceeds the maximum deposit cap.
*/
error DepositExceedsMaxDepositCap(uint256 maxDepositCap);
/**
* @notice Emitted when only one request per batch is allowed for deposit.
*/
error OnlyOneRequestPerBatchAllowedForDeposit();
/**
* @notice Emitted when the deposit request fails.
*/
error DepositRequestFailed();
/**
* @notice Emitted when only async deposit is allowed (sync is not valid).
*/
error OnlyAsyncDepositAllowed();
/*//////////////////////////////////////////////////////////////
STRUCTS
//////////////////////////////////////////////////////////////*/
/**
* @notice Constructor params.
* @param minDepositAmountTimelock The timelock period for the minimum deposit amount.
* @param minUserBalanceTimelock The timelock period for the minimum user balance.
* @param maxDepositCapTimelock The timelock period for the maximum deposit cap.
*/
struct DepositConstructorParams {
uint48 minDepositAmountTimelock;
uint48 minUserBalanceTimelock;
uint48 maxDepositCapTimelock;
}
/**
* @notice Parameters for a deposit request.
* @param classId The ID of the share class.
* @param amount The amount of the deposit request.
* @param _authSignature The auth signature for the deposit request.
*/
struct RequestDepositParams {
uint8 classId;
uint256 amount;
AuthLibrary.AuthSignature authSignature;
}
/*//////////////////////////////////////////////////////////////
TIMELOCK FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Queues a new minimum deposit amount.
* @param _classId The ID of the share class to set the minimum deposit amount for.
* @param _minDepositAmount The new minimum deposit amount.
*/
function queueMinDepositAmount(uint8 _classId, uint256 _minDepositAmount) external;
/**
* @notice Queues a new minimum user balance.
* @param _classId The ID of the share class to set the minimum user balance for.
* @param _minUserBalance The new minimum user balance.
*/
function queueMinUserBalance(uint8 _classId, uint256 _minUserBalance) external;
/**
* @notice Queues a new maximum deposit cap.
* @param _classId The ID of the share class to set the maximum deposit cap for.
* @param _maxDepositCap The new maximum deposit cap.
*/
function queueMaxDepositCap(uint8 _classId, uint256 _maxDepositCap) external;
/**
* @notice Sets the minimum deposit amount.
* @param _classId The ID of the share class to set the minimum deposit amount for.
*/
function setMinDepositAmount(uint8 _classId) external;
/**
* @notice Sets the minimum user balance.
* @param _classId The ID of the share class to set the minimum user balance for.
*/
function setMinUserBalance(uint8 _classId) external;
/**
* @notice Sets the maximum deposit cap.
* @param _classId The ID of the share class to set the maximum deposit cap for.
*/
function setMaxDepositCap(uint8 _classId) external;
/*//////////////////////////////////////////////////////////////
DEPOSIT FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Requests a deposit of assets into the vault for the current batch.
* @param _requestDepositParams The parameters for the deposit request.
* @return _batchId The batch ID for the deposit.
*/
function requestDeposit(RequestDepositParams calldata _requestDepositParams) external returns (uint48 _batchId);
/**
* @notice Deposits assets synchronously into the vault, minting shares immediately.
* @param _requestDepositParams The parameters for the deposit (same as requestDeposit).
* @return _shares The number of shares minted to the caller.
* @dev Only callable when totalAssets is valid for the specified class.
*/
function syncDeposit(RequestDepositParams calldata _requestDepositParams) external returns (uint256 _shares);
}
src/interfaces/IEigenYieldsVaultRedeem.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.27;
/*
_______ _ __ ___ _ _
| ____(_) __ _ ___ _ __ \ \ / (_) ___| | __| |___
| _| | |/ _` |/ _ \ '_ \ \ V /| |/ _ \ |/ _` / __|
| |___| | (_| | __/ | | | | | | | __/ | (_| \__ \
|_____|_|\__, |\___|_| |_| |_| |_|\___|_|\__,_|___/
|___/
*/
interface IEigenYieldsVaultRedeem {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/**
* @notice Emitted when a new notice period is queued.
* @param classId The ID of the share class.
* @param noticePeriod The new notice period in batches.
*/
event NewNoticePeriodQueued(uint8 classId, uint48 noticePeriod);
/**
* @notice Emitted when a new lock in period is queued.
* @param classId The ID of the share class.
* @param lockInPeriod The new lock in period in batches.
*/
event NewLockInPeriodQueued(uint8 classId, uint48 lockInPeriod);
/**
* @notice Emitted when a new minimum redeem amount is queued.
* @param classId The ID of the share class.
* @param minRedeemAmount The new minimum redeem amount.
*/
event NewMinRedeemAmountQueued(uint8 classId, uint256 minRedeemAmount);
/**
* @notice Emitted when a new notice period is set.
* @param classId The ID of the share class.
* @param noticePeriod The new notice period in batches.
*/
event NewNoticePeriodSet(uint8 classId, uint48 noticePeriod);
/**
* @notice Emitted when a new lock in period is set.
* @param classId The ID of the share class.
* @param lockInPeriod The new lock in period in batches.
*/
event NewLockInPeriodSet(uint8 classId, uint48 lockInPeriod);
/**
* @notice Emitted when a new minimum redeem amount is set.
* @param classId The ID of the share class.
* @param minRedeemAmount The new minimum redeem amount.
*/
event NewMinRedeemAmountSet(uint8 classId, uint256 minRedeemAmount);
/**
* @notice Emitted when a redeem request is made.
* @param classId The ID of the share class.
* @param batchId The batch ID of the redeem request.
* @param user The user making the redeem request.
* @param estAmountToRedeem The estimated amount to redeem.
*/
event RedeemRequest(uint8 classId, uint48 batchId, address indexed user, uint256 estAmountToRedeem);
/**
* @notice Emitted when the redeemable amount is withdrawn.
* @param user The user withdrawing the redeemable amount.
* @param redeemableAmount The redeemable amount.
*/
event RedeemableAmountWithdrawn(address indexed user, uint256 redeemableAmount);
/**
* @notice Emitted when the excess assets are withdrawn.
* @param excessAssets The excess assets.
*/
event ExcessAssetsWithdrawn(uint256 excessAssets);
/**
* @notice Emitted when a synchronous redeem is made.
* @param classId The ID of the share class.
* @param batchId The batch ID when the redeem occurred.
* @param allocator The address making the redeem.
* @param requestedAmount The amount requested to redeem.
*/
event SyncRedeem(uint8 indexed classId, uint48 batchId, address indexed allocator, uint256 requestedAmount);
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/**
* @notice Emitted when the minimum redeem amount is invalid.
*/
error InvalidMinRedeemAmount();
/**
* @notice Emitted when the redeem is less than the minimum redeem amount.
* @param minRedeemAmount The minimum redeem amount.
*/
error RedeemLessThanMinRedeemAmount(uint256 minRedeemAmount);
/**
* @notice Emitted when the user is in the lock in period.
* @param userLockInPeriod The user lock in period.
*/
error UserInLockInPeriodNotElapsed(uint48 userLockInPeriod);
/**
* @notice Emitted when the assets to redeem are insufficient.
*/
error InsufficientAssetsToRedeem();
/**
* @notice Emitted when the redeem falls below the minimum user balance.
* @param minUserBalance The minimum user balance.
*/
error RedeemFallBelowMinUserBalance(uint256 minUserBalance);
/**
* @notice Emitted when only one request per batch is allowed for redeem.
*/
error OnlyOneRequestPerBatchAllowedForRedeem();
/**
* @notice Emitted when the vault balance is insufficient.
*/
error InsufficientVaultBalance();
/**
* @notice Emitted when only async redeem is allowed (sync is not valid).
*/
error OnlyAsyncRedeemAllowed();
/*//////////////////////////////////////////////////////////////
STRUCTS
//////////////////////////////////////////////////////////////*/
/**
* @notice Constructor params.
* @param noticePeriodTimelock The timelock period for the notice period.
* @param lockInPeriodTimelock The timelock period for the lock in period.
* @param minRedeemAmountTimelock The timelock period for the minimum redeem amount.
*/
struct RedeemConstructorParams {
uint48 noticePeriodTimelock;
uint48 lockInPeriodTimelock;
uint48 minRedeemAmountTimelock;
}
/**
* @notice Parameters for a redeem request.
* @param classId The ID of the share class.
* @param estAmountToRedeem The estimated amount to redeem.
* @dev pleas note that the amount mentioned here is used to calculate the share units based on the
* PPS at the moment of request. The actual amount the users can withdraw after settlement may be
* different from the amount specified here due to change in PPS based on the pnl of the vault and fees.
*/
struct RedeemRequestParams {
uint8 classId;
uint256 estAmountToRedeem;
}
/*//////////////////////////////////////////////////////////////
TIMELOCK FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Queues a new notice period.
* @param _classId The ID of the share class to set the notice period for.
* @param _noticePeriod The new notice period in batches.
*/
function queueNoticePeriod(uint8 _classId, uint48 _noticePeriod) external;
/**
* @notice Queues a new lock in period.
* @param _classId The ID of the share class to set the lock in period for.
* @param _lockInPeriod The new lock in period in batches.
*/
function queueLockInPeriod(uint8 _classId, uint48 _lockInPeriod) external;
/**
* @notice Queues a new minimum redeem amount.
* @param _classId The ID of the share class to set the minimum redeem amount for.
* @param _minRedeemAmount The new minimum redeem amount.
*/
function queueMinRedeemAmount(uint8 _classId, uint256 _minRedeemAmount) external;
/**
* @notice Sets the notice period in batches
* @param _classId The ID of the share class to set the notice period for.
*/
function setNoticePeriod(uint8 _classId) external;
/**
* @notice Sets the lock in period in batches
* @param _classId The ID of the share class to set the lock in period for.
*/
function setLockInPeriod(uint8 _classId) external;
/**
* @notice Sets the minimum redeem amount.
* @param _classId The ID of the share class to set the minimum redeem amount for.
*/
function setMinRedeemAmount(uint8 _classId) external;
/*//////////////////////////////////////////////////////////////
REDEEM FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Requests to redeem shares from the vault for the current batch.
* @param _redeemRequestParams The parameters for the redeem request.
* @return _batchId The batch ID for the redeem request.
*/
function requestRedeem(RedeemRequestParams calldata _redeemRequestParams) external returns (uint48 _batchId);
/**
* @notice Withdraws the redeemable amount for the user.
*/
function withdrawRedeemableAmount() external;
/**
* @notice Withdraws excess assets from the vault and sends back to custodian.
*/
function withdrawExcessAssets() external;
/**
* @notice Redeems shares synchronously from the vault, transferring assets immediately.
* @param _redeemRequestParams The parameters for the redeem (same as requestRedeem).
* @return _assets The amount of assets transferred to the caller.
* @dev Only callable when totalAssets is valid. Bypasses notice period.
*/
function syncRedeem(RedeemRequestParams calldata _redeemRequestParams) external returns (uint256 _assets);
}
src/interfaces/IEigenYieldsVaultSettlement.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.27;
/*
_______ _ __ ___ _ _
| ____(_) __ _ ___ _ __ \ \ / (_) ___| | __| |___
| _| | |/ _` |/ _ \ '_ \ \ V /| |/ _ \ |/ _` / __|
| |___| | (_| | __/ | | | | | | | __/ | (_| \__ \
|_____|_|\__, |\___|_| |_| |_| |_|\___|_|\__,_|___/
|___/
*/
import {AuthLibrary} from "@eigenyields-vault/libraries/AuthLibrary.sol";
import {SeriesAccounting} from "@eigenyields-vault/libraries/SeriesAccounting.sol";
interface IEigenYieldsVaultSettlement {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/**
* @notice Emitted when a deposit cycle is settled.
* @param classId The ID of the share class for which the deposits are settled.
* @param seriesId The ID of the share series in which the deposits are settled.
* @param fromBatchId The batch ID from which the deposits are settled.
* @param toBatchId The batch ID up to which the deposits are settled.
* @param amountToSettle The total amount of deposits that are settled.
* @param totalAssets The total assets of the share series after settlement.
* @param totalShares The total shares of the share series after settlement.
*/
event SettleDeposit(
uint8 classId,
uint32 seriesId,
uint48 indexed fromBatchId,
uint48 indexed toBatchId,
uint256 amountToSettle,
uint256 totalAssets,
uint256 totalShares
);
/**
* @notice Emitted when a new series is created.
* @param classId The ID of the share class for which the new series is created.
* @param seriesId The ID of the new share series.
* @param toBatchId The batch ID in which the new series is created.
* @dev the new series is marked as created in the batch ID up to which the deposits are settled,
* which may not be the current batch ID.
*/
event NewSeriesCreated(uint8 classId, uint32 seriesId, uint48 toBatchId);
/**
* @notice Emitted when a series is consolidated.
* @param classId The ID of the share class for which the series is consolidated.
* @param seriesId The ID of the share series that is consolidated.
* @param toBatchId The batch ID in which the series is consolidated.
* @param amountToTransfer The total amount of the shares that are transferred.
* @param sharesToTransfer The total shares that are transferred.
* @dev the series is marked as consolidated in the batch ID up to which the deposits are settled,
* which may not be the current batch ID.
*/
event SeriesConsolidated(
uint8 classId, uint32 seriesId, uint48 toBatchId, uint256 amountToTransfer, uint256 sharesToTransfer
);
/**
* @notice Emitted when all series are consolidated.
* @param classId The ID of the share class for which the series are consolidated.
* @param fromSeriesId The ID of the first share series that is consolidated.
* @param toSeriesId The ID of the last share series that is consolidated.
* @param toBatchId The batch ID in which the series are consolidated.
* @param totalAmountToTransfer The total amount of the shares that are transferred.
* @param totalSharesToTransfer The total shares that are transferred.
* @dev the series are marked as consolidated in the batch ID up to which the deposits are settled,
* which may not be the current batch ID.
*/
event AllSeriesConsolidated(
uint8 classId,
uint32 fromSeriesId,
uint32 toSeriesId,
uint48 toBatchId,
uint256 totalAmountToTransfer,
uint256 totalSharesToTransfer
);
/**
* @notice Emitted when a user's shares are consolidated.
* @param userConsolidationDetails The details of the user's shares consolidation.
*/
event UserSharesConsolidated(SeriesAccounting.UserConsolidationDetails userConsolidationDetails);
/**
* @notice Emitted when a deposit request is settled.
* @param classId The ID of the share class for which the deposit request is settled.
* @param seriesId The ID of the share series in which the deposit request is settled.
* @param toBatchId The batch ID up to which the deposit request is settled.
* @param user The user that made the deposit request.
* @param amount The amount of the deposit request.
* @param sharesToMint The shares to mint for the deposit request.
*/
event DepositRequestSettled(
uint8 classId,
uint32 seriesId,
uint48 indexed toBatchId,
address indexed user,
uint256 amount,
uint256 sharesToMint
);
/**
* @notice Emitted when a deposit batch is settled.
* @param classId The ID of the share class for which the deposit batch is settled.
* @param seriesId The ID of the share series in which the deposit batch is settled.
* @param batchId The batch ID that is settled.
* @param totalAmountToDeposit The total amount of the deposits that are settled in the batch.
* @param totalSharesToMint The total shares to mint for the deposit requests in the batch.
*/
event SettleDepositBatch(
uint8 classId, uint32 seriesId, uint48 indexed batchId, uint256 totalAmountToDeposit, uint256 totalSharesToMint
);
/**
* @notice Emitted when a redeem request is settled.
* @param classId The ID of the share class for which the redeem request is settled.
* @param fromBatchId The batch ID from which the redeem request is settled.
* @param toBatchId The batch ID up to which the redeem request is settled.
*/
event SettleRedeem(uint8 classId, uint48 indexed fromBatchId, uint48 indexed toBatchId);
/**
* @notice Emitted when a redeem request is settled.
* @param classId The ID of the share class for which the redeem request is settled.
* @param batchId The batch ID in which redeem request is settled.
* @param user The user that made the redeem request.
* @param amountToRedeem The amount of the redeem request.
*/
event RedeemRequestSettled(uint8 classId, uint48 indexed batchId, address indexed user, uint256 amountToRedeem);
/**
* @notice Emitted when a redeem request slice is settled.
* @param classId The ID of the share class for which the redeem request is settled.
* @param seriesId The ID of the share series in which the redeem request is settled.
* @param batchId The batch ID in which redeem slice is settled.
* @param user The user that made the redeem request.
* @param amountToRedeem The amount of the redeem request.
*/
event RedeemRequestSliceSettled(
uint8 classId,
uint32 seriesId,
uint48 indexed batchId,
address indexed user,
uint256 amountToRedeem,
uint256 sharesToBurn
);
/**
* @notice Emitted when a redeem batch is settled.
* @param classId The ID of the share class for which the redeem batch is settled.
* @param batchId The batch ID that is settled.
* @param totalAmountToRedeem The total amount of the redeem requests that are settled in the batch.
*/
event SettleRedeemBatch(uint8 indexed classId, uint48 indexed batchId, uint256 totalAmountToRedeem);
/**
* @notice Emitted when a redeem is forced by the manager.
* @param batchId The batch ID in which redeem is forced.
* @param user The user that made the redeem request.
* @param totalAssetsToSettle The total assets to settle.
*/
event ForceRedeem(uint48 indexed batchId, address indexed user, uint256 totalAssetsToSettle);
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/**
* @notice Emitted when the new total assets are invalid.
*/
error InvalidNewTotalAssets();
/**
* @notice Emitted when the to batch ID is invalid.
*/
error InvalidToBatchId();
/**
* @notice Emitted when there are no deposits to settle.
*/
error NoDepositsToSettle();
/**
* @notice Emitted when there are no redeems to settle.
*/
error NoRedeemsToSettle();
/**
* @notice Emitted when there are insufficient assets to settle deposits/redeems.
* @param requiredVaultBalance The required vault balance.
*/
error InsufficientAssetsToSettle(uint256 requiredVaultBalance);
/**
* @notice Emitted when the delegate call fails.
* @param _data The data of the delegate call.
*/
error DelegateCallFailed(bytes _data);
/**
* @notice Emitted when sync expiration batches are queued.
* @param expirationBatches The number of batches sync flows remain valid.
*/
event SyncExpirationBatchesQueued(uint48 expirationBatches);
/**
* @notice Emitted when sync expiration batches are updated.
* @param expirationBatches The number of batches sync flows remain valid.
*/
event SyncExpirationBatchesUpdated(uint48 expirationBatches);
/*//////////////////////////////////////////////////////////////
STRUCTS
//////////////////////////////////////////////////////////////*/
/**
* @notice Parameters for the settlement.
* @param classId The ID of the share class.
* @param toBatchId The batch ID up to which the settlement is done.
* @param newTotalAssets The new total assets before settlement.
* @param authSignature The auth signature for the settlement.
*/
struct SettlementParams {
uint8 classId;
uint48 toBatchId;
uint256[] newTotalAssets;
AuthLibrary.AuthSignature authSignature;
}
/**
* @notice Details for the settlement of a deposit.
* @param createSeries Whether a new series is to be created.
* @param classId The ID of the share class for which the settlement should be done.
* @param seriesId The ID of the share series in which the settlement should be done.
* @param batchId The batch ID for which the settlement is to be done.
* @param toBatchId The batch ID in which settlement should be logged as done.
* @param totalAssets The total assets before settlement of the batch.
* @param totalShares The total shares before settlement of the batch.
*/
struct SettleDepositDetails {
bool createSeries;
uint8 classId;
uint32 seriesId;
uint48 batchId;
uint48 toBatchId;
uint256 totalAssets;
uint256 totalShares;
}
/**
* @notice Details for the settlement of a deposit request.
* @param user The user that made the deposit request which is to be settled.
* @param amount The amount of the deposit request which is to be settled.
* @param sharesToMint The shares to mint for the deposit request which is to be settled.
*/
struct DepositRequestDetails {
address user;
uint256 amount;
uint256 sharesToMint;
}
/*//////////////////////////////////////////////////////////////
SETTLEMENT FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Settles all pending deposits up to the current batch.
* @param _settlementParams The parameters for the settlement.
*/
function settleDeposit(SettlementParams calldata _settlementParams) external;
/**
* @notice Settles all pending redeems up to the current batch.
* @param _settlementParams The parameters for the settlement.
*/
function settleRedeem(SettlementParams calldata _settlementParams) external;
/**
* @notice Forces a redeem for a user.
* @param _user The user to force a redeem for.
*/
function forceRedeem(address _user) external;
/**
* @notice Queues a new sync expiration batches value to be set after the timelock period.
* @param _expirationBatches The number of batches sync flows remain valid.
* @dev Only callable by the MANAGER role.
* @dev Setting _expirationBatches to 0 will disable sync flows (only valid in the exact batch where settlement occurred).
*/
function queueSyncExpirationBatches(uint48 _expirationBatches) external;
/**
* @notice Sets the sync expiration batches to the queued value after the timelock period.
* @dev Only callable by the MANAGER role.
*/
function setSyncExpirationBatches() external;
}
src/libraries/AuthLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// ─────────────────────────────────────────────────────────────────────────────
// AuthLibrary
// Off-chain signature verification for privileged vault operations.
// Each entry point constructs the appropriate digest and delegates to the
// shared recovery routine.
// ─────────────────────────────────────────────────────────────────────────────
import {ECDSA} from "openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol";
import {MessageHashUtils} from "openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol";
library AuthLibrary {
using ECDSA for bytes32;
using MessageHashUtils for bytes32;
// -------------------------------------------------------------------------
// Constants
// -------------------------------------------------------------------------
/// @dev Flow discriminator for settle-deposit operations.
bytes4 internal constant SETTLE_DEPOSIT = bytes4(keccak256("SETTLE_DEPOSIT"));
/// @dev Flow discriminator for settle-redeem operations.
bytes4 internal constant SETTLE_REDEEM = bytes4(keccak256("SETTLE_REDEEM"));
// -------------------------------------------------------------------------
// Errors
// -------------------------------------------------------------------------
/// @notice Thrown when the provided signature's expiry block has already passed.
error AuthSignatureExpired();
/// @notice Thrown when the recovered signer does not match the expected authority.
error InvalidAuthSignature();
// -------------------------------------------------------------------------
// Structs
// -------------------------------------------------------------------------
/**
* @notice Bundles an ECDSA signature with its validity window.
* @param authSignature Raw 65-byte ECDSA signature bytes.
* @param expiryBlock Block number after which the signature is no longer valid.
*/
struct AuthSignature {
bytes authSignature;
uint256 expiryBlock;
}
// -------------------------------------------------------------------------
// Verification entry points
// -------------------------------------------------------------------------
/**
* @notice Verifies that a vault deployment was authorised by the expected signer.
*
* The digest commits to the deployer, factory address, vault name, config ID,
* chain ID, and the signature's own expiry block to prevent cross-chain or
* cross-deployment replay attacks.
*
* @param vaultFactory Address of the factory contract initiating the deployment.
* @param name Human-readable name of the vault being deployed.
* @param configId Opaque configuration identifier for the vault class.
* @param authSigner Address whose private key must have produced the signature.
* @param sig Signature bundle to validate.
*/
function checkVaultDeployAuth(
address vaultFactory,
string memory name,
string memory configId,
address authSigner,
AuthSignature memory sig
) internal view {
bytes32 digest = keccak256(abi.encode(msg.sender, vaultFactory, name, configId, block.chainid, sig.expiryBlock));
recoverAndVerify(digest, authSigner, sig);
}
/**
* @notice Verifies that a deposit request was authorised for the given user and class.
*
* Commits the sender, vault address, chain ID, class ID, and expiry block.
*
* @param classId Share-class ID the deposit targets.
* @param authSigner Expected signer of the authorisation.
* @param sig Signature bundle to validate.
*/
function checkDepositRequestAuth(uint8 classId, address authSigner, AuthSignature memory sig) internal view {
bytes32 digest = keccak256(abi.encode(msg.sender, address(this), block.chainid, classId, sig.expiryBlock));
recoverAndVerify(digest, authSigner, sig);
}
/**
* @notice Verifies that a batch settlement was authorised by the expected signer.
*
* Commits the flow type, manager, vault address, chain ID, class ID, target
* batch ID, new total-asset array, and the expiry block.
*
* @param flow Flow identifier (SETTLE_DEPOSIT or SETTLE_REDEEM).
* @param classId Share-class being settled.
* @param toBatchId The batch number up to which settlement is authorised.
* @param manager Address of the manager executing the settlement.
* @param newTotalAssets Updated asset totals reported for each series.
* @param authSigner Expected signer of the authorisation.
* @param sig Signature bundle to validate.
*/
function checkSettlementAuth(
bytes4 flow,
uint8 classId,
uint48 toBatchId,
address manager,
uint256[] calldata newTotalAssets,
address authSigner,
AuthSignature memory sig
) internal view {
bytes32 digest = keccak256(
abi.encode(flow, manager, address(this), block.chainid, classId, toBatchId, newTotalAssets, sig.expiryBlock)
);
recoverAndVerify(digest, authSigner, sig);
}
// -------------------------------------------------------------------------
// Internal helpers
// -------------------------------------------------------------------------
/**
* @notice Core recovery and equality check.
*
* Applies the Ethereum signed-message prefix to the raw digest before
* recovering the signer, matching the behaviour of eth_sign.
*
* @param digest Raw keccak256 digest of the signed payload.
* @param expected Address that must match the recovered signer.
* @param sig Signature bundle (raw bytes + expiry block).
*/
function recoverAndVerify(bytes32 digest, address expected, AuthSignature memory sig) internal view {
if (sig.expiryBlock < block.number) {
revert AuthSignatureExpired();
}
address recovered = digest.toEthSignedMessageHash().recover(sig.authSignature);
if (recovered != expected) {
revert InvalidAuthSignature();
}
}
}
src/libraries/ERC4626Math.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Math} from "openzeppelin-contracts/contracts/utils/math/Math.sol";
/**
* @title ERC4626Math
* @dev Arithmetic helpers for ERC-4626 share/asset conversions.
*
* All preview functions follow the rounding conventions required by EIP-4626:
* deposits and redeems round down (Floor), mints and withdraws round up (Ceil).
* A fixed decimals offset of zero is used throughout.
*/
library ERC4626Math {
using Math for uint256;
/// @notice Total share-unit scale factor (1e18). One full share equals this many share units.
uint256 public constant TOTAL_SHARE_UNITS = 1e18;
// -------------------------------------------------------------------------
// Preview helpers — public-facing API (names must match callers)
// -------------------------------------------------------------------------
/// @dev Returns shares minted for a given asset deposit (rounds down).
function previewDeposit(uint256 assets, uint256 totalShares, uint256 totalAssets) internal pure returns (uint256) {
return sharesFromAssets(assets, totalShares, totalAssets, Math.Rounding.Floor);
}
/// @dev Returns assets required to mint a given number of shares (rounds up).
function previewMint(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
return assetsFromShares(shares, totalAssets, totalShares, Math.Rounding.Ceil);
}
/// @dev Returns shares burned to withdraw a given asset amount (rounds up).
function previewWithdraw(uint256 assets, uint256 totalShares, uint256 totalAssets) internal pure returns (uint256) {
return sharesFromAssets(assets, totalShares, totalAssets, Math.Rounding.Ceil);
}
/// @dev Returns assets received for redeeming a given number of shares (rounds down).
function previewRedeem(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
return assetsFromShares(shares, totalAssets, totalShares, Math.Rounding.Floor);
}
/**
* @notice Returns the asset amount for a given number of share units, rounding up.
* @param shareUnits The quantity of share units to convert.
* @param totalAssets Total vault assets at the time of conversion.
* @return Asset amount corresponding to the share units.
*/
function previewMintUnits(uint256 shareUnits, uint256 totalAssets) internal pure returns (uint256) {
return assetsFromShareUnits(shareUnits, totalAssets);
}
/**
* @notice Returns the share-unit amount needed to withdraw a given asset quantity, rounding down.
* @param assets The asset amount to withdraw.
* @param totalAssets Total vault assets at the time of conversion.
* @return Share-unit amount corresponding to the asset quantity.
*/
function previewWithdrawUnits(uint256 assets, uint256 totalAssets) internal pure returns (uint256) {
return shareUnitsFromAssets(assets, totalAssets);
}
// -------------------------------------------------------------------------
// Core conversion primitives (library-private)
// -------------------------------------------------------------------------
/// @dev Converts an asset amount to shares using mulDiv with the specified rounding.
function sharesFromAssets(uint256 assets, uint256 totalShares, uint256 totalAssets, Math.Rounding rounding)
internal
pure
returns (uint256)
{
return assets.mulDiv(totalShares + 10 ** decimalsOffset(), totalAssets + 1, rounding);
}
/// @dev Converts a share count to assets using mulDiv with the specified rounding.
function assetsFromShares(uint256 shares, uint256 totalAssets, uint256 totalShares, Math.Rounding rounding)
internal
pure
returns (uint256)
{
return shares.mulDiv(totalAssets + 1, totalShares + 10 ** decimalsOffset(), rounding);
}
/// @dev Converts an asset amount to share units, rounding down.
function shareUnitsFromAssets(uint256 assets, uint256 totalAssets) internal pure returns (uint256) {
return assets.mulDiv(TOTAL_SHARE_UNITS, totalAssets, Math.Rounding.Floor);
}
/// @dev Converts share units to an asset amount, rounding up.
function assetsFromShareUnits(uint256 shareUnits, uint256 totalAssets) internal pure returns (uint256) {
return shareUnits.mulDiv(totalAssets, TOTAL_SHARE_UNITS, Math.Rounding.Ceil);
}
/// @dev Returns the decimal offset applied to share/asset calculations (always 0).
function decimalsOffset() private pure returns (uint8) {
return 0;
}
}
src/libraries/ModulesLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.27;
// ─────────────────────────────────────────────────────────────────────────────
// ModulesLibrary
// Byte-selector identifiers for each pluggable module in the EigenYields system.
// ─────────────────────────────────────────────────────────────────────────────
library ModulesLibrary {
// -- Vault flow modules ---------------------------------------------------
/// @dev Identifies the deposit module handling vault deposit flows.
bytes4 internal constant EIGEN_YIELDS_VAULT_DEPOSIT = bytes4(keccak256("EIGEN_YIELDS_VAULT_DEPOSIT"));
/// @dev Identifies the redeem module handling vault redeem flows.
bytes4 internal constant EIGEN_YIELDS_VAULT_REDEEM = bytes4(keccak256("EIGEN_YIELDS_VAULT_REDEEM"));
/// @dev Identifies the settlement module handling batch settlement flows.
bytes4 internal constant EIGEN_YIELDS_VAULT_SETTLEMENT = bytes4(keccak256("EIGEN_YIELDS_VAULT_SETTLEMENT"));
// -- Management modules ---------------------------------------------------
/// @dev Identifies the fee manager module.
bytes4 internal constant FEE_MANAGER = bytes4(keccak256("FEE_MANAGER"));
/// @dev Identifies the migration manager module.
bytes4 internal constant MIGRATION_MANAGER = bytes4(keccak256("MIGRATION_MANAGER"));
}
src/libraries/PausableFlows.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.27;
// ─────────────────────────────────────────────────────────────────────────────
// PausableFlows
// Byte-selector identifiers for user-facing flows that can be individually
// paused by a guardian or operations multisig.
// ─────────────────────────────────────────────────────────────────────────────
library PausableFlows {
// -- Request flows --------------------------------------------------------
/// @dev Identifies the deposit-request flow (user submits deposit intent).
bytes4 internal constant DEPOSIT_REQUEST_FLOW = bytes4(keccak256("DEPOSIT_REQUEST_FLOW"));
/// @dev Identifies the redeem-request flow (user submits redeem intent).
bytes4 internal constant REDEEM_REQUEST_FLOW = bytes4(keccak256("REDEEM_REQUEST_FLOW"));
// -- Settlement flows -----------------------------------------------------
/// @dev Identifies the settle-deposit flow (batch deposit settlement by manager).
bytes4 internal constant SETTLE_DEPOSIT_FLOW = bytes4(keccak256("SETTLE_DEPOSIT_FLOW"));
/// @dev Identifies the settle-redeem flow (batch redeem settlement by manager).
bytes4 internal constant SETTLE_REDEEM_FLOW = bytes4(keccak256("SETTLE_REDEEM_FLOW"));
// -- Withdrawal flow ------------------------------------------------------
/// @dev Identifies the withdraw flow (user claims settled assets).
bytes4 internal constant WITHDRAW_FLOW = bytes4(keccak256("WITHDRAW_FLOW"));
}
src/libraries/RolesLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.27;
// ─────────────────────────────────────────────────────────────────────────────
// RolesLibrary
// Byte-selector identifiers for access-control roles within EigenYields.
// ─────────────────────────────────────────────────────────────────────────────
library RolesLibrary {
// -- Data-feed roles ------------------------------------------------------
/// @dev Identifies the price oracle role for reporting NAV updates.
bytes4 internal constant ORACLE = bytes4(keccak256("ORACLE"));
// -- Operational roles ----------------------------------------------------
/// @dev Identifies the guardian role with emergency-pause authority.
bytes4 internal constant GUARDIAN = bytes4(keccak256("GUARDIAN"));
/// @dev Identifies the manager role for day-to-day vault operations.
bytes4 internal constant MANAGER = bytes4(keccak256("MANAGER"));
/// @dev Identifies the operations multisig role for protocol governance.
bytes4 internal constant OPERATIONS_MULTISIG = bytes4(keccak256("OPERATIONS_MULTISIG"));
// -- Infrastructure roles -------------------------------------------------
/// @dev Identifies the vault factory role for deploying new vaults.
bytes4 internal constant VAULT_FACTORY = bytes4(keccak256("VAULT_FACTORY"));
/// @dev Identifies the accountant role responsible for fee accounting.
bytes4 internal constant ACCOUNTANT = bytes4(keccak256("ACCOUNTANT"));
/// @dev Identifies the EigenYields AVS role for restaking operations.
bytes4 internal constant EIGEN_YIELDS_AVS = bytes4(keccak256("EIGEN_YIELDS_AVS"));
}
src/libraries/SeriesAccounting.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// ─────────────────────────────────────────────────────────────────────────────
// SeriesAccounting
// Share-series lifecycle management for EigenYields vaults.
//
// Vaults accumulate deposits in discrete "series". When a new settlement
// cycle begins a fresh series is opened; outstanding series are later merged
// (consolidated) into the permanent lead series (ID 0). Redemptions drain
// value from series in first-in-first-out order.
// ─────────────────────────────────────────────────────────────────────────────
import {EnumerableSet} from "openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol";
import {IEigenYieldsVault} from "@eigenyields-vault/interfaces/IEigenYieldsVault.sol";
import {IEigenYieldsVaultSettlement} from "@eigenyields-vault/interfaces/IEigenYieldsVaultSettlement.sol";
import {ERC4626Math} from "@eigenyields-vault/libraries/ERC4626Math.sol";
library SeriesAccounting {
using EnumerableSet for EnumerableSet.AddressSet;
// -------------------------------------------------------------------------
// Constants
// -------------------------------------------------------------------------
/// @dev The permanent lead-series identifier. Always zero.
uint32 internal constant LEAD_SERIES_ID = 0;
/// @dev Denominator used when expressing price-per-share as a fixed-point ratio.
uint256 internal constant PRICE_DENOMINATOR = 1e6;
/// @dev Virtual recipient address for accrued management fees within a series.
address internal constant MANAGEMENT_FEE_RECIPIENT = address(bytes20(keccak256("MANAGEMENT_FEE_RECIPIENT")));
/// @dev Virtual recipient address for accrued performance fees within a series.
address internal constant PERFORMANCE_FEE_RECIPIENT = address(bytes20(keccak256("PERFORMANCE_FEE_RECIPIENT")));
// -------------------------------------------------------------------------
// Structs
// -------------------------------------------------------------------------
/**
* @notice Carries per-user state during a series consolidation pass.
* @param user The account being consolidated.
* @param classId Share-class identifier.
* @param seriesId Source series being merged into the lead series.
* @param toBatchId Batch number used to timestamp the consolidation event.
* @param shares User's share balance in the source series.
* @param amountToTransfer Asset value attributed to those shares.
* @param sharesToTransfer Equivalent share count minted in the lead series.
*/
struct UserConsolidationDetails {
address user;
uint8 classId;
uint32 seriesId;
uint48 toBatchId;
uint256 shares;
uint256 amountToTransfer;
uint256 sharesToTransfer;
}
// -------------------------------------------------------------------------
// Series lifecycle functions
// -------------------------------------------------------------------------
/**
* @dev Opens a new share series for the given class, initialising its
* high-water mark and emitting the NewSeriesCreated event.
*
* @param shareClass Storage reference to the share class record.
* @param classId Identifier of the owning share class.
* @param settleBatch Batch number associated with this opening (for event logging).
*/
function openSeries(IEigenYieldsVault.ShareClass storage shareClass, uint8 classId, uint48 settleBatch) internal {
uint32 nextId = ++shareClass.shareSeriesId;
shareClass.shareSeries[nextId].highWaterMark = PRICE_DENOMINATOR;
emit IEigenYieldsVaultSettlement.NewSeriesCreated(classId, nextId, settleBatch);
}
/**
* @dev Merges all outstanding series (from lastConsolidatedSeriesId+1 through
* shareSeriesId) into the lead series and updates accounting totals.
*
* Each merged series has its users' assets revalued at the current lead-series
* price per share, and new lead-series shares are minted accordingly. The source
* series records are deleted after processing.
*
* @param shareClass Storage reference to the share class.
* @param classId Share-class identifier.
* @param topSeriesId Highest series ID to consolidate (inclusive).
* @param lastMergedId Last series ID that was previously consolidated.
* @param settleBatch Batch number used for event logging.
*/
function mergeSeries(
IEigenYieldsVault.ShareClass storage shareClass,
uint8 classId,
uint32 topSeriesId,
uint32 lastMergedId,
uint48 settleBatch
) internal {
uint256 totalAssetsIn;
uint256 totalSharesIn;
IEigenYieldsVault.ShareSeries storage lead = shareClass.shareSeries[LEAD_SERIES_ID];
for (uint32 sid = lastMergedId + 1; sid <= topSeriesId; sid++) {
IEigenYieldsVault.ShareSeries storage series = shareClass.shareSeries[sid];
(uint256 assetsIn, uint256 sharesIn) = mergeUserBalances(lead, series, classId, sid, settleBatch);
totalAssetsIn += assetsIn;
totalSharesIn += sharesIn;
series.users.clear();
delete shareClass.shareSeries[sid];
emit IEigenYieldsVaultSettlement.SeriesConsolidated(classId, sid, settleBatch, assetsIn, sharesIn);
}
shareClass.lastConsolidatedSeriesId = topSeriesId;
shareClass.shareSeries[LEAD_SERIES_ID].totalAssets += totalAssetsIn;
shareClass.shareSeries[LEAD_SERIES_ID].totalShares += totalSharesIn;
emit IEigenYieldsVaultSettlement.AllSeriesConsolidated(
classId, lastMergedId + 1, topSeriesId, settleBatch, totalAssetsIn, totalSharesIn
);
}
/**
* @dev Processes a user's redemption request using FIFO series ordering.
*
* Attempts to settle the full requested amount starting from the lead series,
* then iterates through outstanding series in ascending order until the
* balance is exhausted or the full amount is covered.
*
* @param shareClass Storage reference to the share class.
* @param classId Share-class identifier.
* @param batchId Batch number in which this redemption is being settled.
* @param account The user whose redemption is being processed.
* @param requested Total asset amount the user wishes to redeem.
*/
function processRedemption(
IEigenYieldsVault.ShareClass storage shareClass,
uint8 classId,
uint48 batchId,
address account,
uint256 requested
) internal {
uint256 outstanding = requested;
uint32 topId = shareClass.shareSeriesId;
for (uint32 sid; sid <= topId; sid++) {
if (outstanding == 0) break;
outstanding = redeemFromSeries(shareClass, classId, sid, batchId, account, outstanding);
// After the lead series, jump ahead to the first unconsolidated series
if (sid == SeriesAccounting.LEAD_SERIES_ID) {
sid = shareClass.lastConsolidatedSeriesId;
}
}
}
// -------------------------------------------------------------------------
// Private helpers
// -------------------------------------------------------------------------
/**
* @dev Iterates every holder in a source series and credits equivalent lead-series
* shares. Fee recipients are temporarily added to ensure their balances are
* captured without permanently joining the lead-series user set.
*
* @param lead Lead series storage reference (shares are deposited here).
* @param source Source series storage reference (shares are consumed here).
* @param classId Share-class identifier.
* @param sid Series identifier of the source series.
* @param batch Batch number for event logging.
* @return assetsIn Sum of assets moved from the source series.
* @return sharesIn Sum of lead-series shares minted across all users.
*/
function mergeUserBalances(
IEigenYieldsVault.ShareSeries storage lead,
IEigenYieldsVault.ShareSeries storage source,
uint8 classId,
uint32 sid,
uint48 batch
) private returns (uint256 assetsIn, uint256 sharesIn) {
source.users.add(MANAGEMENT_FEE_RECIPIENT);
source.users.add(PERFORMANCE_FEE_RECIPIENT);
uint256 count = source.users.length();
UserConsolidationDetails memory entry = UserConsolidationDetails({
user: address(0),
classId: classId,
seriesId: sid,
shares: 0,
amountToTransfer: 0,
sharesToTransfer: 0,
toBatchId: batch
});
for (uint256 idx; idx < count; idx++) {
entry.user = source.users.at(idx);
entry.shares = source.sharesOf[entry.user];
entry.amountToTransfer = ERC4626Math.previewRedeem(entry.shares, source.totalAssets, source.totalShares);
entry.sharesToTransfer =
ERC4626Math.previewDeposit(entry.amountToTransfer, lead.totalShares, lead.totalAssets);
assetsIn += entry.amountToTransfer;
sharesIn += entry.sharesToTransfer;
lead.sharesOf[entry.user] += entry.sharesToTransfer;
bool isFeeRecipient = entry.user == MANAGEMENT_FEE_RECIPIENT || entry.user == PERFORMANCE_FEE_RECIPIENT;
if (!lead.users.contains(entry.user) && !isFeeRecipient) {
lead.users.add(entry.user);
}
delete source.sharesOf[entry.user];
emit IEigenYieldsVaultSettlement.UserSharesConsolidated(entry);
}
}
/**
* @dev Applies a single redemption slice against one series.
*
* If the series holds enough assets to cover the entire remaining balance,
* the remaining amount is fully settled and zero is returned. Otherwise the
* series is drained completely and the unsettled balance is returned for the
* caller to continue with the next series.
*
* @param shareClass Storage reference to the share class.
* @param classId Share-class identifier.
* @param sid Series to draw from.
* @param batchId Settlement batch number for event logging.
* @param account User whose shares are being redeemed.
* @param remaining Asset amount still needed to complete the redemption.
* @return Updated remaining amount after applying this series.
*/
function redeemFromSeries(
IEigenYieldsVault.ShareClass storage shareClass,
uint8 classId,
uint32 sid,
uint48 batchId,
address account,
uint256 remaining
) private returns (uint256) {
IEigenYieldsVault.ShareSeries storage series = shareClass.shareSeries[sid];
uint256 userShares = series.sharesOf[account];
uint256 seriesBalance = ERC4626Math.previewRedeem(userShares, series.totalAssets, series.totalShares);
if (seriesBalance <= remaining) {
// Drain the entire user position in this series
remaining -= seriesBalance;
series.totalAssets -= seriesBalance;
series.totalShares -= userShares;
series.users.remove(account);
delete series.sharesOf[account];
emit IEigenYieldsVaultSettlement.RedeemRequestSliceSettled(
classId, sid, batchId, account, seriesBalance, userShares
);
} else {
// Partial redemption — only burn enough shares to cover the remaining amount
uint256 sharesToBurn = ERC4626Math.previewWithdraw(remaining, series.totalShares, series.totalAssets);
series.totalAssets -= remaining;
series.totalShares -= sharesToBurn;
series.sharesOf[account] -= sharesToBurn;
emit IEigenYieldsVaultSettlement.RedeemRequestSliceSettled(
classId, sid, batchId, account, remaining, sharesToBurn
);
remaining = 0;
}
return remaining;
}
}
src/libraries/TimelockRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// ─────────────────────────────────────────────────────────────────────────────
// TimelockRegistry
// Manages pending configuration changes that require a delay before taking
// effect. Each configuration key is namespaced by a share-class ID so that
// different classes may carry independent timelock schedules.
// ─────────────────────────────────────────────────────────────────────────────
import {Time} from "openzeppelin-contracts/contracts/utils/types/Time.sol";
import {EigenYieldsVaultStorageData} from "@eigenyields-vault/EigenYieldsVaultStorage.sol";
library TimelockRegistry {
// -------------------------------------------------------------------------
// Configuration keys — keccak4 identifiers for each timelocked parameter
// -------------------------------------------------------------------------
/// @dev Key for the minimum deposit amount setting.
bytes4 internal constant MIN_DEPOSIT_AMOUNT = bytes4(keccak256("MIN_DEPOSIT_AMOUNT"));
/// @dev Key for the minimum user balance setting.
bytes4 internal constant MIN_USER_BALANCE = bytes4(keccak256("MIN_USER_BALANCE"));
/// @dev Key for the maximum total deposit cap.
bytes4 internal constant MAX_DEPOSIT_CAP = bytes4(keccak256("MAX_DEPOSIT_CAP"));
/// @dev Key for the notice period before a redemption is claimable.
bytes4 internal constant NOTICE_PERIOD = bytes4(keccak256("NOTICE_PERIOD"));
/// @dev Key for the lock-in period that prevents early redemptions.
bytes4 internal constant LOCK_IN_PERIOD = bytes4(keccak256("LOCK_IN_PERIOD"));
/// @dev Key for the minimum redemption amount.
bytes4 internal constant MIN_REDEEM_AMOUNT = bytes4(keccak256("MIN_REDEEM_AMOUNT"));
/// @dev Key for the management fee rate.
bytes4 internal constant MANAGEMENT_FEE = bytes4(keccak256("MANAGEMENT_FEE"));
/// @dev Key for the performance fee rate.
bytes4 internal constant PERFORMANCE_FEE = bytes4(keccak256("PERFORMANCE_FEE"));
/// @dev Key for the accountant address.
bytes4 internal constant ACCOUNTANT = bytes4(keccak256("ACCOUNTANT"));
/// @dev Key for the sync expiration batches setting.
bytes4 internal constant SYNC_EXPIRATION_BATCHES = bytes4(keccak256("SYNC_EXPIRATION_BATCHES"));
// -------------------------------------------------------------------------
// Errors
// -------------------------------------------------------------------------
/**
* @notice Raised when attempting to execute a timelock that was never queued.
* @param key The configuration key that was looked up.
* @param classId The share-class ID associated with this timelock.
*/
error TimelockNotQueued(bytes4 key, uint8 classId);
/**
* @notice Raised when a queued timelock has not yet reached its unlock time.
* @param key The configuration key.
* @param classId The share-class ID.
* @param unlockTimestamp The earliest timestamp at which execution is permitted.
*/
error TimelockNotExpired(bytes4 key, uint8 classId, uint48 unlockTimestamp);
// -------------------------------------------------------------------------
// Structs
// -------------------------------------------------------------------------
/**
* @notice Represents a single pending configuration update.
* @param isQueued True once the update has been scheduled.
* @param unlockTimestamp Block timestamp after which the update may be applied.
* @param newValue ABI-encoded next value for the parameter.
*/
struct Timelock {
bool isQueued;
uint48 unlockTimestamp;
bytes newValue;
}
// -------------------------------------------------------------------------
// Internal functions
// -------------------------------------------------------------------------
/**
* @notice Executes a pending timelock, returning the encoded new value.
*
* Reverts if the lock was not queued or has not yet expired. On success
* the record is deleted from storage before the value is returned, so a
* re-entrant call cannot replay the same update.
*
* @param key The configuration key to execute.
* @param classId The share-class the lock belongs to.
* @param store The vault storage struct that holds the timelocks mapping.
* @return ABI-encoded new parameter value.
*/
function applyTimelock(bytes4 key, uint8 classId, EigenYieldsVaultStorageData storage store)
internal
returns (bytes memory)
{
bytes4 compositeKey = getKey(key, classId);
Timelock memory pending = store.timelocks[compositeKey];
if (!pending.isQueued) {
revert TimelockNotQueued(key, classId);
}
if (pending.unlockTimestamp > Time.timestamp()) {
revert TimelockNotExpired(key, classId, pending.unlockTimestamp);
}
delete store.timelocks[compositeKey];
return pending.newValue;
}
/**
* @notice Derives the namespaced storage key for a given config key and class.
* @param key Base configuration key.
* @param classId Share-class identifier that scopes the entry.
* @return Four-byte composite key used as a mapping index.
*/
function getKey(bytes4 key, uint8 classId) internal pure returns (bytes4) {
return bytes4(keccak256(abi.encodePacked(key, classId)));
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@eigenyields-script/=script/",
"@eigenyields-vault/=src/",
"@eigenyields-test/=test/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"forge-std/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.