Verified contractExactBUSL-1.1
ObsoleteAvsGovernance
Address0x8b158361896ae4159fe8e771e8da65a6f76ff8ce
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.25
- Same code
Only this contract
Details
- Compiler
- solc 0.8.25+commit.b61c2a91
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- paris
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 21,872,438
- Creation transaction
- 0x8afce748cf…1ba92d48a8
59 files
- lib/contracts/src/NetworkManagement/L1/ObsoleteAvsGovernance.solmain18.74 KB
- lib/contracts/lib/core/src/contracts/VaultFactory.sol334 B
- lib/contracts/lib/core/src/contracts/common/MigratableEntityProxy.sol1.6 KB
- lib/contracts/lib/core/src/contracts/common/MigratablesFactory.sol3.47 KB
- lib/contracts/lib/core/src/contracts/common/Registry.sol1.27 KB
- lib/contracts/lib/core/src/contracts/service/NetworkMiddlewareService.sol1.08 KB
- lib/contracts/lib/core/src/interfaces/INetworkRegistry.sol297 B
- lib/contracts/lib/core/src/interfaces/IVaultFactory.sol178 B
- lib/contracts/lib/core/src/interfaces/common/IMigratableEntity.sol1.13 KB
- lib/contracts/lib/core/src/interfaces/common/IMigratableEntityProxy.sol426 B
- lib/contracts/lib/core/src/interfaces/common/IMigratablesFactory.sol3.16 KB
- lib/contracts/lib/core/src/interfaces/common/IRegistry.sol909 B
- lib/contracts/lib/core/src/interfaces/service/INetworkMiddlewareService.sol1.02 KB
- lib/contracts/lib/core/src/interfaces/service/IOptInService.sol4.01 KB
- lib/contracts/lib/eigenlayer-contracts/src/contracts/interfaces/IAVSDirectory.sol3.75 KB
- lib/contracts/lib/eigenlayer-contracts/src/contracts/interfaces/IRewardsCoordinator.sol25.78 KB
- lib/contracts/lib/eigenlayer-contracts/src/contracts/interfaces/ISignatureUtils.sol1.07 KB
- lib/contracts/lib/eigenlayer-contracts/src/contracts/interfaces/IStrategy.sol6.1 KB
- lib/contracts/src/NetworkManagement/Common/BLS.sol14.81 KB
- lib/contracts/src/NetworkManagement/Common/BLSAuthLibrary.sol2.19 KB
- lib/contracts/src/NetworkManagement/Common/MessagesLibrary.sol4.55 KB
- lib/contracts/src/NetworkManagement/Common/ModExp.sol25.06 KB
- lib/contracts/src/NetworkManagement/Common/PausableFlows.sol3.56 KB
- lib/contracts/src/NetworkManagement/Common/PausableFlowsStorage.sol1.35 KB
- lib/contracts/src/NetworkManagement/Common/PauserRolesLibrary.sol1.63 KB
- lib/contracts/src/NetworkManagement/Common/RolesLibrary.sol2.01 KB
- lib/contracts/src/NetworkManagement/Common/SignedAuthTokenLibrary.sol1.82 KB
- lib/contracts/src/NetworkManagement/Common/interfaces/IAvsTreasury.sol3.15 KB
- lib/contracts/src/NetworkManagement/Common/interfaces/IBLSAuthSingleton.sol1.04 KB
- lib/contracts/src/NetworkManagement/Common/interfaces/IMessageHandler.sol916 B
- lib/contracts/src/NetworkManagement/Common/interfaces/IPausableFlows.sol1.31 KB
- lib/contracts/src/NetworkManagement/L1/AvsGovernancePausable.sol2.51 KB
- lib/contracts/src/NetworkManagement/L1/AvsGovernanceStorage.sol3.01 KB
- lib/contracts/src/NetworkManagement/L1/interfaces/IAvsGovernance.sol7.37 KB
- lib/contracts/src/NetworkManagement/L1/interfaces/IAvsGovernanceLogic.sol725 B
- lib/contracts/src/NetworkManagement/L1/interfaces/IObsoleteAvsGovernance.sol4.27 KB
- lib/contracts/src/NetworkManagement/L1/interfaces/IOthenticRegistry.sol3.2 KB
- lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol8.28 KB
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol8.91 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol1.19 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol4.36 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol1.18 KB
- lib/openzeppelin-contracts/contracts/access/IAccessControl.sol3.26 KB
- lib/openzeppelin-contracts/contracts/access/Ownable.sol3.1 KB
- lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Proxy.sol1.72 KB
- lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol6.72 KB
- lib/openzeppelin-contracts/contracts/proxy/Proxy.sol2.67 KB
- lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol472 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol6.26 KB
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol3.93 KB
- lib/openzeppelin-contracts/contracts/utils/Strings.sol3.1 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol7.73 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol3.76 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol869 B
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol15.12 KB
- lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol1.26 KB
- lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol12.97 KB
lib/contracts/src/NetworkManagement/L1/ObsoleteAvsGovernance.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.25;
/*______ __ __ __ __
/ \ / | / | / | / |
/$$$$$$ | _$$ |_ $$ |____ ______ _______ _$$ |_ $$/ _______
$$ | $$ |/ $$ | $$ \ / \ / \ / $$ | / | / |
$$ | $$ |$$$$$$/ $$$$$$$ |/$$$$$$ |$$$$$$$ |$$$$$$/ $$ |/$$$$$$$/
$$ | $$ | $$ | __ $$ | $$ |$$ $$ |$$ | $$ | $$ | __ $$ |$$ |
$$ \__$$ | $$ |/ |$$ | $$ |$$$$$$$$/ $$ | $$ | $$ |/ |$$ |$$ \_____
$$ $$/ $$ $$/ $$ | $$ |$$ |$$ | $$ | $$ $$/ $$ |$$ |
$$$$$$/ $$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$$$/ $$/ $$$$$$$/
*/
import {AvsGovernanceStorage, AvsGovernanceStorageData} from "@othentic/NetworkManagement/L1/AvsGovernanceStorage.sol";
import {AvsGovernancePausable} from "@othentic/NetworkManagement/L1/AvsGovernancePausable.sol";
import {IAvsGovernance} from "@othentic/NetworkManagement/L1/interfaces/IAvsGovernance.sol";
import {IObsoleteAvsGovernance} from "@othentic/NetworkManagement/L1/interfaces/IObsoleteAvsGovernance.sol";
import {IOthenticRegistry} from "@othentic/NetworkManagement/L1/interfaces/IOthenticRegistry.sol";
import {IAvsGovernanceLogic} from "@othentic/NetworkManagement/L1/interfaces/IAvsGovernanceLogic.sol";
import {ISignatureUtils} from "@eigenlayer/contracts/interfaces/ISignatureUtils.sol";
import {IBLSAuthSingleton} from "@othentic/NetworkManagement/Common/interfaces/IBLSAuthSingleton.sol";
import {RolesLibrary} from "@othentic/NetworkManagement/Common/RolesLibrary.sol";
import {PauserRolesLibrary} from "@othentic/NetworkManagement/Common/PauserRolesLibrary.sol";
import {SignedAuthTokenLibrary} from "@othentic/NetworkManagement/Common/SignedAuthTokenLibrary.sol";
import {BLSAuthLibrary} from "@othentic/NetworkManagement/Common/BLSAuthLibrary.sol";
import {MessagesLibrary} from "@othentic/NetworkManagement/Common/MessagesLibrary.sol";
import {ReentrancyGuardUpgradeable} from "openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol";
contract ObsoleteAvsGovernance is
IObsoleteAvsGovernance,
AvsGovernancePausable,
ReentrancyGuardUpgradeable
{
IOthenticRegistry private immutable OTHENTIC_REGISTRY;
using SignedAuthTokenLibrary for bytes;
modifier onlyRegisteredOperator() {
if (_getStorage().isOperatorRegistered[msg.sender] == 0)
revert OperatorNotRegistered();
_;
}
modifier onlyUnregisteredOperator() {
if (_getStorage().isOperatorRegistered[msg.sender] != 0)
revert OperatorAlreadyRegistered();
_;
}
constructor(IOthenticRegistry _othenticRegistry) {
if(address(_othenticRegistry) == address(0)) {
revert ZeroAddress();
}
OTHENTIC_REGISTRY = _othenticRegistry;
}
// obsolete - only supports EigenLayer registration
function registerAsAllowedOperator(
uint256[4] calldata _blsKey,
bytes calldata _authToken,
address _rewardsReceiver,
ISignatureUtils.SignatureWithSaltAndExpiry calldata _operatorSignature,
BLSAuthLibrary.Signature calldata _blsRegistrationSignature
)
external
onlyUnregisteredOperator
whenFlowNotPaused(PauserRolesLibrary.REGISTRATION_FLOW)
nonReentrant
{
AvsGovernanceStorageData storage _sd = _getStorage();
if (!_sd.isAllowlisted) revert AllowlistDisabled();
if (
!_authToken.verifyAuthTokenForAddress(
address(this),
msg.sender,
_sd.allowlistSigner
)
) revert InvalidAllowlistAuthToken();
_registerAsOperator(
_sd,
msg.sender,
_blsKey,
_blsRegistrationSignature,
_rewardsReceiver
);
_sd.avsDirectoryContract.registerOperatorToAVS(
msg.sender,
_operatorSignature
);
}
// obsolete - only supports EigenLayer registration
function registerAsOperator(
uint256[4] calldata _blsKey,
address _rewardsReceiver,
ISignatureUtils.SignatureWithSaltAndExpiry calldata _operatorSignature,
BLSAuthLibrary.Signature calldata _blsRegistrationSignature
)
external
onlyUnregisteredOperator
whenFlowNotPaused(PauserRolesLibrary.REGISTRATION_FLOW)
nonReentrant
{
AvsGovernanceStorageData storage _sd = _getStorage();
if (_sd.isAllowlisted) revert AllowlistEnabled();
_registerAsOperator(
_sd,
msg.sender,
_blsKey,
_blsRegistrationSignature,
_rewardsReceiver
);
_sd.avsDirectoryContract.registerOperatorToAVS(
msg.sender,
_operatorSignature
);
}
// @obsolete - auth token required
function registerOperatorToEigenLayer(ISignatureUtils.SignatureWithSaltAndExpiry memory /*_eigenSig*/) pure external {
revert("Obsolete missing the auth token please add or update your CLI");
}
// @obsolete - auth token required
function registerOperatorToSymbiotic(IAvsGovernance.SymbioticOptInSignature memory /*_symbioticSig*/) pure external {
revert("Obsolete missing the auth token please add or update your CLI");
}
// @obsolete - Use avsTreasury()
function vault() external view returns (address) {
return address(_getStorage().avsTreasury);
}
// @obsolete - Use minStakeAmountPerStakingContract()
function minSharesForStrategy(
address _stakingContract
) external view returns (uint256) {
return _getStorage().minStakeAmountPerStakingContract[_stakingContract];
}
// @obsolete - Use stakingContracts()
function strategies() external view returns (address[] memory) {
return _getStorage().stakingContracts;
}
// @obsolete - Use multiplier()
function strategyMultiplier(
address _stakingContract
) external view returns (uint256) {
return _getStorage().multipliers[_stakingContract];
}
// @obsolete - Use setMinStakesForStakingContract
function setMinSharesForStrategy(
address _stakingContract,
uint256 _minShares
) external onlyRole(RolesLibrary.AVS_GOVERNANCE_MULTISIG) {
setMinStakesForStakingContract(_stakingContract, _minShares);
}
// @obsolete - Use setStakingContractMultiplier
function setStrategyMultiplier(
IAvsGovernance.VotingPowerMultiplier calldata _votingPowerMultiplier
) external onlyRole(RolesLibrary.MULTIPLIER_SYNCER) {
_setStakingContractMultiplier(_getStorage(), _votingPowerMultiplier);
}
// @obsolete - Use setStakingContractMultiplierBatch
function setStrategyMultiplierBatch(
IAvsGovernance.VotingPowerMultiplier[] calldata _votingPowerMultipliers
) external onlyRole(RolesLibrary.MULTIPLIER_SYNCER) {
setStakingContractMultiplierBatch(_votingPowerMultipliers);
}
// @obsolete - need to use registerAvsToEigenLayer
function updateAVSMetadataURI(
string calldata metadataURI
) external onlyRole(RolesLibrary.AVS_GOVERNANCE_MULTISIG) {
_getStorage().avsDirectoryContract.updateAVSMetadataURI(metadataURI);
}
// obsolete - only supports EigenLayer, use setSupportedStakingContracts
function setSupportedStrategies(
address[] memory _strategies
)
external
onlyRole(RolesLibrary.AVS_GOVERNANCE_MULTISIG)
whenFlowNotPaused(PauserRolesLibrary.SET_SUPPORTED_STRATEGIES_FLOW)
{
AvsGovernanceStorageData storage _sd = _getStorage();
IAvsGovernance.StakingContractInfo[]
memory _stakingContractsDetails = new IAvsGovernance.StakingContractInfo[](
_strategies.length
);
for (uint256 i = 0; i < _strategies.length; ) {
_stakingContractsDetails[i] = IAvsGovernance.StakingContractInfo(
_strategies[i],
IAvsGovernance.SharedSecurityProvider.EigenLayer
);
unchecked {
++i;
}
}
_setSupportedStakingContracts(_sd, _stakingContractsDetails);
}
// obsolete - only supports EigenLayer deregistration
function unregisterAsOperator()
external
onlyRegisteredOperator
whenFlowNotPaused(PauserRolesLibrary.REGISTRATION_FLOW)
nonReentrant
{
AvsGovernanceStorageData storage _sd = _getStorage();
_unregisterAsOperator(msg.sender);
_sd.avsDirectoryContract.deregisterOperatorFromAVS(msg.sender);
}
function setStakingContractMultiplierBatch(
IAvsGovernance.VotingPowerMultiplier[] calldata _votingPowerMultipliers
) public onlyRole(RolesLibrary.MULTIPLIER_SYNCER) {
AvsGovernanceStorageData storage _sd = _getStorage();
for (uint256 i = 0; i < _votingPowerMultipliers.length; ) {
_setStakingContractMultiplier(_sd, _votingPowerMultipliers[i]);
unchecked {
++i;
}
}
}
// @obsolete - Use setMinStakesForStakingContract
function setMinStakesForStakingContract(
address _stakingContract,
uint256 _minShares
) public onlyRole(RolesLibrary.AVS_GOVERNANCE_MULTISIG) {
AvsGovernanceStorageData storage _sd = AvsGovernanceStorage.load();
bool _stakingContractFound = false;
for (uint256 i = 0; i < _sd.stakingContracts.length; i++) {
if (_sd.stakingContracts[i] == _stakingContract) {
_stakingContractFound = true;
break;
}
}
if (!_stakingContractFound) revert InvalidStakingContract();
_sd.minStakeAmountPerStakingContract[_stakingContract] = _minShares;
emit MinStakeForStakingContractSet(_stakingContract, _minShares);
}
function _setSupportedStakingContracts(
AvsGovernanceStorageData storage _sd,
IAvsGovernance.StakingContractInfo[] memory _stakingContractsDetails
) internal {
delete _sd.stakingContracts;
for (uint256 i = 0; i < _stakingContractsDetails.length; ) {
IAvsGovernance.StakingContractInfo
memory _stakingContractDetails = _stakingContractsDetails[i];
if (_stakingContractDetails.stakingContract == address(0))
revert InvalidStakingContract();
_sd.stakingContracts.push(_stakingContractDetails.stakingContract);
_sd.stakingContractToSharedSecurityProvider[
_stakingContractDetails.stakingContract
] = _stakingContractDetails.sharedSecurityProvider;
unchecked {
++i;
}
}
emit setNewSupportedStakingContracts(_sd.stakingContracts);
}
function _registerAsOperator(
AvsGovernanceStorageData storage _sd,
address _operator,
uint256[4] calldata _blsKey,
BLSAuthLibrary.Signature calldata _blsRegistrationSignature,
address _rewardsReceiver
) internal {
if (_rewardsReceiver == address(0)) revert InvalidRewardsReceiver();
_setRewardsReceiver(_sd, _rewardsReceiver);
uint256 _numOfOperatorsLimit = _sd.numOfOperatorsLimit;
if (_sd.numOfActiveOperators >= _numOfOperatorsLimit)
revert NumOfOperatorsLimitReached(_numOfOperatorsLimit);
if (
!IBLSAuthSingleton(_sd.blsAuthSingleton).isValidSignature(
_blsRegistrationSignature,
_operator,
address(this),
_blsKey
)
) revert InvalidBlsRegistrationSignature();
IAvsGovernanceLogic _avsGovernanceLogic = _sd.avsGovernanceLogic;
{
bool _isAvsGovernanceLogicSet = address(_avsGovernanceLogic) !=
address(0);
(
IAvsGovernance.StakingContractDetails[]
memory _minStakePerStakingContract,
IAvsGovernance.VotingPowerMultiplier[]
memory _votingPowerMultipliers
) = _calculateStakingContractDetailsAndMultipliers(
_sd,
_sd.stakingContracts
);
uint256 _votingPower = _getVotingPower(
_sd,
_operator,
_votingPowerMultipliers
);
{
bool _isActive = (_votingPower >= _sd.minVotingPower) &&
OTHENTIC_REGISTRY.isValidStakeAmount(
_operator,
_minStakePerStakingContract,
address(this)
);
if (!_isActive) revert NotEnoughVotingPower();
if (_isAvsGovernanceLogicSet) {
_avsGovernanceLogic.beforeOperatorRegistered(
_operator,
_votingPower,
_blsKey,
_rewardsReceiver
);
}
_triggerL2OperatorRegistration(
_sd,
_operator,
_votingPower,
_blsKey,
_rewardsReceiver
);
++_sd.numOfActiveOperators;
_sd.isOperatorRegistered[_operator] = 1;
}
if (_isAvsGovernanceLogicSet) {
_avsGovernanceLogic.afterOperatorRegistered(
_operator,
_votingPower,
_blsKey,
_rewardsReceiver
);
}
}
emit OperatorRegistered(_operator, _blsKey);
}
function _unregisterAsOperator(address _operator) internal {
AvsGovernanceStorageData storage _sd = _getStorage();
IAvsGovernanceLogic _avsGovernanceLogic = _sd.avsGovernanceLogic;
bool _isAvsGovernanceLogicSet = address(_avsGovernanceLogic) !=
address(0);
if (_isAvsGovernanceLogicSet) {
_avsGovernanceLogic.beforeOperatorUnregistered(_operator);
}
_triggerL2Unregister(_sd, _operator);
--_sd.numOfActiveOperators;
_sd.isOperatorRegistered[_operator] = 0;
if (_isAvsGovernanceLogicSet) {
_avsGovernanceLogic.afterOperatorUnregistered(_operator);
}
emit OperatorUnregistered(_operator);
}
function _triggerL2Unregister(
AvsGovernanceStorageData storage _sd,
address _operator
) internal {
bytes memory _unRegisterMessage = MessagesLibrary
.BuildUnregisterRequestMessage(_operator);
_sd.messageHandler.sendMessage(abi.encode(_unRegisterMessage, uint32(0)));
}
function _triggerL2OperatorRegistration(
AvsGovernanceStorageData storage _sd,
address _operator,
uint256 _votingPower,
uint256[4] calldata _blsKey,
address _rewardsReceiver
) internal {
bytes memory _registerOperatorMessage = MessagesLibrary
.BuildRegisterOperatorMessage(
_operator,
_votingPower,
_blsKey,
_rewardsReceiver
);
_sd.messageHandler.sendMessage(abi.encode(_registerOperatorMessage, uint32(0)));
}
function _setRewardsReceiver(
AvsGovernanceStorageData storage _sd,
address _rewardsReceiver
) private {
_sd.rewardsReceiver[msg.sender] = _rewardsReceiver;
emit SetRewardsReceiver(msg.sender, _rewardsReceiver);
}
function _calculateStakingContractDetailsAndMultipliers(
AvsGovernanceStorageData storage _sd,
address[] memory _stakingContracts
)
internal
view
returns (
IAvsGovernance.StakingContractDetails[] memory,
IAvsGovernance.VotingPowerMultiplier[] memory
)
{
IAvsGovernance.StakingContractDetails[]
memory _minStakeAmountPerStakingContract = new IAvsGovernance.StakingContractDetails[](
_stakingContracts.length
);
IAvsGovernance.VotingPowerMultiplier[]
memory _votingPowerMultipliers = new IAvsGovernance.VotingPowerMultiplier[](
_stakingContracts.length
);
for (uint256 i = 0; i < _stakingContracts.length; ) {
address _stakingContract = _stakingContracts[i];
IAvsGovernance.SharedSecurityProvider _sharedSecurityProvider = _sd
.stakingContractToSharedSecurityProvider[_stakingContract];
_minStakeAmountPerStakingContract[i] = IAvsGovernance
.StakingContractDetails(
_stakingContract,
_sd.minStakeAmountPerStakingContract[_stakingContract],
_sharedSecurityProvider
);
uint256 _multiplier = _sd.multipliers[_stakingContract];
if (_multiplier == 0) {
_multiplier = 1;
}
_votingPowerMultipliers[i] = IAvsGovernance.VotingPowerMultiplier(
_stakingContract,
_multiplier,
_sharedSecurityProvider
);
unchecked {
++i;
}
}
return (_minStakeAmountPerStakingContract, _votingPowerMultipliers);
}
function _getVotingPower(
AvsGovernanceStorageData storage _sd,
address _operator,
IAvsGovernance.VotingPowerMultiplier[] memory _votingPowerMultipliers
) private view returns (uint256) {
uint256 _maxEffBalance = _sd.maxEffectiveBalance;
uint256 _votingPower = OTHENTIC_REGISTRY.getVotingPower(
_operator,
_votingPowerMultipliers,
address(this)
);
if (_votingPower > _maxEffBalance && _maxEffBalance > 0) {
_votingPower = _maxEffBalance;
}
return _votingPower;
}
function _setStakingContractMultiplier(
AvsGovernanceStorageData storage _sd,
IAvsGovernance.VotingPowerMultiplier calldata _votingPowerMultiplier
) private {
_sd.multipliers[
_votingPowerMultiplier.stakingContract
] = _votingPowerMultiplier.multiplier;
emit SetStakingContractMultiplier(
_votingPowerMultiplier.stakingContract,
_votingPowerMultiplier.multiplier
);
}
function _getStorage()
internal
pure
returns (AvsGovernanceStorageData storage _sd)
{
return AvsGovernanceStorage.load();
}
}
lib/contracts/lib/core/src/contracts/VaultFactory.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import {MigratablesFactory} from "./common/MigratablesFactory.sol";
import {IVaultFactory} from "../interfaces/IVaultFactory.sol";
contract VaultFactory is MigratablesFactory, IVaultFactory {
constructor(
address owner_
) MigratablesFactory(owner_) {}
}
lib/contracts/lib/core/src/contracts/common/MigratableEntityProxy.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import {IMigratableEntityProxy} from "../../interfaces/common/IMigratableEntityProxy.sol";
import {ERC1967Proxy} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
contract MigratableEntityProxy is ERC1967Proxy, IMigratableEntityProxy {
// An immutable address for the admin to avoid unnecessary SLOADs before each call.
address private immutable _admin;
/**
* @dev The proxy caller is the current admin, and can't fallback to the proxy target.
*/
error ProxyDeniedAdminAccess();
/**
* @dev Initializes an upgradeable proxy managed by `msg.sender`,
* backed by the implementation at `logic`, and optionally initialized with `data` as explained in
* {ERC1967Proxy-constructor}.
*/
constructor(address logic, bytes memory data) ERC1967Proxy(logic, data) {
_admin = msg.sender;
// Set the storage value and emit an event for ERC-1967 compatibility
ERC1967Utils.changeAdmin(_proxyAdmin());
}
/**
* @inheritdoc IMigratableEntityProxy
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) external {
if (msg.sender != _proxyAdmin()) {
revert ProxyDeniedAdminAccess();
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
}
/**
* @dev Returns the admin of this proxy.
*/
function _proxyAdmin() internal view returns (address) {
return _admin;
}
}
lib/contracts/lib/core/src/contracts/common/MigratablesFactory.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import {MigratableEntityProxy} from "./MigratableEntityProxy.sol";
import {Registry} from "./Registry.sol";
import {IMigratableEntityProxy} from "../../interfaces/common/IMigratableEntityProxy.sol";
import {IMigratableEntity} from "../../interfaces/common/IMigratableEntity.sol";
import {IMigratablesFactory} from "../../interfaces/common/IMigratablesFactory.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
contract MigratablesFactory is Registry, Ownable, IMigratablesFactory {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
/**
* @inheritdoc IMigratablesFactory
*/
mapping(uint64 version => bool value) public blacklisted;
EnumerableSet.AddressSet private _whitelistedImplementations;
modifier checkVersion(
uint64 version
) {
if (version == 0 || version > lastVersion()) {
revert InvalidVersion();
}
_;
}
constructor(
address owner_
) Ownable(owner_) {}
/**
* @inheritdoc IMigratablesFactory
*/
function lastVersion() public view returns (uint64) {
return uint64(_whitelistedImplementations.length());
}
/**
* @inheritdoc IMigratablesFactory
*/
function implementation(
uint64 version
) public view checkVersion(version) returns (address) {
return _whitelistedImplementations.at(version - 1);
}
/**
* @inheritdoc IMigratablesFactory
*/
function whitelist(
address implementation_
) external onlyOwner {
if (IMigratableEntity(implementation_).FACTORY() != address(this)) {
revert InvalidImplementation();
}
if (!_whitelistedImplementations.add(implementation_)) {
revert AlreadyWhitelisted();
}
emit Whitelist(implementation_);
}
/**
* @inheritdoc IMigratablesFactory
*/
function blacklist(
uint64 version
) external onlyOwner checkVersion(version) {
if (blacklisted[version]) {
revert AlreadyBlacklisted();
}
blacklisted[version] = true;
emit Blacklist(version);
}
/**
* @inheritdoc IMigratablesFactory
*/
function create(uint64 version, address owner_, bytes calldata data) external returns (address entity_) {
entity_ = address(
new MigratableEntityProxy{salt: keccak256(abi.encode(totalEntities(), version, owner_, data))}(
implementation(version), abi.encodeCall(IMigratableEntity.initialize, (version, owner_, data))
)
);
_addEntity(entity_);
}
/**
* @inheritdoc IMigratablesFactory
*/
function migrate(address entity_, uint64 newVersion, bytes calldata data) external checkEntity(entity_) {
if (msg.sender != Ownable(entity_).owner()) {
revert NotOwner();
}
if (newVersion <= IMigratableEntity(entity_).version()) {
revert OldVersion();
}
IMigratableEntityProxy(entity_).upgradeToAndCall(
implementation(newVersion), abi.encodeCall(IMigratableEntity.migrate, (newVersion, data))
);
emit Migrate(entity_, newVersion);
}
}
lib/contracts/lib/core/src/contracts/common/Registry.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import {IRegistry} from "../../interfaces/common/IRegistry.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
abstract contract Registry is IRegistry {
using EnumerableSet for EnumerableSet.AddressSet;
EnumerableSet.AddressSet private _entities;
modifier checkEntity(
address account
) {
_checkEntity(account);
_;
}
/**
* @inheritdoc IRegistry
*/
function isEntity(
address entity_
) public view returns (bool) {
return _entities.contains(entity_);
}
/**
* @inheritdoc IRegistry
*/
function totalEntities() public view returns (uint256) {
return _entities.length();
}
/**
* @inheritdoc IRegistry
*/
function entity(
uint256 index
) public view returns (address) {
return _entities.at(index);
}
function _addEntity(
address entity_
) internal {
_entities.add(entity_);
emit AddEntity(entity_);
}
function _checkEntity(
address account
) internal view {
if (!isEntity(account)) {
revert EntityNotExist();
}
}
}
lib/contracts/lib/core/src/contracts/service/NetworkMiddlewareService.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import {INetworkMiddlewareService} from "../../interfaces/service/INetworkMiddlewareService.sol";
import {IRegistry} from "../../interfaces/common/IRegistry.sol";
contract NetworkMiddlewareService is INetworkMiddlewareService {
/**
* @inheritdoc INetworkMiddlewareService
*/
address public immutable NETWORK_REGISTRY;
/**
* @inheritdoc INetworkMiddlewareService
*/
mapping(address network => address value) public middleware;
constructor(
address networkRegistry
) {
NETWORK_REGISTRY = networkRegistry;
}
/**
* @inheritdoc INetworkMiddlewareService
*/
function setMiddleware(
address middleware_
) external {
if (!IRegistry(NETWORK_REGISTRY).isEntity(msg.sender)) {
revert NotNetwork();
}
if (middleware[msg.sender] == middleware_) {
revert AlreadySet();
}
middleware[msg.sender] = middleware_;
emit SetMiddleware(msg.sender, middleware_);
}
}
lib/contracts/lib/core/src/interfaces/INetworkRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IRegistry} from "./common/IRegistry.sol";
interface INetworkRegistry is IRegistry {
error NetworkAlreadyRegistered();
/**
* @notice Register the caller as a network.
*/
function registerNetwork() external;
}
lib/contracts/lib/core/src/interfaces/IVaultFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IMigratablesFactory} from "./common/IMigratablesFactory.sol";
interface IVaultFactory is IMigratablesFactory {}
lib/contracts/lib/core/src/interfaces/common/IMigratableEntity.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IMigratableEntity {
error AlreadyInitialized();
error NotFactory();
error NotInitialized();
/**
* @notice Get the factory's address.
* @return address of the factory
*/
function FACTORY() external view returns (address);
/**
* @notice Get the entity's version.
* @return version of the entity
* @dev Starts from 1.
*/
function version() external view returns (uint64);
/**
* @notice Initialize this entity contract by using a given data and setting a particular version and owner.
* @param initialVersion initial version of the entity
* @param owner initial owner of the entity
* @param data some data to use
*/
function initialize(uint64 initialVersion, address owner, bytes calldata data) external;
/**
* @notice Migrate this entity to a particular newer version using a given data.
* @param newVersion new version of the entity
* @param data some data to use
*/
function migrate(uint64 newVersion, bytes calldata data) external;
}
lib/contracts/lib/core/src/interfaces/common/IMigratableEntityProxy.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IMigratableEntityProxy {
/**
* @notice Upgrade the proxy to a new implementation and call a function on the new implementation.
* @param newImplementation address of the new implementation
* @param data data to call on the new implementation
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) external;
}
lib/contracts/lib/core/src/interfaces/common/IMigratablesFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IRegistry} from "./IRegistry.sol";
interface IMigratablesFactory is IRegistry {
error AlreadyBlacklisted();
error AlreadyWhitelisted();
error InvalidImplementation();
error InvalidVersion();
error NotOwner();
error OldVersion();
/**
* @notice Emitted when a new implementation is whitelisted.
* @param implementation address of the new implementation
*/
event Whitelist(address indexed implementation);
/**
* @notice Emitted when a version is blacklisted (e.g., in case of invalid implementation).
* @param version version that was blacklisted
* @dev The given version is still deployable.
*/
event Blacklist(uint64 indexed version);
/**
* @notice Emitted when an entity is migrated to a new version.
* @param entity address of the entity
* @param newVersion new version of the entity
*/
event Migrate(address indexed entity, uint64 newVersion);
/**
* @notice Get the last available version.
* @return version of the last implementation
* @dev If zero, no implementations are whitelisted.
*/
function lastVersion() external view returns (uint64);
/**
* @notice Get the implementation for a given version.
* @param version version to get the implementation for
* @return address of the implementation
* @dev Reverts when an invalid version.
*/
function implementation(
uint64 version
) external view returns (address);
/**
* @notice Get if a version is blacklisted (e.g., in case of invalid implementation).
* @param version version to check
* @return whether the version is blacklisted
* @dev The given version is still deployable.
*/
function blacklisted(
uint64 version
) external view returns (bool);
/**
* @notice Whitelist a new implementation for entities.
* @param implementation address of the new implementation
*/
function whitelist(
address implementation
) external;
/**
* @notice Blacklist a version of entities.
* @param version version to blacklist
* @dev The given version will still be deployable.
*/
function blacklist(
uint64 version
) external;
/**
* @notice Create a new entity at the factory.
* @param version entity's version to use
* @param owner initial owner of the entity
* @param data initial data for the entity creation
* @return address of the entity
* @dev CREATE2 salt is constructed from the given parameters.
*/
function create(uint64 version, address owner, bytes calldata data) external returns (address);
/**
* @notice Migrate a given entity to a given newer version.
* @param entity address of the entity to migrate
* @param newVersion new version to migrate to
* @param data some data to reinitialize the contract with
* @dev Only the entity's owner can call this function.
*/
function migrate(address entity, uint64 newVersion, bytes calldata data) external;
}
lib/contracts/lib/core/src/interfaces/common/IRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IRegistry {
error EntityNotExist();
/**
* @notice Emitted when an entity is added.
* @param entity address of the added entity
*/
event AddEntity(address indexed entity);
/**
* @notice Get if a given address is an entity.
* @param account address to check
* @return if the given address is an entity
*/
function isEntity(
address account
) external view returns (bool);
/**
* @notice Get a total number of entities.
* @return total number of entities added
*/
function totalEntities() external view returns (uint256);
/**
* @notice Get an entity given its index.
* @param index index of the entity to get
* @return address of the entity
*/
function entity(
uint256 index
) external view returns (address);
}
lib/contracts/lib/core/src/interfaces/service/INetworkMiddlewareService.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface INetworkMiddlewareService {
error AlreadySet();
error NotNetwork();
/**
* @notice Emitted when a middleware is set for a network.
* @param network address of the network
* @param middleware new middleware of the network
*/
event SetMiddleware(address indexed network, address middleware);
/**
* @notice Get the network registry's address.
* @return address of the network registry
*/
function NETWORK_REGISTRY() external view returns (address);
/**
* @notice Get a given network's middleware.
* @param network address of the network
* @return middleware of the network
*/
function middleware(
address network
) external view returns (address);
/**
* @notice Set a new middleware for a calling network.
* @param middleware new middleware of the network
*/
function setMiddleware(
address middleware
) external;
}
lib/contracts/lib/core/src/interfaces/service/IOptInService.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IOptInService {
error AlreadyOptedIn();
error ExpiredSignature();
error InvalidSignature();
error NotOptedIn();
error NotWhereEntity();
error NotWho();
error OptOutCooldown();
/**
* @notice Emitted when a "who" opts into a "where" entity.
* @param who address of the "who"
* @param where address of the "where" entity
*/
event OptIn(address indexed who, address indexed where);
/**
* @notice Emitted when a "who" opts out from a "where" entity.
* @param who address of the "who"
* @param where address of the "where" entity
*/
event OptOut(address indexed who, address indexed where);
/**
* @notice Emitted when the nonce of a "who" to a "where" entity is increased.
* @param who address of the "who"
* @param where address of the "where" entity
*/
event IncreaseNonce(address indexed who, address indexed where);
/**
* @notice Get the "who" registry's address.
* @return address of the "who" registry
*/
function WHO_REGISTRY() external view returns (address);
/**
* @notice Get the address of the registry where to opt-in.
* @return address of the "where" registry
*/
function WHERE_REGISTRY() external view returns (address);
/**
* @notice Get if a given "who" is opted-in to a particular "where" entity at a given timestamp using a hint.
* @param who address of the "who"
* @param where address of the "where" entity
* @param timestamp time point to get if the "who" is opted-in at
* @param hint hint for the checkpoint index
* @return if the "who" is opted-in at the given timestamp
*/
function isOptedInAt(
address who,
address where,
uint48 timestamp,
bytes calldata hint
) external view returns (bool);
/**
* @notice Check if a given "who" is opted-in to a particular "where" entity.
* @param who address of the "who"
* @param where address of the "where" entity
* @return if the "who" is opted-in
*/
function isOptedIn(address who, address where) external view returns (bool);
/**
* @notice Get the nonce of a given "who" to a particular "where" entity.
* @param who address of the "who"
* @param where address of the "where" entity
* @return nonce
*/
function nonces(address who, address where) external view returns (uint256);
/**
* @notice Opt-in a calling "who" to a particular "where" entity.
* @param where address of the "where" entity
*/
function optIn(
address where
) external;
/**
* @notice Opt-in a "who" to a particular "where" entity with a signature.
* @param who address of the "who"
* @param where address of the "where" entity
* @param deadline time point until the signature is valid (inclusively)
* @param signature signature of the "who"
*/
function optIn(address who, address where, uint48 deadline, bytes calldata signature) external;
/**
* @notice Opt-out a calling "who" from a particular "where" entity.
* @param where address of the "where" entity
*/
function optOut(
address where
) external;
/**
* @notice Opt-out a "who" from a particular "where" entity with a signature.
* @param who address of the "who"
* @param where address of the "where" entity
* @param deadline time point until the signature is valid (inclusively)
* @param signature signature of the "who"
*/
function optOut(address who, address where, uint48 deadline, bytes calldata signature) external;
/**
* @notice Increase the nonce of a given "who" to a particular "where" entity.
* @param where address of the "where" entity
* @dev It can be used to invalidate a given signature.
*/
function increaseNonce(
address where
) external;
}
lib/contracts/lib/eigenlayer-contracts/src/contracts/interfaces/IAVSDirectory.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.5.0;
import "./ISignatureUtils.sol";
interface IAVSDirectory is ISignatureUtils {
/// @notice Enum representing the status of an operator's registration with an AVS
enum OperatorAVSRegistrationStatus {
UNREGISTERED, // Operator not registered to AVS
REGISTERED // Operator registered to AVS
}
/**
* @notice Emitted when @param avs indicates that they are updating their MetadataURI string
* @dev Note that these strings are *never stored in storage* and are instead purely emitted in events for off-chain indexing
*/
event AVSMetadataURIUpdated(address indexed avs, string metadataURI);
/// @notice Emitted when an operator's registration status for an AVS is updated
event OperatorAVSRegistrationStatusUpdated(
address indexed operator, address indexed avs, OperatorAVSRegistrationStatus status
);
/**
* @notice Called by the AVS's service manager contract to register an operator with the avs.
* @param operator The address of the operator to register.
* @param operatorSignature The signature, salt, and expiry of the operator's signature.
*/
function registerOperatorToAVS(
address operator,
ISignatureUtils.SignatureWithSaltAndExpiry memory operatorSignature
) external;
/**
* @notice Called by an avs to deregister an operator with the avs.
* @param operator The address of the operator to deregister.
*/
function deregisterOperatorFromAVS(address operator) external;
/**
* @notice Called by an AVS to emit an `AVSMetadataURIUpdated` event indicating the information has updated.
* @param metadataURI The URI for metadata associated with an AVS
* @dev Note that the `metadataURI` is *never stored * and is only emitted in the `AVSMetadataURIUpdated` event
*/
function updateAVSMetadataURI(string calldata metadataURI) external;
/**
* @notice Returns whether or not the salt has already been used by the operator.
* @dev Salts is used in the `registerOperatorToAVS` function.
*/
function operatorSaltIsSpent(address operator, bytes32 salt) external view returns (bool);
/**
* @notice Calculates the digest hash to be signed by an operator to register with an AVS
* @param operator The account registering as an operator
* @param avs The address of the service manager contract for the AVS that the operator is registering to
* @param salt A unique and single use value associated with the approver signature.
* @param expiry Time after which the approver's signature becomes invalid
*/
function calculateOperatorAVSRegistrationDigestHash(
address operator,
address avs,
bytes32 salt,
uint256 expiry
) external view returns (bytes32);
/// @notice The EIP-712 typehash for the Registration struct used by the contract
function OPERATOR_AVS_REGISTRATION_TYPEHASH() external view returns (bytes32);
/**
* @notice Called by an operator to cancel a salt that has been used to register with an AVS.
* @param salt A unique and single use value associated with the approver signature.
*/
function cancelSalt(bytes32 salt) external;
/**
* @notice Getter function for the current EIP-712 domain separator for this contract.
*
* @dev The domain separator will change in the event of a fork that changes the ChainID.
* @dev By introducing a domain separator the DApp developers are guaranteed that there can be no signature collision.
* for more detailed information please read EIP-712.
*/
function domainSeparator() external view returns (bytes32);
}
lib/contracts/lib/eigenlayer-contracts/src/contracts/interfaces/IRewardsCoordinator.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IStrategy.sol";
/**
* @title Interface for the `IRewardsCoordinator` contract.
* @author Layr Labs, Inc.
* @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service
* @notice Allows AVSs to make "Rewards Submissions", which get distributed amongst the AVSs' confirmed
* Operators and the Stakers delegated to those Operators.
* Calculations are performed based on the completed RewardsSubmission, with the results posted in
* a Merkle root against which Stakers & Operators can make claims.
*/
interface IRewardsCoordinator {
/// STRUCTS ///
/**
* @notice A linear combination of strategies and multipliers for AVSs to weigh
* EigenLayer strategies.
* @param strategy The EigenLayer strategy to be used for the rewards submission
* @param multiplier The weight of the strategy in the rewards submission
*/
struct StrategyAndMultiplier {
IStrategy strategy;
uint96 multiplier;
}
/**
* @notice A reward struct for an operator
* @param operator The operator to be rewarded
* @param amount The reward amount for the operator
*/
struct OperatorReward {
address operator;
uint256 amount;
}
/**
* @notice A split struct for an Operator
* @param oldSplitBips The old split in basis points. This is the split that is active if `block.timestamp < activatedAt`
* @param newSplitBips The new split in basis points. This is the split that is active if `block.timestamp >= activatedAt`
* @param activatedAt The timestamp at which the split will be activated
*/
struct OperatorSplit {
uint16 oldSplitBips;
uint16 newSplitBips;
uint32 activatedAt;
}
/**
* Sliding Window for valid RewardsSubmission startTimestamp
*
* Scenario A: GENESIS_REWARDS_TIMESTAMP IS WITHIN RANGE
* <-----MAX_RETROACTIVE_LENGTH-----> t (block.timestamp) <---MAX_FUTURE_LENGTH--->
* <--------------------valid range for startTimestamp------------------------>
* ^
* GENESIS_REWARDS_TIMESTAMP
*
*
* Scenario B: GENESIS_REWARDS_TIMESTAMP IS OUT OF RANGE
* <-----MAX_RETROACTIVE_LENGTH-----> t (block.timestamp) <---MAX_FUTURE_LENGTH--->
* <------------------------valid range for startTimestamp------------------------>
* ^
* GENESIS_REWARDS_TIMESTAMP
* @notice RewardsSubmission struct submitted by AVSs when making rewards for their operators and stakers
* RewardsSubmission can be for a time range within the valid window for startTimestamp and must be within max duration.
* See `createAVSRewardsSubmission()` for more details.
* @param strategiesAndMultipliers The strategies and their relative weights
* cannot have duplicate strategies and need to be sorted in ascending address order
* @param token The rewards token to be distributed
* @param amount The total amount of tokens to be distributed
* @param startTimestamp The timestamp (seconds) at which the submission range is considered for distribution
* could start in the past or in the future but within a valid range. See the diagram above.
* @param duration The duration of the submission range in seconds. Must be <= MAX_REWARDS_DURATION
*/
struct RewardsSubmission {
StrategyAndMultiplier[] strategiesAndMultipliers;
IERC20 token;
uint256 amount;
uint32 startTimestamp;
uint32 duration;
}
/**
* @notice OperatorDirectedRewardsSubmission struct submitted by AVSs when making operator-directed rewards for their operators and stakers.
* @param strategiesAndMultipliers The strategies and their relative weights.
* @param token The rewards token to be distributed.
* @param operatorRewards The rewards for the operators.
* @param startTimestamp The timestamp (seconds) at which the submission range is considered for distribution.
* @param duration The duration of the submission range in seconds.
* @param description Describes what the rewards submission is for.
*/
struct OperatorDirectedRewardsSubmission {
StrategyAndMultiplier[] strategiesAndMultipliers;
IERC20 token;
OperatorReward[] operatorRewards;
uint32 startTimestamp;
uint32 duration;
string description;
}
/**
* @notice A distribution root is a merkle root of the distribution of earnings for a given period.
* The RewardsCoordinator stores all historical distribution roots so that earners can claim their earnings against older roots
* if they wish but the merkle tree contains the cumulative earnings of all earners and tokens for a given period so earners (or their claimers if set)
* only need to claim against the latest root to claim all available earnings.
* @param root The merkle root of the distribution
* @param rewardsCalculationEndTimestamp The timestamp (seconds) until which rewards have been calculated
* @param activatedAt The timestamp (seconds) at which the root can be claimed against
*/
struct DistributionRoot {
bytes32 root;
uint32 rewardsCalculationEndTimestamp;
uint32 activatedAt;
bool disabled;
}
/**
* @notice Internal leaf in the merkle tree for the earner's account leaf
* @param earner The address of the earner
* @param earnerTokenRoot The merkle root of the earner's token subtree
* Each leaf in the earner's token subtree is a TokenTreeMerkleLeaf
*/
struct EarnerTreeMerkleLeaf {
address earner;
bytes32 earnerTokenRoot;
}
/**
* @notice The actual leaves in the distribution merkle tree specifying the token earnings
* for the respective earner's subtree. Each leaf is a claimable amount of a token for an earner.
* @param token The token for which the earnings are being claimed
* @param cumulativeEarnings The cumulative earnings of the earner for the token
*/
struct TokenTreeMerkleLeaf {
IERC20 token;
uint256 cumulativeEarnings;
}
/**
* @notice A claim against a distribution root called by an
* earners claimer (could be the earner themselves). Each token claim will claim the difference
* between the cumulativeEarnings of the earner and the cumulativeClaimed of the claimer.
* Each claim can specify which of the earner's earned tokens they want to claim.
* See `processClaim()` for more details.
* @param rootIndex The index of the root in the list of DistributionRoots
* @param earnerIndex The index of the earner's account root in the merkle tree
* @param earnerTreeProof The proof of the earner's EarnerTreeMerkleLeaf against the merkle root
* @param earnerLeaf The earner's EarnerTreeMerkleLeaf struct, providing the earner address and earnerTokenRoot
* @param tokenIndices The indices of the token leaves in the earner's subtree
* @param tokenTreeProofs The proofs of the token leaves against the earner's earnerTokenRoot
* @param tokenLeaves The token leaves to be claimed
* @dev The merkle tree is structured with the merkle root at the top and EarnerTreeMerkleLeaf as internal leaves
* in the tree. Each earner leaf has its own subtree with TokenTreeMerkleLeaf as leaves in the subtree.
* To prove a claim against a specified rootIndex(which specifies the distributionRoot being used),
* the claim will first verify inclusion of the earner leaf in the tree against _distributionRoots[rootIndex].root.
* Then for each token, it will verify inclusion of the token leaf in the earner's subtree against the earner's earnerTokenRoot.
*/
struct RewardsMerkleClaim {
uint32 rootIndex;
uint32 earnerIndex;
bytes earnerTreeProof;
EarnerTreeMerkleLeaf earnerLeaf;
uint32[] tokenIndices;
bytes[] tokenTreeProofs;
TokenTreeMerkleLeaf[] tokenLeaves;
}
/// EVENTS ///
/// @notice emitted when an AVS creates a valid RewardsSubmission
event AVSRewardsSubmissionCreated(
address indexed avs,
uint256 indexed submissionNonce,
bytes32 indexed rewardsSubmissionHash,
RewardsSubmission rewardsSubmission
);
/// @notice emitted when a valid RewardsSubmission is created for all stakers by a valid submitter
event RewardsSubmissionForAllCreated(
address indexed submitter,
uint256 indexed submissionNonce,
bytes32 indexed rewardsSubmissionHash,
RewardsSubmission rewardsSubmission
);
/// @notice emitted when a valid RewardsSubmission is created when rewardAllStakersAndOperators is called
event RewardsSubmissionForAllEarnersCreated(
address indexed tokenHopper,
uint256 indexed submissionNonce,
bytes32 indexed rewardsSubmissionHash,
RewardsSubmission rewardsSubmission
);
/**
* @notice Emitted when an AVS creates a valid `OperatorDirectedRewardsSubmission`
* @param caller The address calling `createOperatorDirectedAVSRewardsSubmission`.
* @param avs The avs on behalf of which the operator-directed rewards are being submitted.
* @param operatorDirectedRewardsSubmissionHash Keccak256 hash of (`avs`, `submissionNonce` and `operatorDirectedRewardsSubmission`).
* @param submissionNonce Current nonce of the avs. Used to generate a unique submission hash.
* @param operatorDirectedRewardsSubmission The Operator-Directed Rewards Submission. Contains the token, start timestamp, duration, operator rewards, description and, strategy and multipliers.
*/
event OperatorDirectedAVSRewardsSubmissionCreated(
address indexed caller,
address indexed avs,
bytes32 indexed operatorDirectedRewardsSubmissionHash,
uint256 submissionNonce,
OperatorDirectedRewardsSubmission operatorDirectedRewardsSubmission
);
/// @notice rewardsUpdater is responsible for submiting DistributionRoots, only owner can set rewardsUpdater
event RewardsUpdaterSet(address indexed oldRewardsUpdater, address indexed newRewardsUpdater);
event RewardsForAllSubmitterSet(
address indexed rewardsForAllSubmitter,
bool indexed oldValue,
bool indexed newValue
);
event ActivationDelaySet(uint32 oldActivationDelay, uint32 newActivationDelay);
event DefaultOperatorSplitBipsSet(uint16 oldDefaultOperatorSplitBips, uint16 newDefaultOperatorSplitBips);
/**
* @notice Emitted when the operator split for an AVS is set.
* @param caller The address calling `setOperatorAVSSplit`.
* @param operator The operator on behalf of which the split is being set.
* @param avs The avs for which the split is being set by the operator.
* @param activatedAt The timestamp at which the split will be activated.
* @param oldOperatorAVSSplitBips The old split for the operator for the AVS.
* @param newOperatorAVSSplitBips The new split for the operator for the AVS.
*/
event OperatorAVSSplitBipsSet(
address indexed caller,
address indexed operator,
address indexed avs,
uint32 activatedAt,
uint16 oldOperatorAVSSplitBips,
uint16 newOperatorAVSSplitBips
);
/**
* @notice Emitted when the operator split for Programmatic Incentives is set.
* @param caller The address calling `setOperatorPISplit`.
* @param operator The operator on behalf of which the split is being set.
* @param activatedAt The timestamp at which the split will be activated.
* @param oldOperatorPISplitBips The old split for the operator for Programmatic Incentives.
* @param newOperatorPISplitBips The new split for the operator for Programmatic Incentives.
*/
event OperatorPISplitBipsSet(
address indexed caller,
address indexed operator,
uint32 activatedAt,
uint16 oldOperatorPISplitBips,
uint16 newOperatorPISplitBips
);
event ClaimerForSet(address indexed earner, address indexed oldClaimer, address indexed claimer);
/// @notice rootIndex is the specific array index of the newly created root in the storage array
event DistributionRootSubmitted(
uint32 indexed rootIndex,
bytes32 indexed root,
uint32 indexed rewardsCalculationEndTimestamp,
uint32 activatedAt
);
event DistributionRootDisabled(uint32 indexed rootIndex);
/// @notice root is one of the submitted distribution roots that was claimed against
event RewardsClaimed(
bytes32 root,
address indexed earner,
address indexed claimer,
address indexed recipient,
IERC20 token,
uint256 claimedAmount
);
/**
*
* VIEW FUNCTIONS
*
*/
/// @notice The address of the entity that can update the contract with new merkle roots
function rewardsUpdater() external view returns (address);
/**
* @notice The interval in seconds at which the calculation for a RewardsSubmission distribution is done.
* @dev Rewards Submission durations must be multiples of this interval.
*/
function CALCULATION_INTERVAL_SECONDS() external view returns (uint32);
/// @notice The maximum amount of time (seconds) that a RewardsSubmission can span over
function MAX_REWARDS_DURATION() external view returns (uint32);
/// @notice max amount of time (seconds) that a submission can start in the past
function MAX_RETROACTIVE_LENGTH() external view returns (uint32);
/// @notice max amount of time (seconds) that a submission can start in the future
function MAX_FUTURE_LENGTH() external view returns (uint32);
/// @notice absolute min timestamp (seconds) that a submission can start at
function GENESIS_REWARDS_TIMESTAMP() external view returns (uint32);
/// @notice Delay in timestamp (seconds) before a posted root can be claimed against
function activationDelay() external view returns (uint32);
/// @notice Mapping: earner => the address of the entity who can call `processClaim` on behalf of the earner
function claimerFor(address earner) external view returns (address);
/// @notice Mapping: claimer => token => total amount claimed
function cumulativeClaimed(address claimer, IERC20 token) external view returns (uint256);
/// @notice the defautl split for all operators across all avss
function defaultOperatorSplitBips() external view returns (uint16);
/// @notice the split for a specific `operator` for a specific `avs`
function getOperatorAVSSplit(address operator, address avs) external view returns (uint16);
/// @notice the split for a specific `operator` for Programmatic Incentives
function getOperatorPISplit(address operator) external view returns (uint16);
/// @notice return the hash of the earner's leaf
function calculateEarnerLeafHash(EarnerTreeMerkleLeaf calldata leaf) external pure returns (bytes32);
/// @notice returns the hash of the earner's token leaf
function calculateTokenLeafHash(TokenTreeMerkleLeaf calldata leaf) external pure returns (bytes32);
/// @notice returns 'true' if the claim would currently pass the check in `processClaims`
/// but will revert if not valid
function checkClaim(RewardsMerkleClaim calldata claim) external view returns (bool);
/// @notice The timestamp until which RewardsSubmissions have been calculated
function currRewardsCalculationEndTimestamp() external view returns (uint32);
/// @notice returns the number of distribution roots posted
function getDistributionRootsLength() external view returns (uint256);
/// @notice returns the distributionRoot at the specified index
function getDistributionRootAtIndex(uint256 index) external view returns (DistributionRoot memory);
/// @notice returns the current distributionRoot
function getCurrentDistributionRoot() external view returns (DistributionRoot memory);
/// @notice loop through the distribution roots from reverse and get latest root that is not disabled and activated
/// i.e. a root that can be claimed against
function getCurrentClaimableDistributionRoot() external view returns (DistributionRoot memory);
/// @notice loop through distribution roots from reverse and return index from hash
function getRootIndexFromHash(bytes32 rootHash) external view returns (uint32);
/**
*
* EXTERNAL FUNCTIONS
*
*/
/**
* @notice Creates a new rewards submission on behalf of an AVS, to be split amongst the
* set of stakers delegated to operators who are registered to the `avs`
* @param rewardsSubmissions The rewards submissions being created
* @dev Expected to be called by the ServiceManager of the AVS on behalf of which the submission is being made
* @dev The duration of the `rewardsSubmission` cannot exceed `MAX_REWARDS_DURATION`
* @dev The tokens are sent to the `RewardsCoordinator` contract
* @dev Strategies must be in ascending order of addresses to check for duplicates
* @dev This function will revert if the `rewardsSubmission` is malformed,
* e.g. if the `strategies` and `weights` arrays are of non-equal lengths
*/
function createAVSRewardsSubmission(RewardsSubmission[] calldata rewardsSubmissions) external;
/**
* @notice similar to `createAVSRewardsSubmission` except the rewards are split amongst *all* stakers
* rather than just those delegated to operators who are registered to a single avs and is
* a permissioned call based on isRewardsForAllSubmitter mapping.
* @param rewardsSubmission The rewards submission being created
*/
function createRewardsForAllSubmission(RewardsSubmission[] calldata rewardsSubmission) external;
/**
* @notice Creates a new rewards submission for all earners across all AVSs.
* Earners in this case indicating all operators and their delegated stakers. Undelegated stake
* is not rewarded from this RewardsSubmission. This interface is only callable
* by the token hopper contract from the Eigen Foundation
* @param rewardsSubmissions The rewards submissions being created
*/
function createRewardsForAllEarners(RewardsSubmission[] calldata rewardsSubmissions) external;
/**
* @notice Creates a new operator-directed rewards submission on behalf of an AVS, to be split amongst the operators and
* set of stakers delegated to operators who are registered to the `avs`.
* @param avs The AVS on behalf of which the reward is being submitted
* @param operatorDirectedRewardsSubmissions The operator-directed rewards submissions being created
* @dev Expected to be called by the ServiceManager of the AVS on behalf of which the submission is being made
* @dev The duration of the `rewardsSubmission` cannot exceed `MAX_REWARDS_DURATION`
* @dev The tokens are sent to the `RewardsCoordinator` contract
* @dev The `RewardsCoordinator` contract needs a token approval of sum of all `operatorRewards` in the `operatorDirectedRewardsSubmissions`, before calling this function.
* @dev Strategies must be in ascending order of addresses to check for duplicates
* @dev Operators must be in ascending order of addresses to check for duplicates.
* @dev This function will revert if the `operatorDirectedRewardsSubmissions` is malformed.
*/
function createOperatorDirectedAVSRewardsSubmission(
address avs,
OperatorDirectedRewardsSubmission[] calldata operatorDirectedRewardsSubmissions
) external;
/**
* @notice Claim rewards against a given root (read from _distributionRoots[claim.rootIndex]).
* Earnings are cumulative so earners don't have to claim against all distribution roots they have earnings for,
* they can simply claim against the latest root and the contract will calculate the difference between
* their cumulativeEarnings and cumulativeClaimed. This difference is then transferred to recipient address.
* @param claim The RewardsMerkleClaim to be processed.
* Contains the root index, earner, token leaves, and required proofs
* @param recipient The address recipient that receives the ERC20 rewards
* @dev only callable by the valid claimer, that is
* if claimerFor[claim.earner] is address(0) then only the earner can claim, otherwise only
* claimerFor[claim.earner] can claim the rewards.
*/
function processClaim(RewardsMerkleClaim calldata claim, address recipient) external;
/**
* @notice Batch claim rewards against a given root (read from _distributionRoots[claim.rootIndex]).
* Earnings are cumulative so earners don't have to claim against all distribution roots they have earnings for,
* they can simply claim against the latest root and the contract will calculate the difference between
* their cumulativeEarnings and cumulativeClaimed. This difference is then transferred to recipient address.
* @param claims The RewardsMerkleClaims to be processed.
* Contains the root index, earner, token leaves, and required proofs
* @param recipient The address recipient that receives the ERC20 rewards
* @dev only callable by the valid claimer, that is
* if claimerFor[claim.earner] is address(0) then only the earner can claim, otherwise only
* claimerFor[claim.earner] can claim the rewards.
* @dev This function may fail to execute with a large number of claims due to gas limits. Use a smaller array of claims if necessary.
*/
function processClaims(RewardsMerkleClaim[] calldata claims, address recipient) external;
/**
* @notice Creates a new distribution root. activatedAt is set to block.timestamp + activationDelay
* @param root The merkle root of the distribution
* @param rewardsCalculationEndTimestamp The timestamp until which rewards have been calculated
* @dev Only callable by the rewardsUpdater
*/
function submitRoot(bytes32 root, uint32 rewardsCalculationEndTimestamp) external;
/**
* @notice allow the rewardsUpdater to disable/cancel a pending root submission in case of an error
* @param rootIndex The index of the root to be disabled
*/
function disableRoot(uint32 rootIndex) external;
/**
* @notice Sets the address of the entity that can call `processClaim` on behalf of the earner (msg.sender)
* @param claimer The address of the entity that can call `processClaim` on behalf of the earner
* @dev Only callable by the `earner`
*/
function setClaimerFor(address claimer) external;
/**
* @notice Sets the delay in timestamp before a posted root can be claimed against
* @dev Only callable by the contract owner
* @param _activationDelay The new value for activationDelay
*/
function setActivationDelay(uint32 _activationDelay) external;
/**
* @notice Sets the default split for all operators across all avss.
* @param split The default split for all operators across all avss in bips.
* @dev Only callable by the contract owner.
*/
function setDefaultOperatorSplit(uint16 split) external;
/**
* @notice Sets the split for a specific operator for a specific avs
* @param operator The operator who is setting the split
* @param avs The avs for which the split is being set by the operator
* @param split The split for the operator for the specific avs in bips.
* @dev Only callable by the operator
* @dev Split has to be between 0 and 10000 bips (inclusive)
* @dev The split will be activated after the activation delay
*/
function setOperatorAVSSplit(address operator, address avs, uint16 split) external;
/**
* @notice Sets the split for a specific operator for Programmatic Incentives.
* @param operator The operator on behalf of which the split is being set.
* @param split The split for the operator for Programmatic Incentives in bips.
* @dev Only callable by the operator
* @dev Split has to be between 0 and 10000 bips (inclusive)
* @dev The split will be activated after the activation delay
*/
function setOperatorPISplit(address operator, uint16 split) external;
/**
* @notice Sets the permissioned `rewardsUpdater` address which can post new roots
* @dev Only callable by the contract owner
* @param _rewardsUpdater The address of the new rewardsUpdater
*/
function setRewardsUpdater(address _rewardsUpdater) external;
/**
* @notice Sets the permissioned `rewardsForAllSubmitter` address which can submit createRewardsForAllSubmission
* @dev Only callable by the contract owner
* @param _submitter The address of the rewardsForAllSubmitter
* @param _newValue The new value for isRewardsForAllSubmitter
*/
function setRewardsForAllSubmitter(address _submitter, bool _newValue) external;
/**
* @notice Getter function for the current EIP-712 domain separator for this contract.
*
* @dev The domain separator will change in the event of a fork that changes the ChainID.
* @dev By introducing a domain separator the DApp developers are guaranteed that there can be no signature collision.
* for more detailed information please read EIP-712.
*/
function domainSeparator() external view returns (bytes32);
}
lib/contracts/lib/eigenlayer-contracts/src/contracts/interfaces/ISignatureUtils.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.5.0;
/**
* @title The interface for common signature utilities.
* @author Layr Labs, Inc.
* @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service
*/
interface ISignatureUtils {
// @notice Struct that bundles together a signature and an expiration time for the signature. Used primarily for stack management.
struct SignatureWithExpiry {
// the signature itself, formatted as a single bytes object
bytes signature;
// the expiration timestamp (UTC) of the signature
uint256 expiry;
}
// @notice Struct that bundles together a signature, a salt for uniqueness, and an expiration time for the signature. Used primarily for stack management.
struct SignatureWithSaltAndExpiry {
// the signature itself, formatted as a single bytes object
bytes signature;
// the salt used to generate the signature
bytes32 salt;
// the expiration timestamp (UTC) of the signature
uint256 expiry;
}
}
lib/contracts/lib/eigenlayer-contracts/src/contracts/interfaces/IStrategy.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Minimal interface for an `Strategy` contract.
* @author Layr Labs, Inc.
* @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service
* @notice Custom `Strategy` implementations may expand extensively on this interface.
*/
interface IStrategy {
/**
* @notice Used to emit an event for the exchange rate between 1 share and underlying token in a strategy contract
* @param rate is the exchange rate in wad 18 decimals
* @dev Tokens that do not have 18 decimals must have offchain services scale the exchange rate by the proper magnitude
*/
event ExchangeRateEmitted(uint256 rate);
/**
* Used to emit the underlying token and its decimals on strategy creation
* @notice token
* @param token is the ERC20 token of the strategy
* @param decimals are the decimals of the ERC20 token in the strategy
*/
event StrategyTokenSet(IERC20 token, uint8 decimals);
/**
* @notice Used to deposit tokens into this Strategy
* @param token is the ERC20 token being deposited
* @param amount is the amount of token being deposited
* @dev This function is only callable by the strategyManager contract. It is invoked inside of the strategyManager's
* `depositIntoStrategy` function, and individual share balances are recorded in the strategyManager as well.
* @return newShares is the number of new shares issued at the current exchange ratio.
*/
function deposit(IERC20 token, uint256 amount) external returns (uint256);
/**
* @notice Used to withdraw tokens from this Strategy, to the `recipient`'s address
* @param recipient is the address to receive the withdrawn funds
* @param token is the ERC20 token being transferred out
* @param amountShares is the amount of shares being withdrawn
* @dev This function is only callable by the strategyManager contract. It is invoked inside of the strategyManager's
* other functions, and individual share balances are recorded in the strategyManager as well.
*/
function withdraw(address recipient, IERC20 token, uint256 amountShares) external;
/**
* @notice Used to convert a number of shares to the equivalent amount of underlying tokens for this strategy.
* @notice In contrast to `sharesToUnderlyingView`, this function **may** make state modifications
* @param amountShares is the amount of shares to calculate its conversion into the underlying token
* @return The amount of underlying tokens corresponding to the input `amountShares`
* @dev Implementation for these functions in particular may vary significantly for different strategies
*/
function sharesToUnderlying(uint256 amountShares) external returns (uint256);
/**
* @notice Used to convert an amount of underlying tokens to the equivalent amount of shares in this strategy.
* @notice In contrast to `underlyingToSharesView`, this function **may** make state modifications
* @param amountUnderlying is the amount of `underlyingToken` to calculate its conversion into strategy shares
* @return The amount of underlying tokens corresponding to the input `amountShares`
* @dev Implementation for these functions in particular may vary significantly for different strategies
*/
function underlyingToShares(uint256 amountUnderlying) external returns (uint256);
/**
* @notice convenience function for fetching the current underlying value of all of the `user`'s shares in
* this strategy. In contrast to `userUnderlyingView`, this function **may** make state modifications
*/
function userUnderlying(address user) external returns (uint256);
/**
* @notice convenience function for fetching the current total shares of `user` in this strategy, by
* querying the `strategyManager` contract
*/
function shares(address user) external view returns (uint256);
/**
* @notice Used to convert a number of shares to the equivalent amount of underlying tokens for this strategy.
* @notice In contrast to `sharesToUnderlying`, this function guarantees no state modifications
* @param amountShares is the amount of shares to calculate its conversion into the underlying token
* @return The amount of shares corresponding to the input `amountUnderlying`
* @dev Implementation for these functions in particular may vary significantly for different strategies
*/
function sharesToUnderlyingView(uint256 amountShares) external view returns (uint256);
/**
* @notice Used to convert an amount of underlying tokens to the equivalent amount of shares in this strategy.
* @notice In contrast to `underlyingToShares`, this function guarantees no state modifications
* @param amountUnderlying is the amount of `underlyingToken` to calculate its conversion into strategy shares
* @return The amount of shares corresponding to the input `amountUnderlying`
* @dev Implementation for these functions in particular may vary significantly for different strategies
*/
function underlyingToSharesView(uint256 amountUnderlying) external view returns (uint256);
/**
* @notice convenience function for fetching the current underlying value of all of the `user`'s shares in
* this strategy. In contrast to `userUnderlying`, this function guarantees no state modifications
*/
function userUnderlyingView(address user) external view returns (uint256);
/// @notice The underlying token for shares in this Strategy
function underlyingToken() external view returns (IERC20);
/// @notice The total number of extant shares in this Strategy
function totalShares() external view returns (uint256);
/// @notice Returns either a brief string explaining the strategy's goal & purpose, or a link to metadata that explains in more detail.
function explanation() external view returns (string memory);
}
lib/contracts/src/NetworkManagement/Common/BLS.sol
// SPDX-License-Identifier: MIT
/* MIT License
Copyright (c) 2021 Hubble-Project (natspec added by Polygon Technology)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
pragma solidity >=0.8.19;
import {ModexpInverse, ModexpSqrt} from "./ModExp.sol";
/**
@title Boneh–Lynn–Shacham (BLS) signature scheme on Barreto-Naehrig 254 bit curve (BN-254)
@notice BLS signature aggregation reduces the size of signature data to store on-chain
@dev points on G1 are used for signatures and messages, and on G2 for public keys
@dev Adapted to be an internal library instead of an abstract contract
*/
library BLS {
error InvalidPublicKeyCount();
error InvalidPublicKeyMessageCount();
error BNAddCallFailed();
error InvalidFieldElement();
error BadFTMappingImplementation();
// Field order
// prettier-ignore
uint256 private constant N = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
// Negated generator of G2
// prettier-ignore
uint256 private constant N_G2_X1 = 11559732032986387107991004021392285783925812861821192530917403151452391805634;
// prettier-ignore
uint256 private constant N_G2_X0 = 10857046999023057135944570762232829481370756359578518086990519993285655852781;
// prettier-ignore
uint256 private constant N_G2_Y1 = 17805874995975841540914202342111839520379459829704422454583296818431106115052;
// prettier-ignore
uint256 private constant N_G2_Y0 = 13392588948715843804641432497768002650278120570034223513918757245338268106653;
// sqrt(-3)
// prettier-ignore
uint256 private constant Z0 = 0x0000000000000000b3c4d79d41a91759a9e4c7e359b6b89eaec68e62effffffd;
// (sqrt(-3) - 1) / 2
// prettier-ignore
uint256 private constant Z1 = 0x000000000000000059e26bcea0d48bacd4f263f1acdb5c4f5763473177fffffe;
// prettier-ignore
uint256 private constant T24 = 0x1000000000000000000000000000000000000000000000000;
// prettier-ignore
uint256 private constant MASK24 = 0xffffffffffffffffffffffffffffffffffffffffffffffff;
function verifySingle(
uint256[2] memory signature,
uint256[4] memory pubkey,
uint256[2] memory message
) internal view returns (bool, bool) {
uint256[12] memory input = [
signature[0],
signature[1],
N_G2_X1,
N_G2_X0,
N_G2_Y1,
N_G2_Y0,
message[0],
message[1],
pubkey[1],
pubkey[0],
pubkey[3],
pubkey[2]
];
uint256[1] memory out;
bool callSuccess;
// solhint-disable-next-line no-inline-assembly
assembly {
callSuccess := staticcall(gas(), 8, input, 384, out, 0x20)
}
if (!callSuccess) {
return (false, false);
}
return (out[0] != 0, true);
}
function verifyMultiple(
uint256[2] calldata signature,
uint256[4][] calldata pubkeys,
uint256[2][] calldata messages
) internal view returns (bool checkResult, bool callSuccess) {
uint256 size = pubkeys.length;
if (size == 0) revert InvalidPublicKeyCount();
if (size != messages.length) revert InvalidPublicKeyMessageCount();
uint256 inputSize = (size + 1) * 6;
uint256[] memory input = new uint256[](inputSize);
input[0] = signature[0];
input[1] = signature[1];
input[2] = N_G2_X1;
input[3] = N_G2_X0;
input[4] = N_G2_Y1;
input[5] = N_G2_Y0;
for (uint256 i = 0; i < size; i++) {
input[i * 6 + 6] = messages[i][0];
input[i * 6 + 7] = messages[i][1];
input[i * 6 + 8] = pubkeys[i][1];
input[i * 6 + 9] = pubkeys[i][0];
input[i * 6 + 10] = pubkeys[i][3];
input[i * 6 + 11] = pubkeys[i][2];
}
uint256[1] memory out;
// solhint-disable-next-line no-inline-assembly
assembly {
callSuccess := staticcall(gas(), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)
}
if (!callSuccess) {
return (false, false);
}
return (out[0] != 0, true);
}
function verifyMultipleSameMsg(
uint256[2] calldata signature,
uint256[4][] calldata pubkeys,
uint256[2] calldata message
) internal view returns (bool checkResult, bool callSuccess) {
uint256 size = pubkeys.length;
if (size == 0) revert InvalidPublicKeyCount();
uint256 inputSize = (size + 1) * 6;
uint256[] memory input = new uint256[](inputSize);
input[0] = signature[0];
input[1] = signature[1];
input[2] = N_G2_X1;
input[3] = N_G2_X0;
input[4] = N_G2_Y1;
input[5] = N_G2_Y0;
for (uint256 i = 0; i < size; i++) {
input[i * 6 + 6] = message[0];
input[i * 6 + 7] = message[1];
input[i * 6 + 8] = pubkeys[i][1];
input[i * 6 + 9] = pubkeys[i][0];
input[i * 6 + 10] = pubkeys[i][3];
input[i * 6 + 11] = pubkeys[i][2];
}
uint256[1] memory out;
// solhint-disable-next-line no-inline-assembly
assembly {
callSuccess := staticcall(gas(), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)
}
if (!callSuccess) {
return (false, false);
}
return (out[0] != 0, true);
}
function hashToPoint(bytes32 domain, bytes memory message) internal view returns (uint256[2] memory) {
uint256[2] memory u = hashToField(domain, message);
uint256[2] memory p0 = mapToPoint(u[0]);
uint256[2] memory p1 = mapToPoint(u[1]);
uint256[4] memory bnAddInput;
bnAddInput[0] = p0[0];
bnAddInput[1] = p0[1];
bnAddInput[2] = p1[0];
bnAddInput[3] = p1[1];
bool success;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(sub(gas(), 2000), 6, bnAddInput, 128, p0, 64)
switch success
case 0 {
invalid()
}
}
if (!success) revert BNAddCallFailed();
return p0;
}
function mapToPoint(uint256 _x) internal pure returns (uint256[2] memory p) {
if (_x >= N) revert InvalidFieldElement();
uint256 x = _x;
(, bool decision) = sqrt(x);
uint256 a0 = mulmod(x, x, N);
a0 = addmod(a0, 4, N);
uint256 a1 = mulmod(x, Z0, N);
uint256 a2 = mulmod(a1, a0, N);
a2 = inverse(a2);
a1 = mulmod(a1, a1, N);
a1 = mulmod(a1, a2, N);
// x1
a1 = mulmod(x, a1, N);
x = addmod(Z1, N - a1, N);
// check curve
a1 = mulmod(x, x, N);
a1 = mulmod(a1, x, N);
a1 = addmod(a1, 3, N);
bool found;
(a1, found) = sqrt(a1);
if (found) {
if (!decision) {
a1 = N - a1;
}
return [x, a1];
}
// x2
x = N - addmod(x, 1, N);
// check curve
a1 = mulmod(x, x, N);
a1 = mulmod(a1, x, N);
a1 = addmod(a1, 3, N);
(a1, found) = sqrt(a1);
if (found) {
if (!decision) {
a1 = N - a1;
}
return [x, a1];
}
// x3
x = mulmod(a0, a0, N);
x = mulmod(x, x, N);
x = mulmod(x, a2, N);
x = mulmod(x, a2, N);
x = addmod(x, 1, N);
// must be on curve
a1 = mulmod(x, x, N);
a1 = mulmod(a1, x, N);
a1 = addmod(a1, 3, N);
(a1, found) = sqrt(a1);
// solhint-disable-next-line reason-string
if (!found) revert BadFTMappingImplementation();
if (!decision) {
a1 = N - a1;
}
return [x, a1];
}
function isValidSignature(uint256[2] memory signature) internal pure returns (bool) {
if ((signature[0] >= N) || (signature[1] >= N)) {
return false;
} else {
return isOnCurveG1(signature);
}
}
function isOnCurveG1(uint256[2] memory point) internal pure returns (bool _isOnCurve) {
// solhint-disable-next-line no-inline-assembly
assembly {
let t0 := mload(point)
let t1 := mload(add(point, 32))
let t2 := mulmod(t0, t0, N)
t2 := mulmod(t2, t0, N)
t2 := addmod(t2, 3, N)
t1 := mulmod(t1, t1, N)
_isOnCurve := eq(t1, t2)
}
}
function isOnCurveG2(uint256[4] memory point) internal pure returns (bool _isOnCurve) {
// solhint-disable-next-line no-inline-assembly
assembly {
// x0, x1
let t0 := mload(point)
let t1 := mload(add(point, 32))
// x0 ^ 2
let t2 := mulmod(t0, t0, N)
// x1 ^ 2
let t3 := mulmod(t1, t1, N)
// 3 * x0 ^ 2
let t4 := add(add(t2, t2), t2)
// 3 * x1 ^ 2
let t5 := addmod(add(t3, t3), t3, N)
// x0 * (x0 ^ 2 - 3 * x1 ^ 2)
t2 := mulmod(add(t2, sub(N, t5)), t0, N)
// x1 * (3 * x0 ^ 2 - x1 ^ 2)
t3 := mulmod(add(t4, sub(N, t3)), t1, N)
// x ^ 3 + b
t0 := addmod(t2, 0x2b149d40ceb8aaae81be18991be06ac3b5b4c5e559dbefa33267e6dc24a138e5, N)
t1 := addmod(t3, 0x009713b03af0fed4cd2cafadeed8fdf4a74fa084e52d1852e4a2bd0685c315d2, N)
// y0, y1
t2 := mload(add(point, 64))
t3 := mload(add(point, 96))
// y ^ 2
t4 := mulmod(addmod(t2, t3, N), addmod(t2, sub(N, t3), N), N)
t3 := mulmod(shl(1, t2), t3, N)
// y ^ 2 == x ^ 3 + b
_isOnCurve := and(eq(t0, t4), eq(t1, t3))
}
}
/**
* @notice returns square root of a uint256 value
* @param xx the value to take the square root of
* @return x the uint256 value of the root
* @return hasRoot a bool indicating if there is a square root
*/
function sqrt(uint256 xx) internal pure returns (uint256 x, bool hasRoot) {
x = ModexpSqrt.run(xx);
hasRoot = mulmod(x, x, N) == xx;
}
/**
* @notice inverts a uint256 value
* @param a uint256 value to invert
* @return uint256 of the value of the inverse
*/
function inverse(uint256 a) internal pure returns (uint256) {
return ModexpInverse.run(a);
}
function hashToField(bytes32 domain, bytes memory messages) internal pure returns (uint256[2] memory) {
bytes memory _msg = expandMsgTo96(domain, messages);
uint256 u0;
uint256 u1;
uint256 a0;
uint256 a1;
// solhint-disable-next-line no-inline-assembly
assembly {
let p := add(_msg, 24)
u1 := and(mload(p), MASK24)
p := add(_msg, 48)
u0 := and(mload(p), MASK24)
a0 := addmod(mulmod(u1, T24, N), u0, N)
p := add(_msg, 72)
u1 := and(mload(p), MASK24)
p := add(_msg, 96)
u0 := and(mload(p), MASK24)
a1 := addmod(mulmod(u1, T24, N), u0, N)
}
return [a0, a1];
}
function expandMsgTo96(bytes32 domain, bytes memory message) internal pure returns (bytes memory) {
// zero<64>|msg<var>|lib_str<2>|I2OSP(0, 1)<1>|dst<var>|dst_len<1>
uint256 t0 = message.length;
bytes memory msg0 = new bytes(32 + t0 + 64 + 4);
bytes memory out = new bytes(96);
// b0
// solhint-disable-next-line no-inline-assembly
assembly {
let p := add(msg0, 96)
for {
let z := 0
} lt(z, t0) {
z := add(z, 32)
} {
mstore(add(p, z), mload(add(message, add(z, 32))))
}
p := add(p, t0)
mstore8(p, 0)
p := add(p, 1)
mstore8(p, 96)
p := add(p, 1)
mstore8(p, 0)
p := add(p, 1)
mstore(p, domain)
p := add(p, 32)
mstore8(p, 32)
}
bytes32 b0 = sha256(msg0);
bytes32 bi;
t0 = 32 + 34;
// resize intermediate message
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(msg0, t0)
}
// b1
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(add(msg0, 32), b0)
mstore8(add(msg0, 64), 1)
mstore(add(msg0, 65), domain)
mstore8(add(msg0, add(32, 65)), 32)
}
bi = sha256(msg0);
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(add(out, 32), bi)
}
// b2
// solhint-disable-next-line no-inline-assembly
assembly {
let t := xor(b0, bi)
mstore(add(msg0, 32), t)
mstore8(add(msg0, 64), 2)
mstore(add(msg0, 65), domain)
mstore8(add(msg0, add(32, 65)), 32)
}
bi = sha256(msg0);
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(add(out, 64), bi)
}
// b3
// solhint-disable-next-line no-inline-assembly
assembly {
let t := xor(b0, bi)
mstore(add(msg0, 32), t)
mstore8(add(msg0, 64), 3)
mstore(add(msg0, 65), domain)
mstore8(add(msg0, add(32, 65)), 32)
}
bi = sha256(msg0);
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(add(out, 96), bi)
}
return out;
}
}lib/contracts/src/NetworkManagement/Common/BLSAuthLibrary.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.25;
/*______ __ __ __ __
/ \ / | / | / | / |
/$$$$$$ | _$$ |_ $$ |____ ______ _______ _$$ |_ $$/ _______
$$ | $$ |/ $$ | $$ \ / \ / \ / $$ | / | / |
$$ | $$ |$$$$$$/ $$$$$$$ |/$$$$$$ |$$$$$$$ |$$$$$$/ $$ |/$$$$$$$/
$$ | $$ | $$ | __ $$ | $$ |$$ $$ |$$ | $$ | $$ | __ $$ |$$ |
$$ \__$$ | $$ |/ |$$ | $$ |$$$$$$$$/ $$ | $$ | $$ |/ |$$ |$$ \_____
$$ $$/ $$ $$/ $$ | $$ |$$ |$$ | $$ | $$ $$/ $$ |$$ |
$$$$$$/ $$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$$$/ $$/ $$$$$$$/
*/
import { BLS } from "@othentic/NetworkManagement/Common/BLS.sol";
library BLSAuthLibrary {
using BLS for uint256[2];
bytes32 internal constant DOMAIN = keccak256("OthenticBLSAuth");
struct Signature {
uint256[2] signature;
}
/// @dev because of backwards compatibility issues, _signature is memory
/// even though it should be calldata. Once old registration is removed, adjust accordingly
function isValidSignature(
Signature memory _signature,
address _signer,
address _contract,
uint256[4] calldata _blsKey
) internal view returns (bool) {
/// @dev signature verification succeeds if signature and pubkey are empty
if (!_signature.signature.isValidSignature()) return false;
uint256[2] memory _messageHash = _message(_signer, _contract);
(bool _callSuccess, bool _result) = _signature.signature.verifySingle(_blsKey, _messageHash);
return _callSuccess && _result;
}
/// @dev uses abi.encode twice because of the way the bls signatures are implemented in the CLI
/// if we want to reduce more gas we should look into how polygon implemented it
function _message(address _signer, address _contract) internal view returns (uint256[2] memory) {
// slither-disable-next-line calls-loop
bytes32 _hash = keccak256(abi.encode(_signer, _contract, block.chainid));
return BLS.hashToPoint(DOMAIN, abi.encode(_hash));
}
}lib/contracts/src/NetworkManagement/Common/MessagesLibrary.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.25;
/*______ __ __ __ __
/ \ / | / | / | / |
/$$$$$$ | _$$ |_ $$ |____ ______ _______ _$$ |_ $$/ _______
$$ | $$ |/ $$ | $$ \ / \ / \ / $$ | / | / |
$$ | $$ |$$$$$$/ $$$$$$$ |/$$$$$$ |$$$$$$$ |$$$$$$/ $$ |/$$$$$$$/
$$ | $$ | $$ | __ $$ | $$ |$$ $$ |$$ | $$ | $$ | __ $$ |$$ |
$$ \__$$ | $$ |/ |$$ | $$ |$$$$$$$$/ $$ | $$ | $$ |/ |$$ |$$ \_____
$$ $$/ $$ $$/ $$ | $$ |$$ |$$ | $$ | $$ $$/ $$ |$$ |
$$$$$$/ $$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$$$/ $$/ $$$$$$$/
*/
library MessagesLibrary {
bytes4 internal constant BATCH_CLEAR_SIG = bytes4(keccak256("BATCH_CLEAR"));
bytes4 internal constant BATCH_PAYMENT_SIG = bytes4(keccak256("BATCH_PAYMENT"));
bytes4 internal constant EIGEN_REWARDS_SIG = bytes4(keccak256("EIGEN_REWARDS"));
bytes4 internal constant REGISTER_SIG = bytes4(keccak256("REGISTER"));
bytes4 internal constant UNREGISTER_SIG = bytes4(keccak256("UNREGISTER"));
//////////////////////////////////////////////////////////////////
// Message Builders
//////////////////////////////////////////////////////////////////
//
// Tasks Manager to Network Manager messages
//
/////////////////////////////////////////////////////////////////
function BuildBatchPaymentRequestMessage(bytes memory _operators, uint256 _taskNumber) internal pure returns (bytes memory) {
return abi.encodeWithSelector(MessagesLibrary.BATCH_PAYMENT_SIG, _operators, _taskNumber);
}
function BuildEigenRewardsRequestMessage(bytes memory _operators, uint256 _taskNumber, bytes memory _rewardsData) internal pure returns (bytes memory) {
return abi.encodeWithSelector(MessagesLibrary.EIGEN_REWARDS_SIG, _operators, _taskNumber, _rewardsData);
}
//////////////////////////////////////////////////////////////////
//
// AvsGovernance to AttestationCenter messages
//
/////////////////////////////////////////////////////////////////
function BuildRegisterOperatorMessage(address _operator, uint256 _votingPower, uint[4] calldata _blsKey, address _rewardsReceiver) internal pure returns (bytes memory) {
return abi.encodeWithSelector(MessagesLibrary.REGISTER_SIG, _operator, _votingPower, _blsKey, _rewardsReceiver);
}
function BuildUnregisterRequestMessage(address _operator) internal pure returns (bytes memory) {
return abi.encodeWithSelector(MessagesLibrary.UNREGISTER_SIG, _operator);
}
function BuildBatchClearRequestMessage(bytes memory _operators, uint256 _lastPaidTaskNumber) internal pure returns (bytes memory) {
return abi.encodeWithSelector(MessagesLibrary.BATCH_CLEAR_SIG, _operators, _lastPaidTaskNumber);
}
//////////////////////////////////////////////////////////////////
//
// L1MessageHandler
//
/////////////////////////////////////////////////////////////////
function ParseBatchPaymentRequestMessage(bytes memory _message) internal pure returns (bytes memory _operators, uint256 _lastPayedTask) {
return abi.decode(_message, (bytes, uint256));
}
function ParseEigenRewardsRequestMessage(bytes memory _message) internal pure returns (bytes memory _operators, uint256 _lastPayedTask, bytes memory _data) {
return abi.decode(_message, (bytes, uint256, bytes));
}
//////////////////////////////////////////////////////////////////
//
// L2MessageHandler
//
/////////////////////////////////////////////////////////////////
function ParseRegisterToAvsMessage(bytes memory _message) internal pure returns (address _operator, uint256 _votingPower, uint256[4] memory _blsKey, address _rewardsReceiver) {
return abi.decode(_message, (address, uint256, uint256[4], address));
}
function ParseBatchClearMessage(bytes memory _message) internal pure returns (bytes memory _operators, uint256 _lastPaidTaskNumber) {
return abi.decode(_message, (bytes, uint256));
}
function ParseUnregisterOperatorMessage(bytes memory _message) internal pure returns (address operator) {
return abi.decode(_message, (address));
}
function PayloadToSig(bytes calldata _payload) internal pure returns (bytes4 _sig, bytes memory _body) {
_sig = bytes4(_payload[0:4]);
_body = _payload[4:];
}
}lib/contracts/src/NetworkManagement/Common/ModExp.sol
// SPDX-License-Identifier: MIT
/* MIT License
Copyright (c) 2021 Hubble-Project
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
pragma solidity >=0.8.19;
/**
@title Compute Inverse by Modular Exponentiation
@notice Compute $input^(N - 2) mod N$ using Addition Chain method.
Where N = 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47
and N - 2 = 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd45
@dev the function body is generated with the modified addchain script
see https://github.com/kobigurk/addchain/commit/2c37a2ace567a9bdc680b4e929c94aaaa3ec700f
*/
library ModexpInverse {
/**
* @notice computes inverse
* @dev computes $input^(N - 2) mod N$ using Addition Chain method.
* @param t2 the number to get the inverse of (uint256)
* @return t0 the inverse (uint256)
*/
function run(uint256 t2) internal pure returns (uint256 t0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let n := 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47
t0 := mulmod(t2, t2, n)
let t5 := mulmod(t0, t2, n)
let t1 := mulmod(t5, t0, n)
let t3 := mulmod(t5, t5, n)
let t8 := mulmod(t1, t0, n)
let t4 := mulmod(t3, t5, n)
let t6 := mulmod(t3, t1, n)
t0 := mulmod(t3, t3, n)
let t7 := mulmod(t8, t3, n)
t3 := mulmod(t4, t3, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t5, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t2, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t2, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t8, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t8, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t2, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t8, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t2, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t5, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t7, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t1, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t5, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t8, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t1, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t2, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t6, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t7, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t1, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t5, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t1, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t5, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t6, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t6, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t1, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t8, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t6, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t1, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t4, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t6, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t2, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t8, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t8, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t1, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t2, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t7, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t3, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t2, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t2, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t5, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t6, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t5, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t5, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t3, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t4, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t3, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t1, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t2, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t1, n)
}
}
}
/**
@title Compute Square Root by Modular Exponentiation
@notice Compute $input^{(N + 1) / 4} mod N$ using Addition Chain method.
Where N = 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47
and (N + 1) / 4 = 0xc19139cb84c680a6e14116da060561765e05aa45a1c72a34f082305b61f3f52
*/
library ModexpSqrt {
/**
* @notice computes square root by modular exponentation
* @dev Compute $input^{(N + 1) / 4} mod N$ using Addition Chain method
* @param t6 the number to derive the square root of
* @return t0 the square root
*/
function run(uint256 t6) internal pure returns (uint256 t0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let n := 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47
t0 := mulmod(t6, t6, n)
let t4 := mulmod(t0, t6, n)
let t2 := mulmod(t4, t0, n)
let t3 := mulmod(t4, t4, n)
let t8 := mulmod(t2, t0, n)
let t1 := mulmod(t3, t4, n)
let t5 := mulmod(t3, t2, n)
t0 := mulmod(t3, t3, n)
let t7 := mulmod(t8, t3, n)
t3 := mulmod(t1, t3, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t4, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t6, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t6, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t8, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t8, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t6, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t8, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t6, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t4, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t7, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t2, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t4, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t8, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t2, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t6, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t5, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t7, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t2, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t4, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t2, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t4, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t5, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t5, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t2, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t8, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t5, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t2, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t1, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t5, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t6, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t8, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t8, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t2, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t6, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t7, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t3, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t6, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t6, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t4, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t5, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t4, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t4, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t3, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t1, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t3, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t2, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t0, n)
t0 := mulmod(t0, t1, n)
t0 := mulmod(t0, t0, n)
}
}
}lib/contracts/src/NetworkManagement/Common/PausableFlows.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.25;
/*______ __ __ __ __
/ \ / | / | / | / |
/$$$$$$ | _$$ |_ $$ |____ ______ _______ _$$ |_ $$/ _______
$$ | $$ |/ $$ | $$ \ / \ / \ / $$ | / | / |
$$ | $$ |$$$$$$/ $$$$$$$ |/$$$$$$ |$$$$$$$ |$$$$$$/ $$ |/$$$$$$$/
$$ | $$ | $$ | __ $$ | $$ |$$ $$ |$$ | $$ | $$ | __ $$ |$$ |
$$ \__$$ | $$ |/ |$$ | $$ |$$$$$$$$/ $$ | $$ | $$ |/ |$$ |$$ \_____
$$ $$/ $$ $$/ $$ | $$ |$$ |$$ | $$ | $$ $$/ $$ |$$ |
$$$$$$/ $$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$$$/ $$/ $$$$$$$/
*/
/**
* @author Othentic Labs LTD.
*/
import "openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol";
import "@othentic/NetworkManagement/Common/PauserRolesLibrary.sol";
import "@othentic/NetworkManagement/Common/RolesLibrary.sol";
import "@othentic/NetworkManagement/Common/interfaces/IPausableFlows.sol";
import "@othentic/NetworkManagement/Common/PausableFlowsStorage.sol";
abstract contract PausableFlows is IPausableFlows, AccessControlUpgradeable {
// MODIFIERS
modifier whenFlowNotPaused(bytes4 _pausableFlow) {
_revertIfFlowPaused(_pausableFlow);
_;
}
modifier whenFlowPaused(bytes4 _pausableFlow) {
_revertIfFlowUnpaused(_pausableFlow);
_;
}
function __OthenticAccessControl_init(address _avsGovernanceMultisigOwner, address _operationsMultisig, address _communityMultisig) internal onlyInitializing {
_grantRole(RolesLibrary.OPERATIONS_MULTISIG, _operationsMultisig);
_grantRole(RolesLibrary.AVS_GOVERNANCE_MULTISIG, _avsGovernanceMultisigOwner);
_grantRole(RolesLibrary.COMMUNITY_MULTISIG, _communityMultisig);
}
// EXTERNAL FUNCTIONS
function isFlowPaused(bytes4 _pausableFlow) external view returns (bool _isPaused) {
return _getPausableFlowsStorage().flowsPauseStates[_pausableFlow];
}
function pause(bytes4 _pausableFlow) external whenFlowNotPaused(_pausableFlow) onlyRole(_pausableFlow){
_pause(_pausableFlow);
}
function unpause(bytes4 _pausableFlow) external whenFlowPaused(_pausableFlow) onlyRole(_pausableFlow) {
_unpause(_pausableFlow);
}
// INTERNAL FUNCTIONS
function _pause(bytes4 _pausableFlow) internal {
PausableFlowsStorageData storage _sd = _getPausableFlowsStorage();
if (_sd.flowsPauseStates[_pausableFlow]) revert PauseFlowIsAlreadyPaused();
_sd.flowsPauseStates[_pausableFlow] = true;
emit FlowPaused(_pausableFlow, msg.sender);
}
function _unpause(bytes4 _pausableFlow) internal {
PausableFlowsStorageData storage _sd = _getPausableFlowsStorage();
if (!_sd.flowsPauseStates[_pausableFlow]) revert UnpausingFlowIsAlreadyUnpaused();
_sd.flowsPauseStates[_pausableFlow] = false;
emit FlowUnpaused(_pausableFlow, msg.sender);
}
function _revertIfFlowPaused(bytes4 _pausableFlow) internal view {
if (_getPausableFlowsStorage().flowsPauseStates[_pausableFlow]) revert FlowIsCurrentlyPaused();
}
function _revertIfFlowUnpaused(bytes4 _pausableFlow) internal view {
if (!_getPausableFlowsStorage().flowsPauseStates[_pausableFlow]) revert FlowIsCurrentlyUnpaused();
}
function _getPausableFlowsStorage() internal pure returns (PausableFlowsStorageData storage _sd) {
return PausableFlowsStorage.load();
}
}
lib/contracts/src/NetworkManagement/Common/PausableFlowsStorage.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.25;
/*______ __ __ __ __
/ \ / | / | / | / |
/$$$$$$ | _$$ |_ $$ |____ ______ _______ _$$ |_ $$/ _______
$$ | $$ |/ $$ | $$ \ / \ / \ / $$ | / | / |
$$ | $$ |$$$$$$/ $$$$$$$ |/$$$$$$ |$$$$$$$ |$$$$$$/ $$ |/$$$$$$$/
$$ | $$ | $$ | __ $$ | $$ |$$ $$ |$$ | $$ | $$ | __ $$ |$$ |
$$ \__$$ | $$ |/ |$$ | $$ |$$$$$$$$/ $$ | $$ | $$ |/ |$$ |$$ \_____
$$ $$/ $$ $$/ $$ | $$ |$$ |$$ | $$ | $$ $$/ $$ |$$ |
$$$$$$/ $$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$$$/ $$/ $$$$$$$/
*/
/// @custom:storage-location erc7201:othentic.storage.PauseableFlowControl
struct PausableFlowsStorageData {
mapping(bytes4 _pausableFlow => bool isPaused) flowsPauseStates;
}
library PausableFlowsStorage {
// keccak256(abi.encode(uint256(keccak256("othentic.storage.PauseableFlowControl")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant STORAGE_LOCATION = 0xfe6065fb4e9872e2ad4479001655335380d83f70e163706cd65857449b845100;
function load() internal pure returns (PausableFlowsStorageData storage sd) {
bytes32 position = STORAGE_LOCATION;
assembly {
sd.slot := position
}
}
}lib/contracts/src/NetworkManagement/Common/PauserRolesLibrary.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.25;
/*______ __ __ __ __
/ \ / | / | / | / |
/$$$$$$ | _$$ |_ $$ |____ ______ _______ _$$ |_ $$/ _______
$$ | $$ |/ $$ | $$ \ / \ / \ / $$ | / | / |
$$ | $$ |$$$$$$/ $$$$$$$ |/$$$$$$ |$$$$$$$ |$$$$$$/ $$ |/$$$$$$$/
$$ | $$ | $$ | __ $$ | $$ |$$ $$ |$$ | $$ | $$ | __ $$ |$$ |
$$ \__$$ | $$ |/ |$$ | $$ |$$$$$$$$/ $$ | $$ | $$ |/ |$$ |$$ \_____
$$ $$/ $$ $$/ $$ | $$ |$$ |$$ | $$ | $$ $$/ $$ |$$ |
$$$$$$/ $$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$$$/ $$/ $$$$$$$/
*/
library PauserRolesLibrary {
// PAUSABLE FLOWS-FEATURES
bytes4 internal constant REGISTRATION_FLOW = bytes4(keccak256("REGISTRATION_FLOW"));
bytes4 internal constant BATCH_PAYMENT_REQUEST_FLOW = bytes4(keccak256("BATCH_PAYMENT_REQUEST_FLOW"));
bytes4 internal constant EIGEN_PAYMENT_REQUEST_FLOW = bytes4(keccak256("EIGEN_PAYMENT_REQUEST_FLOW"));
bytes4 internal constant OPERATOR_SET_REWARDS_RECEIVER_FLOW = bytes4(keccak256("AVS_PAUSE_REWARD_MODIFICATION"));
bytes4 internal constant SET_AVS_LOGIC_FLOW = bytes4(keccak256("SET_AVS_LOGIC_FLOW"));
bytes4 internal constant SET_SUPPORTED_STRATEGIES_FLOW = bytes4(keccak256("SET_SUPPORTED_STRATEGIES_FLOW"));
bytes4 internal constant TASKS_SUBMISSION_FLOW = bytes4(keccak256("TASKS_SUBMISSION_FLOW"));
bytes4 internal constant CREATE_NEW_TASK_DEFINITION_FLOW = bytes4(keccak256("CREATE_NEW_TASK_DEFINITION_FLOW"));
}
lib/contracts/src/NetworkManagement/Common/RolesLibrary.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.25;
/*______ __ __ __ __
/ \ / | / | / | / |
/$$$$$$ | _$$ |_ $$ |____ ______ _______ _$$ |_ $$/ _______
$$ | $$ |/ $$ | $$ \ / \ / \ / $$ | / | / |
$$ | $$ |$$$$$$/ $$$$$$$ |/$$$$$$ |$$$$$$$ |$$$$$$/ $$ |/$$$$$$$/
$$ | $$ | $$ | __ $$ | $$ |$$ $$ |$$ | $$ | $$ | __ $$ |$$ |
$$ \__$$ | $$ |/ |$$ | $$ |$$$$$$$$/ $$ | $$ | $$ |/ |$$ |$$ \_____
$$ $$/ $$ $$/ $$ | $$ |$$ |$$ | $$ | $$ $$/ $$ |$$ |
$$$$$$/ $$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$$$/ $$/ $$$$$$$/
*/
library RolesLibrary {
bytes4 internal constant AVS_GOVERNANCE_MULTISIG = bytes4(keccak256("AVS_GOVERNANCE_MULTISIG"));
bytes4 internal constant AVS_GOVERNANCE = bytes4(keccak256("AVS_GOVERNANCE"));
bytes4 internal constant OPERATIONS_MULTISIG = bytes4(keccak256("OPERATIONS_MULTISIG"));
bytes4 internal constant COMMUNITY_MULTISIG = bytes4(keccak256("COMMUNITY_MULTISIG"));
bytes4 internal constant MESSAGE_HANDLER = bytes4(keccak256("MESSAGE_HANDLER"));
bytes4 internal constant ATTESTATION_CENTER = bytes4(keccak256("ATTESTATION_CENTER"));
bytes4 internal constant LZ_RETRY_ROLE = bytes4(keccak256("LZ_RETRY"));
bytes4 internal constant LZ_DELEGATE_ROLE = bytes4(keccak256("LZ_DELEGATE_ROLE"));
bytes4 internal constant AVS_FACTORY_ROLE = bytes4(keccak256("AVS_FACTORY_ROLE"));
bytes4 internal constant MULTIPLIER_SYNCER = bytes4(keccak256("MULTIPLIER_SYNCER"));
bytes4 internal constant VOTING_POWER_SYNCER = bytes4(keccak256("VOTING_POWER_SYNCER"));
bytes4 internal constant OBLS_MANAGER = bytes4(keccak256("OBLS_MANAGER"));
bytes4 internal constant STATE_RECEIVER = bytes4(keccak256("STATE_RECEIVER"));
bytes4 internal constant TOKEN_REPLACEMENT_MODIFICATION_DELAY = bytes4(keccak256("TOKEN_REPLACEMENT_MODIFICATION_DELAY"));
}lib/contracts/src/NetworkManagement/Common/SignedAuthTokenLibrary.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.25;
/*______ __ __ __ __
/ \ / | / | / | / |
/$$$$$$ | _$$ |_ $$ |____ ______ _______ _$$ |_ $$/ _______
$$ | $$ |/ $$ | $$ \ / \ / \ / $$ | / | / |
$$ | $$ |$$$$$$/ $$$$$$$ |/$$$$$$ |$$$$$$$ |$$$$$$/ $$ |/$$$$$$$/
$$ | $$ | $$ | __ $$ | $$ |$$ $$ |$$ | $$ | $$ | __ $$ |$$ |
$$ \__$$ | $$ |/ |$$ | $$ |$$$$$$$$/ $$ | $$ | $$ |/ |$$ |$$ \_____
$$ $$/ $$ $$/ $$ | $$ |$$ |$$ | $$ | $$ $$/ $$ |$$ |
$$$$$$/ $$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$$$/ $$/ $$$$$$$/
*/
import { ECDSA } from "openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol";
import { MessageHashUtils } from "openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol";
library SignedAuthTokenLibrary {
using ECDSA for bytes32;
using MessageHashUtils for bytes32;
function verifyAuthTokenForAddress(bytes memory _authToken, address _avsGovernanceAddress, address _address, address _signer) internal pure returns (bool) {
return getAddress(_avsGovernanceAddress, _address, _authToken) == _signer;
}
function _hash(address _avsGovernanceAddress,address _address) internal pure returns (bytes32) {
return keccak256(abi.encode(_avsGovernanceAddress, _address));
}
function _recover(bytes32 hash, bytes memory token) internal pure returns (address) {
return hash.toEthSignedMessageHash().recover(token);
}
function getAddress(address _avsGovernanceAddress, address _address, bytes memory _authToken) internal pure returns (address) {
return _recover(_hash(_avsGovernanceAddress, _address), _authToken);
}
}
lib/contracts/src/NetworkManagement/Common/interfaces/IAvsTreasury.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.25;
/*______ __ __ __ __
/ \ / | / | / | / |
/$$$$$$ | _$$ |_ $$ |____ ______ _______ _$$ |_ $$/ _______
$$ | $$ |/ $$ | $$ \ / \ / \ / $$ | / | / |
$$ | $$ |$$$$$$/ $$$$$$$ |/$$$$$$ |$$$$$$$ |$$$$$$/ $$ |/$$$$$$$/
$$ | $$ | $$ | __ $$ | $$ |$$ $$ |$$ | $$ | $$ | __ $$ |$$ |
$$ \__$$ | $$ |/ |$$ | $$ |$$$$$$$$/ $$ | $$ | $$ |/ |$$ |$$ \_____
$$ $$/ $$ $$/ $$ | $$ |$$ |$$ | $$ | $$ $$/ $$ |$$ |
$$$$$$/ $$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$$$/ $$/ $$$$$$$/
*/
/**
* @author Othentic Labs LTD.
* @notice Terms of Service: https://www.othentic.xyz/terms-of-service
*/
import {IERC20} from "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
interface IAvsTreasury {
struct InitializationParams {
address avsGovernanceMultisigOwner;
address operationsMultisig;
address communityMultisig;
address token;
address otTreasury;
uint256 protocolFee;
}
struct TokenReplacementDetails {
IERC20 queuedTokenReplacement;
uint48 executionTime;
}
event RewardsDeposited(address avsTreasuryOwner, uint256 amount);
event RewardWithdrawn(address indexed operator, uint256 lastPayedTask, uint256 feeToClaim);
event RewardWithdrawalFailed(address indexed operator, uint256 lastPayedTask, uint256 feeToClaim);
event SetTokenReplacementModificationDelay(uint32 delay);
event TokenReplacementQueued(address queuedTokenReplacement, uint256 modificationTimeTokenReplacement);
event TokenReplaced(address newToken);
event SetAvsGovernanceMultisig(address newAvsGovernanceMultisig);
error NativeETHNotSupported();
error ERC20NotSupported();
error ZeroValueNotAllowed();
error InvalidAmount();
error TransferToOtTreasuryFailed();
error InvalidProtocolFee();
error TransferFailed();
error TokenModificationDelayNotPassed();
error AvsTreasuryBalanceNotZero();
function depositNative() external payable;
// @obsolete
function depositERC20(address _from, uint256 _amount) external;
function depositERC20(uint256 _amount) external;
function depositERC20WithCallback(address _from, uint256 _amount, bytes calldata _data) external;
function withdrawRewards(address _operator, uint256 _lastPayedTask, uint256 _feeToClaim) external returns (bool success);
function setTokenReplacementModificationDelay(uint32 _delay) external;
function queueTokenReplacement(address _newToken) external;
function completeTokenReplacement() external;
function getToken() external view returns (address rewardsToken);
function getTokenReplacementDetails() external view returns (TokenReplacementDetails memory);
function getTokenReplacementModificationDelay() external view returns (uint32);
function ETH_ADDRESS() external view returns (address);
function transferAvsGovernanceMultisig(address _newAvsGovernanceMultisig) external;
}lib/contracts/src/NetworkManagement/Common/interfaces/IBLSAuthSingleton.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.25;
/*______ __ __ __ __
/ \ / | / | / | / |
/$$$$$$ | _$$ |_ $$ |____ ______ _______ _$$ |_ $$/ _______
$$ | $$ |/ $$ | $$ \ / \ / \ / $$ | / | / |
$$ | $$ |$$$$$$/ $$$$$$$ |/$$$$$$ |$$$$$$$ |$$$$$$/ $$ |/$$$$$$$/
$$ | $$ | $$ | __ $$ | $$ |$$ $$ |$$ | $$ | $$ | __ $$ |$$ |
$$ \__$$ | $$ |/ |$$ | $$ |$$$$$$$$/ $$ | $$ | $$ |/ |$$ |$$ \_____
$$ $$/ $$ $$/ $$ | $$ |$$ |$$ | $$ | $$ $$/ $$ |$$ |
$$$$$$/ $$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$$$/ $$/ $$$$$$$/
*/
import { BLSAuthLibrary } from "@othentic/NetworkManagement/Common/BLSAuthLibrary.sol";
interface IBLSAuthSingleton {
function isValidSignature(
BLSAuthLibrary.Signature calldata _signature,
address _signer,
address _contract,
uint256[4] calldata _blsKey
) external view returns (bool);
}lib/contracts/src/NetworkManagement/Common/interfaces/IMessageHandler.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.25;
/*______ __ __ __ __
/ \ / | / | / | / |
/$$$$$$ | _$$ |_ $$ |____ ______ _______ _$$ |_ $$/ _______
$$ | $$ |/ $$ | $$ \ / \ / \ / $$ | / | / |
$$ | $$ |$$$$$$/ $$$$$$$ |/$$$$$$ |$$$$$$$ |$$$$$$/ $$ |/$$$$$$$/
$$ | $$ | $$ | __ $$ | $$ |$$ $$ |$$ | $$ | $$ | __ $$ |$$ |
$$ \__$$ | $$ |/ |$$ | $$ |$$$$$$$$/ $$ | $$ | $$ |/ |$$ |$$ \_____
$$ $$/ $$ $$/ $$ | $$ |$$ |$$ | $$ | $$ $$/ $$ |$$ |
$$$$$$/ $$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$$$/ $$/ $$$$$$$/
*/
/**
* @author Othentic Labs LTD.
*/
interface IMessageHandler {
event SetAvsGovernanceMultisig(address newAvsGovernanceMultisig);
function sendMessage(bytes memory _payload) external;
}
lib/contracts/src/NetworkManagement/Common/interfaces/IPausableFlows.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.25;
/*______ __ __ __ __
/ \ / | / | / | / |
/$$$$$$ | _$$ |_ $$ |____ ______ _______ _$$ |_ $$/ _______
$$ | $$ |/ $$ | $$ \ / \ / \ / $$ | / | / |
$$ | $$ |$$$$$$/ $$$$$$$ |/$$$$$$ |$$$$$$$ |$$$$$$/ $$ |/$$$$$$$/
$$ | $$ | $$ | __ $$ | $$ |$$ $$ |$$ | $$ | $$ | __ $$ |$$ |
$$ \__$$ | $$ |/ |$$ | $$ |$$$$$$$$/ $$ | $$ | $$ |/ |$$ |$$ \_____
$$ $$/ $$ $$/ $$ | $$ |$$ |$$ | $$ | $$ $$/ $$ |$$ |
$$$$$$/ $$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$$$/ $$/ $$$$$$$/
*/
/**
* @author Othentic Labs LTD.
*/
interface IPausableFlows {
// EVENTS
event FlowPaused(bytes4 _pausableFlow, address _pauser);
event FlowUnpaused(bytes4 _pausableFlowFlag, address _unpauser);
// ERRORS
error FlowIsCurrentlyPaused();
error FlowIsCurrentlyUnpaused();
error PauseFlowIsAlreadyPaused();
error UnpausingFlowIsAlreadyUnpaused();
// EXTERNAL FUNCTIONS
function pause(bytes4 _pausableFlow) external;
function unpause(bytes4 _pausableFlow) external;
function isFlowPaused(bytes4 _pausableFlow) external view returns (bool);
}
lib/contracts/src/NetworkManagement/L1/AvsGovernancePausable.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.25;
/*______ __ __ __ __
/ \ / | / | / | / |
/$$$$$$ | _$$ |_ $$ |____ ______ _______ _$$ |_ $$/ _______
$$ | $$ |/ $$ | $$ \ / \ / \ / $$ | / | / |
$$ | $$ |$$$$$$/ $$$$$$$ |/$$$$$$ |$$$$$$$ |$$$$$$/ $$ |/$$$$$$$/
$$ | $$ | $$ | __ $$ | $$ |$$ $$ |$$ | $$ | $$ | __ $$ |$$ |
$$ \__$$ | $$ |/ |$$ | $$ |$$$$$$$$/ $$ | $$ | $$ |/ |$$ |$$ \_____
$$ $$/ $$ $$/ $$ | $$ |$$ |$$ | $$ | $$ $$/ $$ |$$ |
$$$$$$/ $$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$$$/ $$/ $$$$$$$/
*/
/**
* @author Othentic Labs LTD.
*/
import "@othentic/NetworkManagement/Common/PauserRolesLibrary.sol";
import "@othentic/NetworkManagement/Common/RolesLibrary.sol";
import "@othentic/NetworkManagement/Common/PausableFlows.sol";
contract AvsGovernancePausable is PausableFlows {
// INITIALIZER
function __AvsGovernancePausable_init(address _avsGovernanceMultisigOwner, address _operationsMultisig, address _communityMultisig) internal onlyInitializing {
__AccessControl_init();
_grantAvsGovernanceRoles(_avsGovernanceMultisigOwner, _operationsMultisig, _communityMultisig);
renounceRole(DEFAULT_ADMIN_ROLE, address(msg.sender));
}
function _grantAvsGovernanceRoles(address _avsGovernanceMultisigOwner, address _operationsMultisig, address _communityMultisig) private {
_grantRole(PauserRolesLibrary.REGISTRATION_FLOW, _avsGovernanceMultisigOwner);
_grantRole(PauserRolesLibrary.REGISTRATION_FLOW, _operationsMultisig);
_grantRole(PauserRolesLibrary.REGISTRATION_FLOW, _communityMultisig);
_grantRole(PauserRolesLibrary.OPERATOR_SET_REWARDS_RECEIVER_FLOW, _avsGovernanceMultisigOwner);
_grantRole(PauserRolesLibrary.OPERATOR_SET_REWARDS_RECEIVER_FLOW, _operationsMultisig);
_grantRole(PauserRolesLibrary.SET_SUPPORTED_STRATEGIES_FLOW, _avsGovernanceMultisigOwner);
_grantRole(PauserRolesLibrary.SET_SUPPORTED_STRATEGIES_FLOW, _operationsMultisig);
_grantRole(PauserRolesLibrary.SET_SUPPORTED_STRATEGIES_FLOW, _communityMultisig);
_grantRole(PauserRolesLibrary.SET_AVS_LOGIC_FLOW, _avsGovernanceMultisigOwner);
_grantRole(PauserRolesLibrary.SET_AVS_LOGIC_FLOW, _communityMultisig);
_grantRole(PauserRolesLibrary.SET_AVS_LOGIC_FLOW, _operationsMultisig);
}
}
lib/contracts/src/NetworkManagement/L1/AvsGovernanceStorage.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.25;
/*______ __ __ __ __
/ \ / | / | / | / |
/$$$$$$ | _$$ |_ $$ |____ ______ _______ _$$ |_ $$/ _______
$$ | $$ |/ $$ | $$ \ / \ / \ / $$ | / | / |
$$ | $$ |$$$$$$/ $$$$$$$ |/$$$$$$ |$$$$$$$ |$$$$$$/ $$ |/$$$$$$$/
$$ | $$ | $$ | __ $$ | $$ |$$ $$ |$$ | $$ | $$ | __ $$ |$$ |
$$ \__$$ | $$ |/ |$$ | $$ |$$$$$$$$/ $$ | $$ | $$ |/ |$$ |$$ \_____
$$ $$/ $$ $$/ $$ | $$ |$$ |$$ | $$ | $$ $$/ $$ |$$ |
$$$$$$/ $$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$$$/ $$/ $$$$$$$/
*/
import { IMessageHandler } from "@othentic/NetworkManagement/Common/interfaces/IMessageHandler.sol";
import { IAvsTreasury } from "@othentic/NetworkManagement/Common/interfaces/IAvsTreasury.sol";
import { IOthenticRegistry } from "@othentic/NetworkManagement/L1/interfaces/IOthenticRegistry.sol";
import { IAvsGovernanceLogic } from "@othentic/NetworkManagement/L1/interfaces/IAvsGovernanceLogic.sol";
import { IAVSDirectory } from "@eigenlayer/contracts/interfaces/IAVSDirectory.sol";
import { IAvsGovernance } from "@othentic/NetworkManagement/L1/interfaces/IAvsGovernance.sol";
import { INetworkRegistry } from "@symbiotic/src/interfaces/INetworkRegistry.sol";
import { INetworkMiddlewareService } from "@symbiotic/src/contracts/service/NetworkMiddlewareService.sol";
struct AvsGovernanceStorageData {
uint24 slashingRate;
uint256 numOfActiveOperators;
IMessageHandler messageHandler;
IOthenticRegistry othenticRegistry; // Stored on constructor, kept for storage layout compatibility
IAvsTreasury avsTreasury;
IAVSDirectory avsDirectoryContract;
bool isAllowlisted;
address allowlistSigner;
mapping(address => uint256) isOperatorRegistered; // We are using uint256 for backwards compatibility
IAvsGovernanceLogic avsGovernanceLogic;
address[] stakingContracts;
string avsName;
uint256 rewardsReceiverModificationDelay;
mapping(address => bool) isRequestPaymentPaused;
mapping(address => address) rewardsReceiver;
mapping(address => IAvsGovernance.RewardsReceiverModificationDetails) rewardsReceiverModificationDetails;
uint256 numOfOperatorsLimit;
uint256 minVotingPower;
uint256 maxEffectiveBalance;
mapping(address => uint256) minStakeAmountPerStakingContract;
mapping(address => uint256) multipliers;
address avsGovernanceMultiplierSyncer;
address blsAuthSingleton;
mapping(address => IAvsGovernance.SharedSecurityProvider) stakingContractToSharedSecurityProvider;
}
library AvsGovernanceStorage {
uint256 constant private STORAGE_POSITION = uint256(keccak256("storage.avs.governance")) - 1;
function load() internal pure returns (AvsGovernanceStorageData storage sd) {
uint256 position = STORAGE_POSITION;
assembly {
sd.slot := position
}
}
}lib/contracts/src/NetworkManagement/L1/interfaces/IAvsGovernance.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.25;
/*______ __ __ __ __
/ \ / | / | / | / |
/$$$$$$ | _$$ |_ $$ |____ ______ _______ _$$ |_ $$/ _______
$$ | $$ |/ $$ | $$ \ / \ / \ / $$ | / | / |
$$ | $$ |$$$$$$/ $$$$$$$ |/$$$$$$ |$$$$$$$ |$$$$$$/ $$ |/$$$$$$$/
$$ | $$ | $$ | __ $$ | $$ |$$ $$ |$$ | $$ | $$ | __ $$ |$$ |
$$ \__$$ | $$ |/ |$$ | $$ |$$$$$$$$/ $$ | $$ | $$ |/ |$$ |$$ \_____
$$ $$/ $$ $$/ $$ | $$ |$$ |$$ | $$ | $$ $$/ $$ |$$ |
$$$$$$/ $$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$$$/ $$/ $$$$$$$/
*/
import { ISignatureUtils } from "@eigenlayer/contracts/interfaces/ISignatureUtils.sol";
import { BLSAuthLibrary } from "@othentic/NetworkManagement/Common/BLSAuthLibrary.sol";
import { IAccessControl } from "openzeppelin-contracts/contracts/access/IAccessControl.sol";
import { IRewardsCoordinator } from "@eigenlayer/contracts/interfaces/IRewardsCoordinator.sol";
/**
* @author Othentic Labs LTD.
* @notice Terms of Service: https://www.othentic.xyz/terms-of-service
*/
interface IAvsGovernance is IAccessControl {
enum SharedSecurityProvider {
EigenLayer,
Symbiotic
}
struct StakingContractInfo {
address stakingContract;
SharedSecurityProvider sharedSecurityProvider;
}
struct VotingPowerMultiplier {
address stakingContract;
uint256 multiplier;
SharedSecurityProvider sharedSecurityProvider;
}
struct StakingContractDetails {
address stakingContract;
uint256 stakeAmount;
SharedSecurityProvider sharedSecurityProvider;
}
struct StakingContractMinStakeInfo {
address stakingContract;
uint256 minStakeAmount;
}
struct Operator {
uint256[4] blsKey;
uint256 stake;
bool isAllowlisted;
bool isActive;
}
struct PaymentRequestMessage {
address operator;
uint256 feeToClaim;
}
struct EigenRewardsSubmissionData {
uint32 startTimestamp;
uint32 duration;
uint256 totalRewards;
uint256 operatorCount;
}
struct RewardsReceiverModificationDetails {
address newRewardsReceiver;
uint256 modificationDelay;
}
struct InitializationParams {
address avsGovernanceMultisigOwner;
address operationsMultisig;
address communityMultisig;
address othenticRegistry;
address messageHandler;
address avsTreasury;
address avsDirectoryContract;
address allowlistSigner;
string avsName;
address blsAuthSingleton;
}
struct OperatorRegistrationParams {
uint256[4] blsKey;
address rewardsReceiver;
BLSAuthLibrary.Signature blsRegistrationSignature;
bytes authToken;
}
struct SharedSecurityProviderSignature {
SharedSecurityProvider provider;
bytes data;
}
struct SymbioticOptInSignature {
uint48 deadline;
bytes data;
}
struct SymbioticOptOutSignature {
uint48 deadline;
bytes data;
}
// Events
event SetToken(address token);
event SetAvsName(string avsName);
event SetIsAllowlisted(bool isAllowlisted);
event setNewSupportedStakingContracts(address[] stakingContracts);
event QueuedRewardsReceiverModification(address indexed operator, address receiver, uint256 delay);
event SetRewardsReceiver(address indexed operator, address receiver);
event OperatorRegistered(address indexed operator, uint256[4] blsKey);
event OperatorUnregistered(address indexed operator);
event SetStakingContractMultiplier(address stakingContract, uint256 multiplier);
event OperatorRegisteredToEigenLayer(address operator);
event OperatorRegisteredToSymbiotic(address operator);
event OperatorUnregisteredToSymbiotic(address operator);
event NativeCoinNotSupportedForEigenRewards();
event RewardsCoordinatorReverted(bytes revertData);
event OperatorUnregisteredToEigenLayer(address operator);
// Errors
error ZeroAddress();
error Unauthorized(string message);
error NumOfOperatorsLimitReached(uint256 numOfOperatorsLimit);
error OperatorNotRegistered();
error OperatorAlreadyRegistered();
error InvalidBlsRegistrationSignature();
error InvalidRewardsReceiver();
error AllowlistDisabled();
error AllowlistEnabled();
error InvalidAllowlistAuthToken();
error ModificationDelayNotPassed();
error InvalidSlashingRate();
error InvalidStakingContract();
error AccessControlInvalidMultiplierSyncer();
error InvalidMultiplierNotSet();
error NotEnoughVotingPower();
error MissingAuthToken(bytes);
error EmptySharedSecurityProvidersList();
error InvalidSharedSecurityProviderList(uint256 arrayIndex);
error OperatorStillRegisteredToSharedSecurityProviders(address operator);
error EmptyAvsName();
error StakingContractsNotInAscendingOrder();
// Functions
/// @dev See extension contract for additional available methods implemented on AvsGovernanceExtension.sol
function EXTENSION_IMPLEMENTATION() external view returns (address);
// -------------------- Operators Interface -------------------- //
function registerAsOperator(OperatorRegistrationParams calldata _operatorRegistrationParams) external;
function unregisterAsOperatorFromEigenLayer() external;
function queueRewardsReceiverModification(address _rewardsReceiver) external;
function completeRewardsReceiverModification() external;
function votingPower(address _operator) external view returns (uint256);
function votingPowerPerStakingContracts(address _operator, address[] calldata _stakingContracts) external view returns (uint256);
// -------------------- Layer 2 Interface -------------------- //
function withdrawBatchRewards(PaymentRequestMessage[] memory _operators, uint256 _lastPayedTask, uint32 _remoteId) external;
function createOperatorDirectedAVSRewardsSubmission(IRewardsCoordinator.OperatorReward[] memory _operators, uint256 _lastPayedTask, bytes memory _data, uint32 _remoteId) external ;
// -------------------- AvsGovernance Multisig Interface -------------------- //
function setSupportedStakingContracts(StakingContractInfo[] memory _stakingContractsDetails) external;
// -------------------- IServiceManager Interface -------------------- //
function getOperatorRestakedStrategies(address operator) external view returns (address[] memory);
function getRestakeableStrategies() external view returns (address[] memory);
// -------------------- Register AVS to shared security provider -------------------- //
function registerAvsToEigenLayer(string calldata metadataURI) external;
function registerAvsToSymbiotic() external;
// -------------------- Register Operator to shared security provider -------------------- //
function registerOperatorToEigenLayer(ISignatureUtils.SignatureWithSaltAndExpiry memory _eigenSig, bytes calldata _authToken) external;
function registerOperatorToSymbiotic(SymbioticOptInSignature memory _symbioticSig, bytes calldata _authToken) external;
}
lib/contracts/src/NetworkManagement/L1/interfaces/IAvsGovernanceLogic.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.25;
/**
* @author Othentic Labs LTD.
* @notice Terms of Service: https://www.othentic.xyz/terms-of-service
* @notice Depending on the application, it may be necessary to add reentrancy gaurds to hooks
*/
interface IAvsGovernanceLogic {
function beforeOperatorRegistered(address _operator, uint256 _votingPower, uint256[4] calldata _blsKey, address _rewardsReceiver) external;
function afterOperatorRegistered(address _operator, uint256 _votingPower, uint256[4] calldata _blsKey, address _rewardsReceiver) external;
function beforeOperatorUnregistered(address _operator) external;
function afterOperatorUnregistered(address _operator) external;
}lib/contracts/src/NetworkManagement/L1/interfaces/IObsoleteAvsGovernance.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.25;
/*______ __ __ __ __
/ \ / | / | / | / |
/$$$$$$ | _$$ |_ $$ |____ ______ _______ _$$ |_ $$/ _______
$$ | $$ |/ $$ | $$ \ / \ / \ / $$ | / | / |
$$ | $$ |$$$$$$/ $$$$$$$ |/$$$$$$ |$$$$$$$ |$$$$$$/ $$ |/$$$$$$$/
$$ | $$ | $$ | __ $$ | $$ |$$ $$ |$$ | $$ | $$ | __ $$ |$$ |
$$ \__$$ | $$ |/ |$$ | $$ |$$$$$$$$/ $$ | $$ | $$ |/ |$$ |$$ \_____
$$ $$/ $$ $$/ $$ | $$ |$$ |$$ | $$ | $$ $$/ $$ |$$ |
$$$$$$/ $$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$$$/ $$/ $$$$$$$/
*/
import {IAvsGovernance} from "@othentic/NetworkManagement/L1/interfaces/IAvsGovernance.sol";
import {ISignatureUtils} from "@eigenlayer/contracts/interfaces/ISignatureUtils.sol";
import {BLSAuthLibrary} from "@othentic/NetworkManagement/Common/BLSAuthLibrary.sol";
interface IObsoleteAvsGovernance {
event MinStakeForStakingContractSet(
address stakingContract,
uint256 minShares
);
event SetStakingContractMultiplier(
address stakingContract,
uint256 multiplier
);
event setNewSupportedStakingContracts(address[] stakingContracts);
event OperatorUnregistered(address indexed operator);
event SetRewardsReceiver(address indexed operator, address receiver);
error ZeroAddress();
error InvalidStakingContract();
error OperatorNotRegistered();
error OperatorAlreadyRegistered();
error AllowlistDisabled();
error InvalidAllowlistAuthToken();
error NumOfOperatorsLimitReached(uint256 numOfOperatorsLimit);
error InvalidRewardsReceiver();
error NotEnoughVotingPower();
event OperatorRegistered(address indexed operator, uint256[4] blsKey);
error InvalidBlsRegistrationSignature();
error AllowlistEnabled();
// obsolete - only supports EigenLayer registration
function registerAsAllowedOperator(
uint256[4] calldata _blsKey,
bytes calldata _authToken,
address _rewardsReceiver,
ISignatureUtils.SignatureWithSaltAndExpiry calldata _operatorSignature,
BLSAuthLibrary.Signature calldata _blsRegistrationSignature
) external;
// obsolete - only supports EigenLayer registration
function registerAsOperator(
uint256[4] calldata _blsKey,
address _rewardsReceiver,
ISignatureUtils.SignatureWithSaltAndExpiry calldata _operatorSignature,
BLSAuthLibrary.Signature calldata _blsRegistrationSignature
) external;
// @obsolete - Use avsTreasury()
function vault() external view returns (address);
// @obsolete - Use minStakeAmountPerStakingContract()
function minSharesForStrategy(
address _stakingContract
) external view returns (uint256);
// @obsolete - Use stakingContracts()
function strategies() external view returns (address[] memory);
// @obsolete - Use multiplier()
function strategyMultiplier(
address _stakingContract
) external view returns (uint256);
// @obsolete - Use setMinStakesForStakingContract
function setMinSharesForStrategy(
address _stakingContract,
uint256 _minShares
) external;
// @obsolete - Use setStakingContractMultiplier
function setStrategyMultiplier(
IAvsGovernance.VotingPowerMultiplier calldata _votingPowerMultiplier
) external;
// @obsolete - Use setStakingContractMultiplierBatch
function setStrategyMultiplierBatch(
IAvsGovernance.VotingPowerMultiplier[] calldata _votingPowerMultipliers
) external;
// @obsolete - need to use registerAvsToEigenLayer
function updateAVSMetadataURI(string calldata metadataURI) external;
// obsolete - only supports EigenLayer, use setSupportedStakingContracts
function setSupportedStrategies(address[] memory _strategies) external;
// @obsolete - auth token required
function registerOperatorToEigenLayer(ISignatureUtils.SignatureWithSaltAndExpiry memory /*_eigenSig*/) external;
// @obsolete - auth token required
function registerOperatorToSymbiotic(IAvsGovernance.SymbioticOptInSignature memory /*_symbioticSig*/) external;
}
lib/contracts/src/NetworkManagement/L1/interfaces/IOthenticRegistry.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.25;
import "@othentic/NetworkManagement/L1/interfaces/IAvsGovernance.sol";
import { IRewardsCoordinator } from "@eigenlayer/contracts/interfaces/IRewardsCoordinator.sol";
import { IOptInService } from "@symbiotic/src/interfaces/service/IOptInService.sol";
import { INetworkRegistry } from "@symbiotic/src/interfaces/INetworkRegistry.sol";
import { INetworkMiddlewareService } from "@symbiotic/src/contracts/service/NetworkMiddlewareService.sol";
import { IVaultFactory } from "@symbiotic/src/contracts/VaultFactory.sol";
/*______ __ __ __ __
/ \ / | / | / | / |
/$$$$$$ | _$$ |_ $$ |____ ______ _______ _$$ |_ $$/ _______
$$ | $$ |/ $$ | $$ \ / \ / \ / $$ | / | / |
$$ | $$ |$$$$$$/ $$$$$$$ |/$$$$$$ |$$$$$$$ |$$$$$$/ $$ |/$$$$$$$/
$$ | $$ | $$ | __ $$ | $$ |$$ $$ |$$ | $$ | $$ | __ $$ |$$ |
$$ \__$$ | $$ |/ |$$ | $$ |$$$$$$$$/ $$ | $$ | $$ |/ |$$ |$$ \_____
$$ $$/ $$ $$/ $$ | $$ |$$ |$$ | $$ | $$ $$/ $$ |$$ |
$$$$$$/ $$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$$$/ $$/ $$$$$$$/
*/
/**
* @author Othentic Labs LTD.
* @notice Terms of Service: https://www.othentic.xyz/terms-of-service
*/
interface IOthenticRegistry {
struct InitializationParams {
address slasher;
address delegationManager;
address strategyManager;
address ownerMultiSig;
address vaultFactory;
address networkRegistry;
address optInService;
address networkMiddlewareService;
address l1AvsFactory;
address avsDirectory;
address rewardsCoordinator;
}
event OperatorOptIn(address operator, uint256 shares, uint32 serveUntilBlock);
event AvsOptIn(address avsGovernance, string avsName);
error InvalidBlockId();
// @obsolete
function getVotingPower(address _operator, IAvsGovernance.VotingPowerMultiplier[] calldata _votingPowerMultipliers) external view returns (uint256);
function getOperatorRestakedStrategies(address _operator, address[] memory _allStrategies, address _avsGovernance) external view returns (address[] memory);
function registerAvs(string memory _avsName) external;
function isValidStakeAmount(address _operator, IAvsGovernance.StakingContractDetails[] calldata _minStakePerStakingContract, address _avsGovernance) external view returns (bool);
function getDefaultStrategies(uint _chainid) external pure returns (IAvsGovernance.StakingContractInfo[] memory);
function isValidStakingContract(address _stakingContract) external view returns (bool);
function optInService() external view returns (IOptInService);
function networkRegistry() external view returns (INetworkRegistry);
function networkMiddlewareService() external view returns (INetworkMiddlewareService);
function rewardsCoordinator() external view returns (IRewardsCoordinator);
function vaultFactory() external view returns (IVaultFactory);
function getVotingPower(address _operator, IAvsGovernance.VotingPowerMultiplier[] calldata _votingPowerMultipliers, address _avsGovernance) external view returns (uint256);
}lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
struct AccessControlStorage {
mapping(bytes32 role => RoleData) _roles;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;
function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
assembly {
$.slot := AccessControlStorageLocation
}
}
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
AccessControlStorage storage $ = _getAccessControlStorage();
bytes32 previousAdminRole = getRoleAdmin(role);
$._roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (!hasRole(role, account)) {
$._roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (hasRole(role, account)) {
$._roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
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 "../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.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../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 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].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// 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;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._status = 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();
}
function _nonReentrantBefore() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// On the first call to nonReentrant, _status will be NOT_ENTERED
if ($._status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
$._status = ENTERED;
}
function _nonReentrantAfter() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
$._status = 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) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165Upgradeable is Initializable, IERC165 {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
lib/openzeppelin-contracts/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
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/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Proxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Proxy.sol)
pragma solidity ^0.8.20;
import {Proxy} from "../Proxy.sol";
import {ERC1967Utils} from "./ERC1967Utils.sol";
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*/
contract ERC1967Proxy is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an
* encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.
*
* Requirements:
*
* - If `data` is empty, `msg.value` must be zero.
*/
constructor(address implementation, bytes memory _data) payable {
ERC1967Utils.upgradeToAndCall(implementation, _data);
}
/**
* @dev Returns the current implementation address.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function _implementation() internal view virtual override returns (address) {
return ERC1967Utils.getImplementation();
}
}
lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.20;
import {IBeacon} from "../beacon/IBeacon.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*/
library ERC1967Utils {
// We re-declare ERC-1967 events here because they can't be used directly from IERC1967.
// This will be fixed in Solidity 0.8.21. At that point we should remove these events.
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
lib/openzeppelin-contracts/contracts/proxy/Proxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)
pragma solidity ^0.8.20;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overridden so it returns the address to which the fallback
* function and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
}
lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.20;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
lib/openzeppelin-contracts/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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 ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* 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;
* }
* }
* ```
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 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) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
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) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
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) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}
lib/openzeppelin-contracts/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @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;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
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 Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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.
*
* 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, RecoverError, bytes32) {
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.
/// @solidity memory-safe-assembly
assembly {
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 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.
*
* 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 Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
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, RecoverError, bytes32) {
// 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 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.0.0) (utils/cryptography/MessageHashUtils.sol)
pragma solidity ^0.8.20;
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[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
* specifications.
*/
library MessageHashUtils {
/**
* @dev Returns the keccak256 digest of an EIP-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://eth.wiki/json-rpc/API#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) {
/// @solidity memory-safe-assembly
assembly {
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 EIP-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://eth.wiki/json-rpc/API#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 EIP-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 Returns the keccak256 digest of an EIP-712 typed data (EIP-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) {
/// @solidity memory-safe-assembly
assembly {
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.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* 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[EIP 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.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return 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.
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
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^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// 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^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice 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) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice 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 + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @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 + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @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;
}
}
lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return 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 {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
/**
* @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.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [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 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;
}
// 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 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;
/// @solidity memory-safe-assembly
assembly {
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 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;
/// @solidity memory-safe-assembly
assembly {
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 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;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris",
"remappings": [
"ds-test/=lib/forge-std/lib/ds-test/src/",
"forge-std/=lib/forge-std/src/",
"@openzeppelin-upgrades/=lib/openzeppelin-contracts-upgradeable/",
"@openzeppelin/=lib/openzeppelin-contracts/",
"othentic-contracts-script/=lib/contracts/script/",
"@othentic-contracts/=lib/contracts/src/",
"@forge-safe/=lib/forge-safe/src/",
"@othentic-governance/script/=script/",
"@othentic-governance/src/=src/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"@eigenlayer-middleware/=lib/contracts/lib/eigenlayer-middleware/src/",
"@eigenlayer/=lib/contracts/lib/eigenlayer-contracts/src/",
"@layerzerolabs/lz-evm-messagelib-v2/=lib/contracts/lib/LayerZero-v2/messagelib/",
"@layerzerolabs/lz-evm-oapp-v2/=lib/contracts/lib/LayerZero-v2/oapp/",
"@layerzerolabs/lz-evm-protocol-v2/=lib/contracts/lib/LayerZero-v2/protocol/",
"@openzeppelin-upgradeable/=lib/contracts/lib/openzeppelin-contracts-upgradeable/",
"@openzeppelin-upgrades-v4.9.0/=lib/contracts/lib/eigenlayer-contracts/lib/openzeppelin-contracts-upgradeable-v4.9.0/",
"@openzeppelin-v4.9.0/=lib/contracts/lib/eigenlayer-contracts/lib/openzeppelin-contracts-v4.9.0/",
"@othentic-script/=lib/contracts/script/",
"@othentic-test/=lib/contracts/test/",
"@othentic/=lib/contracts/src/",
"@symbiotic/=lib/contracts/lib/core/",
"LayerZero-v2/=lib/contracts/lib/LayerZero-v2/",
"contracts/=lib/contracts/src/",
"core/=lib/contracts/lib/core/",
"eigenlayer-contracts/=lib/contracts/lib/eigenlayer-contracts/",
"eigenlayer-middleware/=lib/contracts/lib/eigenlayer-middleware/",
"forge-safe/=lib/forge-safe/",
"openzeppelin-contracts-upgradeable-v4.9.0/=lib/contracts/lib/eigenlayer-contracts/lib/openzeppelin-contracts-upgradeable-v4.9.0/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts-v4.9.0/=lib/contracts/lib/eigenlayer-contracts/lib/openzeppelin-contracts-v4.9.0/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"openzeppelin-upgrades/=lib/openzeppelin-upgrades/",
"openzeppelin/=lib/contracts/lib/eigenlayer-contracts/lib/openzeppelin-contracts-upgradeable-v4.9.0/contracts/",
"solidity-bytes-utils/contracts/=lib/contracts/src/lz/util/",
"solidity-stringutils/=lib/forge-safe/lib/surl/lib/solidity-stringutils/",
"solmate/=lib/solmate/src/",
"surl/=lib/forge-safe/lib/surl/",
"zeus-templates/=lib/contracts/lib/eigenlayer-contracts/lib/zeus-templates/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.