diff --git a/.github/workflows/forge-fmt.yml b/.github/workflows/forge-fmt.yml new file mode 100644 index 00000000..f1fa3cc6 --- /dev/null +++ b/.github/workflows/forge-fmt.yml @@ -0,0 +1,30 @@ +name: Forge Fmt + +on: + workflow_dispatch: + push: + branches: + - master + - mainnet + - testnet-goerli + - dev + pull_request: + +jobs: + check: + name: CI + strategy: + fail-fast: true + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + - name: Install Foundry + uses: foundry-rs/foundry-toolchain@v1 + with: + version: nightly + - name: Run forge fmt + run: | + forge fmt --check + id: fmt \ No newline at end of file diff --git a/foundry.toml b/foundry.toml index 3d0d84cb..7b02b1c8 100644 --- a/foundry.toml +++ b/foundry.toml @@ -1,33 +1,111 @@ [profile.default] -src = "src" -out = "out" -libs = ["lib"] -fs_permissions = [{ access = "read-write", path = "./" }] -gas_limit = 5000000000 - -ffi = true -no-match-contract = "FFI" - -# Enables or disables the optimizer -optimizer = true -# Sets the number of optimizer runs -optimizer_runs = 200 -# Whether or not to use the Yul intermediate representation compilation pipeline -via_ir = false -# Override the Solidity version (this overrides `auto_detect_solc`) -solc_version = '0.8.27' + # Project Configuration + + # Path to contract sources relative to the root of the project. + src = "src" + # Path to the test contract sources relative to the root of the project. + test = "test" + # Path to the script contract sources relative to the root of the project. + script = "script" + # Path to store contract artifacts relative to the root of the project. + out = "out" + # Array of paths that contain libraries, relative to the root of the project. + libs = ["lib"] + + # Solidity Compiler Configuration + + # Defines paths for Solidity imports. + remappings = [ + "@openzeppelin/=lib/openzeppelin-contracts-v4.9.0/", + "@openzeppelin-upgrades/=lib/openzeppelin-contracts-upgradeable-v4.9.0/", + "ds-test/=lib/ds-test/src/", + "forge-std/=lib/forge-std/src/" + ] + # Specifies the exact version of Solidity to use, overriding auto-detection. + solc_version = '0.8.27' + # If enabled, treats Solidity compiler warnings as errors, preventing artifact generation if warnings are present. + deny_warnings = false + # If set to true, changes compilation pipeline to go through the new IR optimizer. + via_ir = false + # Whether or not to enable the Solidity optimizer. + optimizer = true + # The number of runs specifies roughly how often each opcode of the deployed code will be executed + # across the life-time of the contract. This means it is a trade-off parameter between code size (deploy cost) + # and code execution cost (cost after deployment). + optimizer_runs = 200 + + # Test Configuration + + # Verbosity level during test execution. Higher levels provide more detailed information: + # - 2 (-vv): Logs emitted during tests are displayed. + # - 3 (-vvv): Stack traces for failing tests are displayed. + # - 4 (-vvvv): Stack traces for all tests and setup traces for failing tests are displayed. + # - 5 (-vvvvv): Stack and setup traces are always displayed. + verbosity = 0 + # Enables the Foreign Function Interface (FFI) cheatcode. + # WARNING: This allows arbitrary programs to run on your computer, which poses security risks. + ffi = true + # Contracts to include in gas reports. By default, all contracts are included. + gas_reports = ["./src/**/*"] + # Show test execution progress if set to true. + show_progress = true + # Sparse mode only compiles files that match certain criteria. + sparse_mode = true + + gas_limit = 5000000000 + no-match-contract = "FFI" + fs_permissions = [{ access = "read-write", path = "./" }] + +[profile.default.fmt] + # Single-line vs multi-line statement blocks + single_line_statement_blocks = "preserve" # Options: "single", "multi", "preserve" + # Formatting style for long function headers + multiline_func_header = "params_first" # Options: "attributes_first", "params_first", "all" + # Sort import statements alphabetically + sort_imports = false + # Maximum line length where formatter will wrap the line + line_length = 100 # Default: 120 + # Number of spaces per indentation level + tab_width = 4 # Default: 4 + # Whether to print spaces between brackets + bracket_spacing = false + # Style of uint/int256 types + int_types = "long" # Options: "long", "short", "preserve" + # Quotation mark style + quote_style = "double" # Options: "double", "single", "preserve" + # Style of underscores in number literals + number_underscore = "thousands" # Options: "preserve", "thousands", "remove" + # Whether or not to wrap comments at line_length + wrap_comments = false + # List of files to ignore during formatting (can use glob patterns) + # ignore = [ + # "./script/**/*", + # "./test/**/*" + # ] + +# TODO: Decide if we want to enable this. +# [profile.test.fmt] +# int_types = "short" +# line_length = 140 +# ignore = [ +# "./src/**/*" +# ] + +[profile.ci.fuzz] + optimizer = false + runs = 32 + +[profile.intense.fuzz] + optimizer = false + runs = 15000 + +[profile.forktest.fuzz] + runs = 16 + +[rpc_endpoints] + mainnet = "${RPC_MAINNET}" + holesky = "${RPC_HOLESKY}" [etherscan] -mainnet = { key = "${ETHERSCAN_API_KEY}" } -holesky = { key = "${ETHERSCAN_API_KEY}" } - -[fmt] -bracket_spacing = false -int_types = "long" -line_length = 100 -multiline_func_header = "params_first" -number_underscore = "thousands" -quote_style = "double" -tab_width = 4 - -# See more config options https://github.com/foundry-rs/foundry/blob/master/crates/config/README.md#all-options + mainnet = { key = "${ETHERSCAN_API_KEY}" } + holesky = { key = "${ETHERSCAN_API_KEY}" } \ No newline at end of file diff --git a/script/utils/OperatorSetUpgradeLib.sol b/script/utils/OperatorSetUpgradeLib.sol index 30e921dc..fe25839d 100644 --- a/script/utils/OperatorSetUpgradeLib.sol +++ b/script/utils/OperatorSetUpgradeLib.sol @@ -2,7 +2,8 @@ pragma solidity ^0.8.0; // Deploy L2AVS proxy -import {TransparentUpgradeableProxy} from "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol"; +import {TransparentUpgradeableProxy} from + "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol"; import {ProxyAdmin} from "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol"; import {Vm} from "forge-std/Vm.sol"; @@ -27,8 +28,7 @@ library OperatorSetUpgradeLib { * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1. */ bytes32 internal constant ADMIN_SLOT = - 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; - + 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; function upgrade(address proxy, address implementation, bytes memory data) internal { ProxyAdmin admin = ProxyAdmin(getAdmin(proxy)); @@ -40,13 +40,17 @@ library OperatorSetUpgradeLib { admin.upgrade(TransparentUpgradeableProxy(payable(proxy)), implementation); } - function getAdmin(address proxy) internal view returns (address) { + function getAdmin( + address proxy + ) internal view returns (address) { bytes32 value = vm.load(proxy, ADMIN_SLOT); return address(uint160(uint256(value))); } - function getImplementation(address proxy) internal view returns (address) { + function getImplementation( + address proxy + ) internal view returns (address) { bytes32 value = vm.load(proxy, IMPLEMENTATION_SLOT); return address(uint160(uint256(value))); } -} \ No newline at end of file +} diff --git a/src/BLSApkRegistry.sol b/src/BLSApkRegistry.sol index 189716a6..93972f5c 100644 --- a/src/BLSApkRegistry.sol +++ b/src/BLSApkRegistry.sol @@ -21,9 +21,11 @@ contract BLSApkRegistry is BLSApkRegistryStorage { IRegistryCoordinator _registryCoordinator ) BLSApkRegistryStorage(_registryCoordinator) {} - /******************************************************************************* - EXTERNAL FUNCTIONS - REGISTRY COORDINATOR - *******************************************************************************/ + /** + * + * EXTERNAL FUNCTIONS - REGISTRY COORDINATOR + * + */ /** * @notice Registers the `operator`'s pubkey for the specified `quorumNumbers`. @@ -41,7 +43,7 @@ contract BLSApkRegistry is BLSApkRegistryStorage { bytes memory quorumNumbers ) public virtual onlyRegistryCoordinator { // Get the operator's pubkey. Reverts if they have not registered a key - (BN254.G1Point memory pubkey, ) = getRegisteredPubkey(operator); + (BN254.G1Point memory pubkey,) = getRegisteredPubkey(operator); // Update each quorum's aggregate pubkey _processQuorumApkUpdate(quorumNumbers, pubkey); @@ -67,7 +69,7 @@ contract BLSApkRegistry is BLSApkRegistryStorage { bytes memory quorumNumbers ) public virtual onlyRegistryCoordinator { // Get the operator's pubkey. Reverts if they have not registered a key - (BN254.G1Point memory pubkey, ) = getRegisteredPubkey(operator); + (BN254.G1Point memory pubkey,) = getRegisteredPubkey(operator); // Update each quorum's aggregate pubkey _processQuorumApkUpdate(quorumNumbers, pubkey.negate()); @@ -78,14 +80,18 @@ contract BLSApkRegistry is BLSApkRegistryStorage { * @notice Initializes a new quorum by pushing its first apk update * @param quorumNumber The number of the new quorum */ - function initializeQuorum(uint8 quorumNumber) public virtual onlyRegistryCoordinator { + function initializeQuorum( + uint8 quorumNumber + ) public virtual onlyRegistryCoordinator { require(apkHistory[quorumNumber].length == 0, QuorumAlreadyExists()); - apkHistory[quorumNumber].push(ApkUpdate({ - apkHash: bytes24(0), - updateBlockNumber: uint32(block.number), - nextUpdateBlockNumber: 0 - })); + apkHistory[quorumNumber].push( + ApkUpdate({ + apkHash: bytes24(0), + updateBlockNumber: uint32(block.number), + nextUpdateBlockNumber: 0 + }) + ); } /** @@ -105,24 +111,31 @@ contract BLSApkRegistry is BLSApkRegistryStorage { require(pubkeyHashToOperator[pubkeyHash] == address(0), BLSPubkeyAlreadyRegistered()); // gamma = h(sigma, P, P', H(m)) - uint256 gamma = uint256(keccak256(abi.encodePacked( - params.pubkeyRegistrationSignature.X, - params.pubkeyRegistrationSignature.Y, - params.pubkeyG1.X, - params.pubkeyG1.Y, - params.pubkeyG2.X, - params.pubkeyG2.Y, - pubkeyRegistrationMessageHash.X, - pubkeyRegistrationMessageHash.Y - ))) % BN254.FR_MODULUS; + uint256 gamma = uint256( + keccak256( + abi.encodePacked( + params.pubkeyRegistrationSignature.X, + params.pubkeyRegistrationSignature.Y, + params.pubkeyG1.X, + params.pubkeyG1.Y, + params.pubkeyG2.X, + params.pubkeyG2.Y, + pubkeyRegistrationMessageHash.X, + pubkeyRegistrationMessageHash.Y + ) + ) + ) % BN254.FR_MODULUS; // e(sigma + P * gamma, [-1]_2) = e(H(m) + [1]_1 * gamma, P') - require(BN254.pairing( - params.pubkeyRegistrationSignature.plus(params.pubkeyG1.scalar_mul(gamma)), - BN254.negGeneratorG2(), - pubkeyRegistrationMessageHash.plus(BN254.generatorG1().scalar_mul(gamma)), - params.pubkeyG2 - ), InvalidBLSSignatureOrPrivateKey()); + require( + BN254.pairing( + params.pubkeyRegistrationSignature.plus(params.pubkeyG1.scalar_mul(gamma)), + BN254.negGeneratorG2(), + pubkeyRegistrationMessageHash.plus(BN254.generatorG1().scalar_mul(gamma)), + params.pubkeyG2 + ), + InvalidBLSSignatureOrPrivateKey() + ); operatorToPubkey[operator] = params.pubkeyG1; operatorToPubkeyHash[operator] = pubkeyHash; @@ -132,11 +145,15 @@ contract BLSApkRegistry is BLSApkRegistryStorage { return pubkeyHash; } - /******************************************************************************* - INTERNAL FUNCTIONS - *******************************************************************************/ - - function _processQuorumApkUpdate(bytes memory quorumNumbers, BN254.G1Point memory point) internal { + /** + * + * INTERNAL FUNCTIONS + * + */ + function _processQuorumApkUpdate( + bytes memory quorumNumbers, + BN254.G1Point memory point + ) internal { BN254.G1Point memory newApk; for (uint256 i = 0; i < quorumNumbers.length; i++) { @@ -157,23 +174,29 @@ contract BLSApkRegistry is BLSApkRegistryStorage { lastUpdate.apkHash = newApkHash; } else { lastUpdate.nextUpdateBlockNumber = uint32(block.number); - apkHistory[quorumNumber].push(ApkUpdate({ - apkHash: newApkHash, - updateBlockNumber: uint32(block.number), - nextUpdateBlockNumber: 0 - })); + apkHistory[quorumNumber].push( + ApkUpdate({ + apkHash: newApkHash, + updateBlockNumber: uint32(block.number), + nextUpdateBlockNumber: 0 + }) + ); } } } - /******************************************************************************* - VIEW FUNCTIONS - *******************************************************************************/ + /** + * + * VIEW FUNCTIONS + * + */ /** * @notice Returns the pubkey and pubkey hash of an operator * @dev Reverts if the operator has not registered a valid pubkey */ - function getRegisteredPubkey(address operator) public view returns (BN254.G1Point memory, bytes32) { + function getRegisteredPubkey( + address operator + ) public view returns (BN254.G1Point memory, bytes32) { BN254.G1Point memory pubkey = operatorToPubkey[operator]; bytes32 pubkeyHash = operatorToPubkeyHash[operator]; @@ -196,8 +219,13 @@ contract BLSApkRegistry is BLSApkRegistryStorage { uint8 quorumNumber = uint8(quorumNumbers[i]); uint256 quorumApkUpdatesLength = apkHistory[quorumNumber].length; - if (quorumApkUpdatesLength == 0 || blockNumber < apkHistory[quorumNumber][0].updateBlockNumber) { - revert("BLSApkRegistry.getApkIndicesAtBlockNumber: blockNumber is before the first update"); + if ( + quorumApkUpdatesLength == 0 + || blockNumber < apkHistory[quorumNumber][0].updateBlockNumber + ) { + revert( + "BLSApkRegistry.getApkIndicesAtBlockNumber: blockNumber is before the first update" + ); } // Loop backward through apkHistory until we find an entry that preceeds `blockNumber` @@ -212,12 +240,17 @@ contract BLSApkRegistry is BLSApkRegistryStorage { } /// @notice Returns the current APK for the provided `quorumNumber ` - function getApk(uint8 quorumNumber) external view returns (BN254.G1Point memory) { + function getApk( + uint8 quorumNumber + ) external view returns (BN254.G1Point memory) { return currentApk[quorumNumber]; } /// @notice Returns the `ApkUpdate` struct at `index` in the list of APK updates for the `quorumNumber` - function getApkUpdateAtIndex(uint8 quorumNumber, uint256 index) external view returns (ApkUpdate memory) { + function getApkUpdateAtIndex( + uint8 quorumNumber, + uint256 index + ) external view returns (ApkUpdate memory) { return apkHistory[quorumNumber][index]; } @@ -240,12 +273,10 @@ contract BLSApkRegistry is BLSApkRegistryStorage { * - blockNumber should be >= the update block number * - the next update block number should be either 0 or strictly greater than blockNumber */ + require(blockNumber >= quorumApkUpdate.updateBlockNumber, BlockNumberTooRecent()); require( - blockNumber >= quorumApkUpdate.updateBlockNumber, - BlockNumberTooRecent() - ); - require( - quorumApkUpdate.nextUpdateBlockNumber == 0 || blockNumber < quorumApkUpdate.nextUpdateBlockNumber, + quorumApkUpdate.nextUpdateBlockNumber == 0 + || blockNumber < quorumApkUpdate.nextUpdateBlockNumber, BlockNumberNotLatest() ); @@ -253,18 +284,24 @@ contract BLSApkRegistry is BLSApkRegistryStorage { } /// @notice Returns the length of ApkUpdates for the provided `quorumNumber` - function getApkHistoryLength(uint8 quorumNumber) external view returns (uint32) { + function getApkHistoryLength( + uint8 quorumNumber + ) external view returns (uint32) { return uint32(apkHistory[quorumNumber].length); } /// @notice Returns the operator address for the given `pubkeyHash` - function getOperatorFromPubkeyHash(bytes32 pubkeyHash) public view returns (address) { + function getOperatorFromPubkeyHash( + bytes32 pubkeyHash + ) public view returns (address) { return pubkeyHashToOperator[pubkeyHash]; } /// @notice returns the ID used to identify the `operator` within this AVS /// @dev Returns zero in the event that the `operator` has never registered for the AVS - function getOperatorId(address operator) public view returns (bytes32) { + function getOperatorId( + address operator + ) public view returns (bytes32) { return operatorToPubkeyHash[operator]; } diff --git a/src/BLSApkRegistryStorage.sol b/src/BLSApkRegistryStorage.sol index b35b9362..5007367a 100644 --- a/src/BLSApkRegistryStorage.sol +++ b/src/BLSApkRegistryStorage.sol @@ -10,7 +10,8 @@ import {BN254} from "./libraries/BN254.sol"; abstract contract BLSApkRegistryStorage is Initializable, IBLSApkRegistry { /// @notice the hash of the zero pubkey aka BN254.G1Point(0,0) - bytes32 internal constant ZERO_PK_HASH = hex"ad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5"; + bytes32 internal constant ZERO_PK_HASH = + hex"ad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5"; /// @notice the registry coordinator contract address public immutable registryCoordinator; @@ -29,7 +30,9 @@ abstract contract BLSApkRegistryStorage is Initializable, IBLSApkRegistry { /// @notice maps quorumNumber => current aggregate pubkey of quorum mapping(uint8 => BN254.G1Point) public currentApk; - constructor(IRegistryCoordinator _registryCoordinator) { + constructor( + IRegistryCoordinator _registryCoordinator + ) { registryCoordinator = address(_registryCoordinator); // disable initializers so that the implementation contract cannot be initialized _disableInitializers(); diff --git a/src/BLSSignatureChecker.sol b/src/BLSSignatureChecker.sol index 944ed4f7..2ff55e37 100644 --- a/src/BLSSignatureChecker.sol +++ b/src/BLSSignatureChecker.sol @@ -35,7 +35,9 @@ contract BLSSignatureChecker is IBLSSignatureChecker { _; } - constructor(IRegistryCoordinator _registryCoordinator) { + constructor( + IRegistryCoordinator _registryCoordinator + ) { registryCoordinator = _registryCoordinator; stakeRegistry = _registryCoordinator.stakeRegistry(); blsApkRegistry = _registryCoordinator.blsApkRegistry(); @@ -48,7 +50,9 @@ contract BLSSignatureChecker is IBLSSignatureChecker { * than the delegation.minWithdrawalDelayBlocks() window. * @param value to toggle staleStakesForbidden */ - function setStaleStakesForbidden(bool value) external onlyCoordinatorOwner { + function setStaleStakesForbidden( + bool value + ) external onlyCoordinatorOwner { _setStaleStakesForbidden(value); } @@ -91,16 +95,15 @@ contract BLSSignatureChecker is IBLSSignatureChecker { require(quorumNumbers.length != 0, InputEmptyQuorumNumbers()); require( - (quorumNumbers.length == params.quorumApks.length) && - (quorumNumbers.length == params.quorumApkIndices.length) && - (quorumNumbers.length == params.totalStakeIndices.length) && - (quorumNumbers.length == params.nonSignerStakeIndices.length), + (quorumNumbers.length == params.quorumApks.length) + && (quorumNumbers.length == params.quorumApkIndices.length) + && (quorumNumbers.length == params.totalStakeIndices.length) + && (quorumNumbers.length == params.nonSignerStakeIndices.length), InputArrayLengthMismatch() ); require( - params.nonSignerPubkeys.length == - params.nonSignerQuorumBitmapIndices.length, + params.nonSignerPubkeys.length == params.nonSignerQuorumBitmapIndices.length, InputNonSignerLengthMismatch() ); @@ -122,30 +125,25 @@ contract BLSSignatureChecker is IBLSSignatureChecker { stakeTotals.signedStakeForQuorum = new uint96[](quorumNumbers.length); NonSignerInfo memory nonSigners; - nonSigners.quorumBitmaps = new uint256[]( - params.nonSignerPubkeys.length - ); + nonSigners.quorumBitmaps = new uint256[](params.nonSignerPubkeys.length); nonSigners.pubkeyHashes = new bytes32[](params.nonSignerPubkeys.length); { // Get a bitmap of the quorums signing the message, and validate that // quorumNumbers contains only unique, valid quorum numbers uint256 signingQuorumBitmap = BitmapUtils.orderedBytesArrayToBitmap( - quorumNumbers, - registryCoordinator.quorumCount() + quorumNumbers, registryCoordinator.quorumCount() ); for (uint256 j = 0; j < params.nonSignerPubkeys.length; j++) { // The nonsigner's pubkey hash doubles as their operatorId // The check below validates that these operatorIds are sorted (and therefore // free of duplicates) - nonSigners.pubkeyHashes[j] = params - .nonSignerPubkeys[j] - .hashG1Point(); + nonSigners.pubkeyHashes[j] = params.nonSignerPubkeys[j].hashG1Point(); if (j != 0) { require( - uint256(nonSigners.pubkeyHashes[j]) > - uint256(nonSigners.pubkeyHashes[j - 1]), + uint256(nonSigners.pubkeyHashes[j]) + > uint256(nonSigners.pubkeyHashes[j - 1]), NonSignerPubkeysNotSorted() ); } @@ -153,19 +151,17 @@ contract BLSSignatureChecker is IBLSSignatureChecker { // Get the quorums the nonsigner was registered for at referenceBlockNumber nonSigners.quorumBitmaps[j] = registryCoordinator .getQuorumBitmapAtBlockNumberByIndex({ - operatorId: nonSigners.pubkeyHashes[j], - blockNumber: referenceBlockNumber, - index: params.nonSignerQuorumBitmapIndices[j] - }); + operatorId: nonSigners.pubkeyHashes[j], + blockNumber: referenceBlockNumber, + index: params.nonSignerQuorumBitmapIndices[j] + }); // Add the nonsigner's pubkey to the total apk, multiplied by the number // of quorums they have in common with the signing quorums, because their // public key will be a part of each signing quorum's aggregate pubkey apk = apk.plus( params.nonSignerPubkeys[j].scalar_mul_tiny( - BitmapUtils.countNumOnes( - nonSigners.quorumBitmaps[j] & signingQuorumBitmap - ) + BitmapUtils.countNumOnes(nonSigners.quorumBitmaps[j] & signingQuorumBitmap) ) ); } @@ -184,20 +180,16 @@ contract BLSSignatureChecker is IBLSSignatureChecker { */ { bool _staleStakesForbidden = staleStakesForbidden; - uint256 withdrawalDelayBlocks = _staleStakesForbidden - ? delegation.minWithdrawalDelayBlocks() - : 0; + uint256 withdrawalDelayBlocks = + _staleStakesForbidden ? delegation.minWithdrawalDelayBlocks() : 0; for (uint256 i = 0; i < quorumNumbers.length; i++) { // If we're disallowing stale stake updates, check that each quorum's last update block // is within withdrawalDelayBlocks if (_staleStakesForbidden) { require( - registryCoordinator.quorumUpdateBlockNumber( - uint8(quorumNumbers[i]) - ) + - withdrawalDelayBlocks > - referenceBlockNumber, + registryCoordinator.quorumUpdateBlockNumber(uint8(quorumNumbers[i])) + + withdrawalDelayBlocks > referenceBlockNumber, StaleStakesForbidden() ); } @@ -205,8 +197,8 @@ contract BLSSignatureChecker is IBLSSignatureChecker { // Validate params.quorumApks is correct for this quorum at the referenceBlockNumber, // then add it to the total apk require( - bytes24(params.quorumApks[i].hashG1Point()) == - blsApkRegistry.getApkHashAtBlockNumberAndIndex({ + bytes24(params.quorumApks[i].hashG1Point()) + == blsApkRegistry.getApkHashAtBlockNumberAndIndex({ quorumNumber: uint8(quorumNumbers[i]), blockNumber: referenceBlockNumber, index: params.quorumApkIndices[i] @@ -218,12 +210,11 @@ contract BLSSignatureChecker is IBLSSignatureChecker { // Get the total and starting signed stake for the quorum at referenceBlockNumber stakeTotals.totalStakeForQuorum[i] = stakeRegistry .getTotalStakeAtBlockNumberFromIndex({ - quorumNumber: uint8(quorumNumbers[i]), - blockNumber: referenceBlockNumber, - index: params.totalStakeIndices[i] - }); - stakeTotals.signedStakeForQuorum[i] = stakeTotals - .totalStakeForQuorum[i]; + quorumNumber: uint8(quorumNumbers[i]), + blockNumber: referenceBlockNumber, + index: params.totalStakeIndices[i] + }); + stakeTotals.signedStakeForQuorum[i] = stakeTotals.totalStakeForQuorum[i]; // Keep track of the nonSigners index in the quorum uint256 nonSignerForQuorumIndex = 0; @@ -232,21 +223,14 @@ contract BLSSignatureChecker is IBLSSignatureChecker { // if so, load their stake at referenceBlockNumber and subtract it from running stake signed for (uint256 j = 0; j < params.nonSignerPubkeys.length; j++) { // if the nonSigner is a part of the quorum, subtract their stake from the running total - if ( - BitmapUtils.isSet( - nonSigners.quorumBitmaps[j], - uint8(quorumNumbers[i]) - ) - ) { + if (BitmapUtils.isSet(nonSigners.quorumBitmaps[j], uint8(quorumNumbers[i]))) { stakeTotals.signedStakeForQuorum[i] -= stakeRegistry .getStakeAtBlockNumberAndIndex({ - quorumNumber: uint8(quorumNumbers[i]), - blockNumber: referenceBlockNumber, - operatorId: nonSigners.pubkeyHashes[j], - index: params.nonSignerStakeIndices[i][ - nonSignerForQuorumIndex - ] - }); + quorumNumber: uint8(quorumNumbers[i]), + blockNumber: referenceBlockNumber, + operatorId: nonSigners.pubkeyHashes[j], + index: params.nonSignerStakeIndices[i][nonSignerForQuorumIndex] + }); unchecked { ++nonSignerForQuorumIndex; } @@ -256,22 +240,14 @@ contract BLSSignatureChecker is IBLSSignatureChecker { } { // verify the signature - ( - bool pairingSuccessful, - bool signatureIsValid - ) = trySignatureAndApkVerification( - msgHash, - apk, - params.apkG2, - params.sigma - ); + (bool pairingSuccessful, bool signatureIsValid) = + trySignatureAndApkVerification(msgHash, apk, params.apkG2, params.sigma); require(pairingSuccessful, InvalidBLSPairingKey()); require(signatureIsValid, InvalidBLSSignature()); } // set signatoryRecordHash variable used for fraudproofs - bytes32 signatoryRecordHash = keccak256( - abi.encodePacked(referenceBlockNumber, nonSigners.pubkeyHashes) - ); + bytes32 signatoryRecordHash = + keccak256(abi.encodePacked(referenceBlockNumber, nonSigners.pubkeyHashes)); // return the total stakes that signed for each quorum, and a hash of the information required to prove the exact signers and stake return (stakeTotals, signatoryRecordHash); @@ -318,7 +294,9 @@ contract BLSSignatureChecker is IBLSSignatureChecker { ); } - function _setStaleStakesForbidden(bool value) internal { + function _setStaleStakesForbidden( + bool value + ) internal { staleStakesForbidden = value; emit StaleStakesForbiddenUpdate(value); } diff --git a/src/EjectionManager.sol b/src/EjectionManager.sol index 8ebf6002..f7d3d55d 100644 --- a/src/EjectionManager.sol +++ b/src/EjectionManager.sol @@ -11,7 +11,6 @@ import {IStakeRegistry} from "./interfaces/IStakeRegistry.sol"; * @author Layr Labs, Inc. */ contract EjectionManager is IEjectionManager, OwnableUpgradeable { - /// @notice The basis point denominator for the ejectable stake percent uint16 internal constant BIPS_DENOMINATOR = 10_000; @@ -31,10 +30,7 @@ contract EjectionManager is IEjectionManager, OwnableUpgradeable { /// @notice Ratelimit parameters for each quorum mapping(uint8 => QuorumEjectionParams) public quorumEjectionParams; - constructor( - IRegistryCoordinator _registryCoordinator, - IStakeRegistry _stakeRegistry - ) { + constructor(IRegistryCoordinator _registryCoordinator, IStakeRegistry _stakeRegistry) { registryCoordinator = _registryCoordinator; stakeRegistry = _stakeRegistry; @@ -52,10 +48,10 @@ contract EjectionManager is IEjectionManager, OwnableUpgradeable { QuorumEjectionParams[] memory _quorumEjectionParams ) external initializer { _transferOwnership(_owner); - for(uint8 i = 0; i < _ejectors.length; i++) { + for (uint8 i = 0; i < _ejectors.length; i++) { _setEjector(_ejectors[i], true); } - for(uint8 i = 0; i < _quorumEjectionParams.length; i++) { + for (uint8 i = 0; i < _quorumEjectionParams.length; i++) { _setQuorumEjectionParams(i, _quorumEjectionParams[i]); } } @@ -66,10 +62,12 @@ contract EjectionManager is IEjectionManager, OwnableUpgradeable { * @dev This function will eject as many operators as possible prioritizing operators at the lower index * @dev The owner can eject operators without recording of stake ejection */ - function ejectOperators(bytes32[][] memory _operatorIds) external { + function ejectOperators( + bytes32[][] memory _operatorIds + ) external { require(isEjector[msg.sender] || msg.sender == owner(), OnlyOwnerOrEjector()); - for(uint i = 0; i < _operatorIds.length; ++i) { + for (uint256 i = 0; i < _operatorIds.length; ++i) { uint8 quorumNumber = uint8(i); uint256 amountEjectable = amountEjectableForQuorum(quorumNumber); @@ -77,19 +75,18 @@ contract EjectionManager is IEjectionManager, OwnableUpgradeable { uint32 ejectedOperators; bool ratelimitHit; - for(uint8 j = 0; j < _operatorIds[i].length; ++j) { - uint256 operatorStake = stakeRegistry.getCurrentStake(_operatorIds[i][j], quorumNumber); + for (uint8 j = 0; j < _operatorIds[i].length; ++j) { + uint256 operatorStake = + stakeRegistry.getCurrentStake(_operatorIds[i][j], quorumNumber); //if caller is ejector enforce ratelimit - if( - isEjector[msg.sender] && - quorumEjectionParams[quorumNumber].rateLimitWindow > 0 && - stakeForEjection + operatorStake > amountEjectable - ){ - stakeEjectedForQuorum[quorumNumber].push(StakeEjection({ - timestamp: block.timestamp, - stakeEjected: stakeForEjection - })); + if ( + isEjector[msg.sender] && quorumEjectionParams[quorumNumber].rateLimitWindow > 0 + && stakeForEjection + operatorStake > amountEjectable + ) { + stakeEjectedForQuorum[quorumNumber].push( + StakeEjection({timestamp: block.timestamp, stakeEjected: stakeForEjection}) + ); ratelimitHit = true; break; } @@ -106,11 +103,10 @@ contract EjectionManager is IEjectionManager, OwnableUpgradeable { } //record the stake ejected if ejector and ratelimit enforced - if(!ratelimitHit && isEjector[msg.sender]){ - stakeEjectedForQuorum[quorumNumber].push(StakeEjection({ - timestamp: block.timestamp, - stakeEjected: stakeForEjection - })); + if (!ratelimitHit && isEjector[msg.sender]) { + stakeEjectedForQuorum[quorumNumber].push( + StakeEjection({timestamp: block.timestamp, stakeEjected: stakeForEjection}) + ); } emit QuorumEjection(ejectedOperators, ratelimitHit); @@ -122,7 +118,10 @@ contract EjectionManager is IEjectionManager, OwnableUpgradeable { * @param _quorumNumber The quorum number to set the ratelimit parameters for * @param _quorumEjectionParams The quorum ratelimit parameters to set for the given quorum */ - function setQuorumEjectionParams(uint8 _quorumNumber, QuorumEjectionParams memory _quorumEjectionParams) external onlyOwner() { + function setQuorumEjectionParams( + uint8 _quorumNumber, + QuorumEjectionParams memory _quorumEjectionParams + ) external onlyOwner { _setQuorumEjectionParams(_quorumNumber, _quorumEjectionParams); } @@ -131,15 +130,22 @@ contract EjectionManager is IEjectionManager, OwnableUpgradeable { * @param _ejector The address to permission * @param _status The status to set for the given address */ - function setEjector(address _ejector, bool _status) external onlyOwner() { + function setEjector(address _ejector, bool _status) external onlyOwner { _setEjector(_ejector, _status); } ///@dev internal function to set the quorum ejection params - function _setQuorumEjectionParams(uint8 _quorumNumber, QuorumEjectionParams memory _quorumEjectionParams) internal { + function _setQuorumEjectionParams( + uint8 _quorumNumber, + QuorumEjectionParams memory _quorumEjectionParams + ) internal { require(_quorumNumber < MAX_QUORUM_COUNT, MaxQuorumCount()); quorumEjectionParams[_quorumNumber] = _quorumEjectionParams; - emit QuorumEjectionParamsSet(_quorumNumber, _quorumEjectionParams.rateLimitWindow, _quorumEjectionParams.ejectableStakePercent); + emit QuorumEjectionParamsSet( + _quorumNumber, + _quorumEjectionParams.rateLimitWindow, + _quorumEjectionParams.ejectableStakePercent + ); } ///@dev internal function to set the ejector @@ -152,7 +158,9 @@ contract EjectionManager is IEjectionManager, OwnableUpgradeable { * @notice Returns the amount of stake that can be ejected for a quorum at the current block.timestamp * @param _quorumNumber The quorum number to view ejectable stake for */ - function amountEjectableForQuorum(uint8 _quorumNumber) public view returns (uint256) { + function amountEjectableForQuorum( + uint8 _quorumNumber + ) public view returns (uint256) { uint256 totalEjectable = uint256(quorumEjectionParams[_quorumNumber].ejectableStakePercent) * uint256(stakeRegistry.getCurrentTotalStake(_quorumNumber)) / uint256(BIPS_DENOMINATOR); diff --git a/src/IndexRegistry.sol b/src/IndexRegistry.sol index cab62a17..c8b46061 100644 --- a/src/IndexRegistry.sol +++ b/src/IndexRegistry.sol @@ -9,7 +9,6 @@ import {IRegistryCoordinator} from "./interfaces/IRegistryCoordinator.sol"; * @author Layr Labs, Inc. */ contract IndexRegistry is IndexRegistryStorage { - /// @notice when applied to a function, only allows the RegistryCoordinator to call it modifier onlyRegistryCoordinator() { _checkRegistryCoordinator(); @@ -21,9 +20,11 @@ contract IndexRegistry is IndexRegistryStorage { IRegistryCoordinator _registryCoordinator ) IndexRegistryStorage(_registryCoordinator) {} - /******************************************************************************* - EXTERNAL FUNCTIONS - REGISTRY COORDINATOR - *******************************************************************************/ + /** + * + * EXTERNAL FUNCTIONS - REGISTRY COORDINATOR + * + */ /** * @notice Registers the operator with the specified `operatorId` for the quorums specified by `quorumNumbers`. @@ -40,7 +41,7 @@ contract IndexRegistry is IndexRegistryStorage { function registerOperator( bytes32 operatorId, bytes calldata quorumNumbers - ) public virtual onlyRegistryCoordinator returns(uint32[] memory) { + ) public virtual onlyRegistryCoordinator returns (uint32[] memory) { uint32[] memory numOperatorsPerQuorum = new uint32[](quorumNumbers.length); for (uint256 i = 0; i < quorumNumbers.length; i++) { @@ -112,23 +113,28 @@ contract IndexRegistry is IndexRegistryStorage { * @notice Initialize a quorum by pushing its first quorum update * @param quorumNumber The number of the new quorum */ - function initializeQuorum(uint8 quorumNumber) public virtual onlyRegistryCoordinator { + function initializeQuorum( + uint8 quorumNumber + ) public virtual onlyRegistryCoordinator { require(_operatorCountHistory[quorumNumber].length == 0, QuorumDoesNotExist()); - _operatorCountHistory[quorumNumber].push(QuorumUpdate({ - numOperators: 0, - fromBlockNumber: uint32(block.number) - })); + _operatorCountHistory[quorumNumber].push( + QuorumUpdate({numOperators: 0, fromBlockNumber: uint32(block.number)}) + ); } - /******************************************************************************* - INTERNAL FUNCTIONS - *******************************************************************************/ + /** + * + * INTERNAL FUNCTIONS + * + */ /** * @notice Increases the historical operator count by 1 and returns the new count */ - function _increaseOperatorCount(uint8 quorumNumber) internal returns (uint32) { + function _increaseOperatorCount( + uint8 quorumNumber + ) internal returns (uint32) { QuorumUpdate storage lastUpdate = _latestQuorumUpdate(quorumNumber); uint32 newOperatorCount = lastUpdate.numOperators + 1; @@ -137,10 +143,12 @@ contract IndexRegistry is IndexRegistryStorage { // If this is the first time we're using this operatorIndex, push its first update // This maintains an invariant: existing indices have nonzero history if (_operatorIndexHistory[quorumNumber][newOperatorCount - 1].length == 0) { - _operatorIndexHistory[quorumNumber][newOperatorCount - 1].push(OperatorUpdate({ - operatorId: OPERATOR_DOES_NOT_EXIST_ID, - fromBlockNumber: uint32(block.number) - })); + _operatorIndexHistory[quorumNumber][newOperatorCount - 1].push( + OperatorUpdate({ + operatorId: OPERATOR_DOES_NOT_EXIST_ID, + fromBlockNumber: uint32(block.number) + }) + ); } return newOperatorCount; @@ -149,7 +157,9 @@ contract IndexRegistry is IndexRegistryStorage { /** * @notice Decreases the historical operator count by 1 and returns the new count */ - function _decreaseOperatorCount(uint8 quorumNumber) internal returns (uint32) { + function _decreaseOperatorCount( + uint8 quorumNumber + ) internal returns (uint32) { QuorumUpdate storage lastUpdate = _latestQuorumUpdate(quorumNumber); uint32 newOperatorCount = lastUpdate.numOperators - 1; @@ -171,10 +181,9 @@ contract IndexRegistry is IndexRegistryStorage { if (lastUpdate.fromBlockNumber == uint32(block.number)) { lastUpdate.numOperators = newOperatorCount; } else { - _operatorCountHistory[quorumNumber].push(QuorumUpdate({ - numOperators: newOperatorCount, - fromBlockNumber: uint32(block.number) - })); + _operatorCountHistory[quorumNumber].push( + QuorumUpdate({numOperators: newOperatorCount, fromBlockNumber: uint32(block.number)}) + ); } } @@ -183,12 +192,17 @@ contract IndexRegistry is IndexRegistryStorage { * @dev The last entry's operatorId is updated to OPERATOR_DOES_NOT_EXIST_ID * @return The removed operatorId */ - function _popLastOperator(uint8 quorumNumber, uint32 operatorIndex) internal returns (bytes32) { + function _popLastOperator( + uint8 quorumNumber, + uint32 operatorIndex + ) internal returns (bytes32) { OperatorUpdate storage lastUpdate = _latestOperatorIndexUpdate(quorumNumber, operatorIndex); bytes32 removedOperatorId = lastUpdate.operatorId; // Set the current operator id for this operatorIndex to 0 - _updateOperatorIndexHistory(quorumNumber, operatorIndex, lastUpdate, OPERATOR_DOES_NOT_EXIST_ID); + _updateOperatorIndexHistory( + quorumNumber, operatorIndex, lastUpdate, OPERATOR_DOES_NOT_EXIST_ID + ); return removedOperatorId; } @@ -199,7 +213,11 @@ contract IndexRegistry is IndexRegistryStorage { * @param quorumNumber quorumNumber of the operator to update * @param operatorIndex the latest index of that operator in the list of operators registered for this quorum */ - function _assignOperatorToIndex(bytes32 operatorId, uint8 quorumNumber, uint32 operatorIndex) internal { + function _assignOperatorToIndex( + bytes32 operatorId, + uint8 quorumNumber, + uint32 operatorIndex + ) internal { OperatorUpdate storage lastUpdate = _latestOperatorIndexUpdate(quorumNumber, operatorIndex); _updateOperatorIndexHistory(quorumNumber, operatorIndex, lastUpdate, operatorId); @@ -223,23 +241,27 @@ contract IndexRegistry is IndexRegistryStorage { if (lastUpdate.fromBlockNumber == uint32(block.number)) { lastUpdate.operatorId = newOperatorId; } else { - _operatorIndexHistory[quorumNumber][operatorIndex].push(OperatorUpdate({ - operatorId: newOperatorId, - fromBlockNumber: uint32(block.number) - })); + _operatorIndexHistory[quorumNumber][operatorIndex].push( + OperatorUpdate({operatorId: newOperatorId, fromBlockNumber: uint32(block.number)}) + ); } } /// @notice Returns the most recent operator count update for a quorum /// @dev Reverts if the quorum does not exist (history length == 0) - function _latestQuorumUpdate(uint8 quorumNumber) internal view returns (QuorumUpdate storage) { + function _latestQuorumUpdate( + uint8 quorumNumber + ) internal view returns (QuorumUpdate storage) { uint256 historyLength = _operatorCountHistory[quorumNumber].length; return _operatorCountHistory[quorumNumber][historyLength - 1]; } /// @notice Returns the most recent operator id update for an index /// @dev Reverts if the index has never been used (history length == 0) - function _latestOperatorIndexUpdate(uint8 quorumNumber, uint32 operatorIndex) internal view returns (OperatorUpdate storage) { + function _latestOperatorIndexUpdate( + uint8 quorumNumber, + uint32 operatorIndex + ) internal view returns (OperatorUpdate storage) { uint256 historyLength = _operatorIndexHistory[quorumNumber][operatorIndex].length; return _operatorIndexHistory[quorumNumber][operatorIndex][historyLength - 1]; } @@ -251,7 +273,7 @@ contract IndexRegistry is IndexRegistryStorage { function _operatorCountAtBlockNumber( uint8 quorumNumber, uint32 blockNumber - ) internal view returns (uint32){ + ) internal view returns (uint32) { uint256 historyLength = _operatorCountHistory[quorumNumber].length; // Loop backwards through _operatorCountHistory until we find an entry that preceeds `blockNumber` @@ -263,7 +285,9 @@ contract IndexRegistry is IndexRegistryStorage { } } - revert("IndexRegistry._operatorCountAtBlockNumber: quorum did not exist at given block number"); + revert( + "IndexRegistry._operatorCountAtBlockNumber: quorum did not exist at given block number" + ); } /** @@ -274,12 +298,13 @@ contract IndexRegistry is IndexRegistryStorage { uint8 quorumNumber, uint32 operatorIndex, uint32 blockNumber - ) internal view returns(bytes32) { + ) internal view returns (bytes32) { uint256 historyLength = _operatorIndexHistory[quorumNumber][operatorIndex].length; // Loop backward through _operatorIndexHistory until we find an entry that preceeds `blockNumber` for (uint256 i = historyLength; i > 0; i--) { - OperatorUpdate memory operatorIndexUpdate = _operatorIndexHistory[quorumNumber][operatorIndex][i - 1]; + OperatorUpdate memory operatorIndexUpdate = + _operatorIndexHistory[quorumNumber][operatorIndex][i - 1]; if (operatorIndexUpdate.fromBlockNumber <= blockNumber) { // Special case: this will be OPERATOR_DOES_NOT_EXIST_ID if this operatorIndex was not used at the block number @@ -291,30 +316,44 @@ contract IndexRegistry is IndexRegistryStorage { return OPERATOR_DOES_NOT_EXIST_ID; } - /******************************************************************************* - VIEW FUNCTIONS - *******************************************************************************/ + /** + * + * VIEW FUNCTIONS + * + */ /// @notice Returns the _operatorIndexHistory entry for the specified `operatorIndex` and `quorumNumber` /// at the specified `arrayIndex` - function getOperatorUpdateAtIndex(uint8 quorumNumber, uint32 operatorIndex, uint32 arrayIndex) external view returns (OperatorUpdate memory) { + function getOperatorUpdateAtIndex( + uint8 quorumNumber, + uint32 operatorIndex, + uint32 arrayIndex + ) external view returns (OperatorUpdate memory) { return _operatorIndexHistory[quorumNumber][operatorIndex][arrayIndex]; } /// @notice Returns the _operatorCountHistory entry for the specified `quorumNumber` at the specified `quorumIndex` - function getQuorumUpdateAtIndex(uint8 quorumNumber, uint32 quorumIndex) external view returns (QuorumUpdate memory) { + function getQuorumUpdateAtIndex( + uint8 quorumNumber, + uint32 quorumIndex + ) external view returns (QuorumUpdate memory) { return _operatorCountHistory[quorumNumber][quorumIndex]; } /// @notice Returns the most recent QuorumUpdate entry for the specified quorumNumber /// @dev Reverts if the quorum does not exist - function getLatestQuorumUpdate(uint8 quorumNumber) external view returns (QuorumUpdate memory) { + function getLatestQuorumUpdate( + uint8 quorumNumber + ) external view returns (QuorumUpdate memory) { return _latestQuorumUpdate(quorumNumber); } /// @notice Returns the most recent OperatorUpdate entry for the specified quorumNumber and operatorIndex /// @dev Reverts if there is no update for the given operatorIndex - function getLatestOperatorUpdate(uint8 quorumNumber, uint32 operatorIndex) external view returns (OperatorUpdate memory) { + function getLatestOperatorUpdate( + uint8 quorumNumber, + uint32 operatorIndex + ) external view returns (OperatorUpdate memory) { return _latestOperatorIndexUpdate(quorumNumber, operatorIndex); } @@ -322,22 +361,21 @@ contract IndexRegistry is IndexRegistryStorage { function getOperatorListAtBlockNumber( uint8 quorumNumber, uint32 blockNumber - ) external view returns (bytes32[] memory){ + ) external view returns (bytes32[] memory) { uint32 operatorCount = _operatorCountAtBlockNumber(quorumNumber, blockNumber); bytes32[] memory operatorList = new bytes32[](operatorCount); for (uint256 i = 0; i < operatorCount; i++) { operatorList[i] = _operatorIdForIndexAtBlockNumber(quorumNumber, uint32(i), blockNumber); - require( - operatorList[i] != OPERATOR_DOES_NOT_EXIST_ID, - OperatorIdDoesNotExist() - ); + require(operatorList[i] != OPERATOR_DOES_NOT_EXIST_ID, OperatorIdDoesNotExist()); } return operatorList; } /// @notice Returns the total number of operators for a given `quorumNumber` /// @dev This will revert if the quorum does not exist - function totalOperatorsForQuorum(uint8 quorumNumber) external view returns (uint32){ + function totalOperatorsForQuorum( + uint8 quorumNumber + ) external view returns (uint32) { return _latestQuorumUpdate(quorumNumber).numOperators; } diff --git a/src/IndexRegistryStorage.sol b/src/IndexRegistryStorage.sol index b5b800d6..95f39e34 100644 --- a/src/IndexRegistryStorage.sol +++ b/src/IndexRegistryStorage.sol @@ -12,7 +12,6 @@ import {IIndexRegistry} from "./interfaces/IIndexRegistry.sol"; * @notice This storage contract is separate from the logic to simplify the upgrade process. */ abstract contract IndexRegistryStorage is Initializable, IIndexRegistry { - /// @notice The value that is returned when an operator does not exist at an index at a certain block bytes32 public constant OPERATOR_DOES_NOT_EXIST_ID = bytes32(0); @@ -32,7 +31,7 @@ abstract contract IndexRegistryStorage is Initializable, IIndexRegistry { constructor( IRegistryCoordinator _registryCoordinator - ){ + ) { registryCoordinator = address(_registryCoordinator); // disable initializers so that the implementation contract cannot be initialized _disableInitializers(); diff --git a/src/OperatorStateRetriever.sol b/src/OperatorStateRetriever.sol index 87672b66..82dc8d6e 100644 --- a/src/OperatorStateRetriever.sol +++ b/src/OperatorStateRetriever.sol @@ -46,9 +46,11 @@ contract OperatorStateRetriever { ) external view returns (uint256, Operator[][] memory) { bytes32[] memory operatorIds = new bytes32[](1); operatorIds[0] = operatorId; - uint256 index = registryCoordinator.getQuorumBitmapIndicesAtBlockNumber(blockNumber, operatorIds)[0]; + uint256 index = + registryCoordinator.getQuorumBitmapIndicesAtBlockNumber(blockNumber, operatorIds)[0]; - uint256 quorumBitmap = registryCoordinator.getQuorumBitmapAtBlockNumberByIndex(operatorId, blockNumber, index); + uint256 quorumBitmap = + registryCoordinator.getQuorumBitmapAtBlockNumberByIndex(operatorId, blockNumber, index); bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmap); @@ -67,7 +69,7 @@ contract OperatorStateRetriever { IRegistryCoordinator registryCoordinator, bytes memory quorumNumbers, uint32 blockNumber - ) public view returns(Operator[][] memory) { + ) public view returns (Operator[][] memory) { IStakeRegistry stakeRegistry = registryCoordinator.stakeRegistry(); IIndexRegistry indexRegistry = registryCoordinator.indexRegistry(); IBLSApkRegistry blsApkRegistry = registryCoordinator.blsApkRegistry(); @@ -75,13 +77,16 @@ contract OperatorStateRetriever { Operator[][] memory operators = new Operator[][](quorumNumbers.length); for (uint256 i = 0; i < quorumNumbers.length; i++) { uint8 quorumNumber = uint8(quorumNumbers[i]); - bytes32[] memory operatorIds = indexRegistry.getOperatorListAtBlockNumber(quorumNumber, blockNumber); + bytes32[] memory operatorIds = + indexRegistry.getOperatorListAtBlockNumber(quorumNumber, blockNumber); operators[i] = new Operator[](operatorIds.length); for (uint256 j = 0; j < operatorIds.length; j++) { operators[i][j] = Operator({ operator: blsApkRegistry.getOperatorFromPubkeyHash(operatorIds[j]), operatorId: bytes32(operatorIds[j]), - stake: stakeRegistry.getStakeAtBlockNumber(bytes32(operatorIds[j]), quorumNumber, blockNumber) + stake: stakeRegistry.getStakeAtBlockNumber( + bytes32(operatorIds[j]), quorumNumber, blockNumber + ) }); } } @@ -113,32 +118,40 @@ contract OperatorStateRetriever { CheckSignaturesIndices memory checkSignaturesIndices; // get the indices of the quorumBitmap updates for each of the operators in the nonSignerOperatorIds array - checkSignaturesIndices.nonSignerQuorumBitmapIndices = registryCoordinator.getQuorumBitmapIndicesAtBlockNumber(referenceBlockNumber, nonSignerOperatorIds); + checkSignaturesIndices.nonSignerQuorumBitmapIndices = registryCoordinator + .getQuorumBitmapIndicesAtBlockNumber(referenceBlockNumber, nonSignerOperatorIds); // get the indices of the totalStake updates for each of the quorums in the quorumNumbers array - checkSignaturesIndices.totalStakeIndices = stakeRegistry.getTotalStakeIndicesAtBlockNumber(referenceBlockNumber, quorumNumbers); + checkSignaturesIndices.totalStakeIndices = + stakeRegistry.getTotalStakeIndicesAtBlockNumber(referenceBlockNumber, quorumNumbers); checkSignaturesIndices.nonSignerStakeIndices = new uint32[][](quorumNumbers.length); - for (uint8 quorumNumberIndex = 0; quorumNumberIndex < quorumNumbers.length; quorumNumberIndex++) { + for ( + uint8 quorumNumberIndex = 0; + quorumNumberIndex < quorumNumbers.length; + quorumNumberIndex++ + ) { uint256 numNonSignersForQuorum = 0; // this array's length will be at most the number of nonSignerOperatorIds, this will be trimmed after it is filled - checkSignaturesIndices.nonSignerStakeIndices[quorumNumberIndex] = new uint32[](nonSignerOperatorIds.length); + checkSignaturesIndices.nonSignerStakeIndices[quorumNumberIndex] = + new uint32[](nonSignerOperatorIds.length); - for (uint i = 0; i < nonSignerOperatorIds.length; i++) { + for (uint256 i = 0; i < nonSignerOperatorIds.length; i++) { // get the quorumBitmap for the operator at the given blocknumber and index - uint192 nonSignerQuorumBitmap = - registryCoordinator.getQuorumBitmapAtBlockNumberByIndex( - nonSignerOperatorIds[i], - referenceBlockNumber, - checkSignaturesIndices.nonSignerQuorumBitmapIndices[i] - ); + uint192 nonSignerQuorumBitmap = registryCoordinator + .getQuorumBitmapAtBlockNumberByIndex( + nonSignerOperatorIds[i], + referenceBlockNumber, + checkSignaturesIndices.nonSignerQuorumBitmapIndices[i] + ); require(nonSignerQuorumBitmap != 0, OperatorNotRegistered()); // if the operator was a part of the quorum and the quorum is a part of the provided quorumNumbers if ((nonSignerQuorumBitmap >> uint8(quorumNumbers[quorumNumberIndex])) & 1 == 1) { // get the index of the stake update for the operator at the given blocknumber and quorum number - checkSignaturesIndices.nonSignerStakeIndices[quorumNumberIndex][numNonSignersForQuorum] = stakeRegistry.getStakeUpdateIndexAtBlockNumber( + checkSignaturesIndices.nonSignerStakeIndices[quorumNumberIndex][numNonSignersForQuorum] + = stakeRegistry.getStakeUpdateIndexAtBlockNumber( nonSignerOperatorIds[i], uint8(quorumNumbers[quorumNumberIndex]), referenceBlockNumber @@ -149,15 +162,18 @@ contract OperatorStateRetriever { // resize the array to the number of nonSigners for this quorum uint32[] memory nonSignerStakeIndicesForQuorum = new uint32[](numNonSignersForQuorum); - for (uint i = 0; i < numNonSignersForQuorum; i++) { - nonSignerStakeIndicesForQuorum[i] = checkSignaturesIndices.nonSignerStakeIndices[quorumNumberIndex][i]; + for (uint256 i = 0; i < numNonSignersForQuorum; i++) { + nonSignerStakeIndicesForQuorum[i] = + checkSignaturesIndices.nonSignerStakeIndices[quorumNumberIndex][i]; } - checkSignaturesIndices.nonSignerStakeIndices[quorumNumberIndex] = nonSignerStakeIndicesForQuorum; + checkSignaturesIndices.nonSignerStakeIndices[quorumNumberIndex] = + nonSignerStakeIndicesForQuorum; } IBLSApkRegistry blsApkRegistry = registryCoordinator.blsApkRegistry(); // get the indices of the quorum apks for each of the provided quorums at the given blocknumber - checkSignaturesIndices.quorumApkIndices = blsApkRegistry.getApkIndicesAtBlockNumber(quorumNumbers, referenceBlockNumber); + checkSignaturesIndices.quorumApkIndices = + blsApkRegistry.getApkIndicesAtBlockNumber(quorumNumbers, referenceBlockNumber); return checkSignaturesIndices; } @@ -173,10 +189,13 @@ contract OperatorStateRetriever { bytes32[] memory operatorIds, uint32 blockNumber ) external view returns (uint256[] memory) { - uint32[] memory quorumBitmapIndices = registryCoordinator.getQuorumBitmapIndicesAtBlockNumber(blockNumber, operatorIds); + uint32[] memory quorumBitmapIndices = + registryCoordinator.getQuorumBitmapIndicesAtBlockNumber(blockNumber, operatorIds); uint256[] memory quorumBitmaps = new uint256[](operatorIds.length); for (uint256 i = 0; i < operatorIds.length; i++) { - quorumBitmaps[i] = registryCoordinator.getQuorumBitmapAtBlockNumberByIndex(operatorIds[i], blockNumber, quorumBitmapIndices[i]); + quorumBitmaps[i] = registryCoordinator.getQuorumBitmapAtBlockNumberByIndex( + operatorIds[i], blockNumber, quorumBitmapIndices[i] + ); } return quorumBitmaps; } @@ -212,5 +231,4 @@ contract OperatorStateRetriever { operators[i] = registryCoordinator.getOperatorFromId(operatorIds[i]); } } - } diff --git a/src/RegistryCoordinator.sol b/src/RegistryCoordinator.sol index 9a55ffc5..7b906a70 100644 --- a/src/RegistryCoordinator.sol +++ b/src/RegistryCoordinator.sol @@ -3,8 +3,12 @@ pragma solidity ^0.8.27; import {IPauserRegistry} from "eigenlayer-contracts/src/contracts/interfaces/IPauserRegistry.sol"; import {ISignatureUtils} from "eigenlayer-contracts/src/contracts/interfaces/ISignatureUtils.sol"; -import {IStrategy } from "eigenlayer-contracts/src/contracts/interfaces/IStrategy.sol"; -import {IAllocationManager, OperatorSet, IAllocationManagerTypes} from "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; +import {IStrategy} from "eigenlayer-contracts/src/contracts/interfaces/IStrategy.sol"; +import { + IAllocationManager, + OperatorSet, + IAllocationManagerTypes +} from "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; import {ISocketUpdater} from "./interfaces/ISocketUpdater.sol"; import {IBLSApkRegistry} from "./interfaces/IBLSApkRegistry.sol"; import {IStakeRegistry, StakeType} from "./interfaces/IStakeRegistry.sol"; @@ -54,7 +58,9 @@ contract RegistryCoordinator is /// @dev Checks that `quorumNumber` corresponds to a quorum that has been created /// via `initialize` or `createQuorum` - modifier quorumExists(uint8 quorumNumber) { + modifier quorumExists( + uint8 quorumNumber + ) { _checkQuorumExists(quorumNumber); _; } @@ -122,7 +128,13 @@ contract RegistryCoordinator is // Create quorums for (uint256 i = 0; i < _operatorSetParams.length; i++) { - _createQuorum(_operatorSetParams[i], _minimumStakes[i], _strategyParams[i], _stakeTypes[i], _lookAheadPeriods[i]); + _createQuorum( + _operatorSetParams[i], + _minimumStakes[i], + _strategyParams[i], + _stakeTypes[i], + _lookAheadPeriods[i] + ); } } @@ -201,10 +213,7 @@ contract RegistryCoordinator is SignatureWithSaltAndExpiry memory operatorSignature ) external onlyWhenNotPaused(PAUSED_REGISTER_OPERATOR) { require(!isUsingOperatorSets(), OperatorSetsEnabled()); - require( - operatorKickParams.length == quorumNumbers.length, - InputLengthMismatch() - ); + require(operatorKickParams.length == quorumNumbers.length, InputLengthMismatch()); /** * If the operator has NEVER registered a pubkey before, use `params` to register @@ -261,19 +270,15 @@ contract RegistryCoordinator is * @notice Deregisters the caller from one or more quorums * @param quorumNumbers is an ordered byte array containing the quorum numbers being deregistered from */ - function deregisterOperator(bytes memory quorumNumbers) - external - onlyWhenNotPaused(PAUSED_DEREGISTER_OPERATOR) - { + function deregisterOperator( + bytes memory quorumNumbers + ) external onlyWhenNotPaused(PAUSED_DEREGISTER_OPERATOR) { // Check that either: // 1. The AVS hasn't migrated to operator sets yet (!isOperatorSetAVS), or // 2. The AVS has migrated but this is an M2 quorum for (uint256 i = 0; i < quorumNumbers.length; i++) { uint8 quorumNumber = uint8(quorumNumbers[i]); - require( - !isOperatorSetAVS || isM2Quorum[quorumNumber], - OperatorSetsEnabled() - ); + require(!isOperatorSetAVS || isM2Quorum[quorumNumber], OperatorSetsEnabled()); } _deregisterOperator({operator: msg.sender, quorumNumbers: quorumNumbers}); } @@ -306,10 +311,8 @@ contract RegistryCoordinator is _checkAllocationManager(); // Decode registration data from bytes - ( - string memory socket, - IBLSApkRegistry.PubkeyRegistrationParams memory params - ) = abi.decode(data, (string, IBLSApkRegistry.PubkeyRegistrationParams)); + (string memory socket, IBLSApkRegistry.PubkeyRegistrationParams memory params) = + abi.decode(data, (string, IBLSApkRegistry.PubkeyRegistrationParams)); // Get operator ID from BLS registry bytes32 operatorId = _getOrCreateOperatorId(operator, params); @@ -350,10 +353,9 @@ contract RegistryCoordinator is * @dev stakes are queried from the Eigenlayer core DelegationManager contract * @param operators a list of operator addresses to update */ - function updateOperators(address[] memory operators) - external - onlyWhenNotPaused(PAUSED_UPDATE_OPERATOR) - { + function updateOperators( + address[] memory operators + ) external onlyWhenNotPaused(PAUSED_UPDATE_OPERATOR) { for (uint256 i = 0; i < operators.length; i++) { address operator = operators[i]; OperatorInfo memory operatorInfo = _operatorInfo[operator]; @@ -389,10 +391,7 @@ contract RegistryCoordinator is // - there should be no duplicates in `quorumNumbers` // - there should be one list of operators per quorum BitmapUtils.orderedBytesArrayToBitmap(quorumNumbers, quorumCount); - require( - operatorsPerQuorum.length == quorumNumbers.length, - InputLengthMismatch() - ); + require(operatorsPerQuorum.length == quorumNumbers.length, InputLengthMismatch()); // For each quorum, update ALL registered operators for (uint256 i = 0; i < quorumNumbers.length; ++i) { @@ -420,14 +419,10 @@ contract RegistryCoordinator is uint192 currentBitmap = _currentOperatorBitmap(operatorId); // Check that the operator is registered require( - BitmapUtils.isSet(currentBitmap, quorumNumber), - NotRegisteredForQuorum() + BitmapUtils.isSet(currentBitmap, quorumNumber), NotRegisteredForQuorum() ); // Prevent duplicate operators - require( - operator > prevOperatorAddress, - NotSorted() - ); + require(operator > prevOperatorAddress, NotSorted()); } // Update the operator @@ -445,11 +440,10 @@ contract RegistryCoordinator is * @notice Updates the socket of the msg.sender given they are a registered operator * @param socket is the new socket of the operator */ - function updateSocket(string memory socket) external { - require( - _operatorInfo[msg.sender].status == OperatorStatus.REGISTERED, - NotRegistered() - ); + function updateSocket( + string memory socket + ) external { + require(_operatorInfo[msg.sender].status == OperatorStatus.REGISTERED, NotRegistered()); emit OperatorSocketUpdate(_operatorInfo[msg.sender].operatorId, socket); } @@ -513,7 +507,13 @@ contract RegistryCoordinator is uint32 lookAheadPeriod ) external virtual onlyOwner { require(isUsingOperatorSets(), OperatorSetsNotEnabled()); - _createQuorum(operatorSetParams, minimumStake, strategyParams, StakeType.TOTAL_SLASHABLE, lookAheadPeriod); + _createQuorum( + operatorSetParams, + minimumStake, + strategyParams, + StakeType.TOTAL_SLASHABLE, + lookAheadPeriod + ); } /** @@ -536,7 +536,9 @@ contract RegistryCoordinator is * @param _churnApprover the new churn approver * @dev only callable by the owner */ - function setChurnApprover(address _churnApprover) external onlyOwner { + function setChurnApprover( + address _churnApprover + ) external onlyOwner { _setChurnApprover(_churnApprover); } @@ -545,7 +547,9 @@ contract RegistryCoordinator is * @param _ejector the new ejector * @dev only callable by the owner */ - function setEjector(address _ejector) external onlyOwner { + function setEjector( + address _ejector + ) external onlyOwner { _setEjector(_ejector); } @@ -555,7 +559,9 @@ contract RegistryCoordinator is * @param _ejectionCooldown the new ejection cooldown in seconds * @dev only callable by the owner */ - function setEjectionCooldown(uint256 _ejectionCooldown) external onlyOwner { + function setEjectionCooldown( + uint256 _ejectionCooldown + ) external onlyOwner { ejectionCooldown = _ejectionCooldown; } @@ -591,13 +597,8 @@ contract RegistryCoordinator is uint192 quorumsToAdd = uint192(BitmapUtils.orderedBytesArrayToBitmap(quorumNumbers, quorumCount)); uint192 currentBitmap = _currentOperatorBitmap(operatorId); - require( - !quorumsToAdd.isEmpty(), BitmapEmpty() - ); - require( - quorumsToAdd.noBitsInCommon(currentBitmap), - AlreadyRegisteredForQuorums() - ); + require(!quorumsToAdd.isEmpty(), BitmapEmpty()); + require(quorumsToAdd.noBitsInCommon(currentBitmap), AlreadyRegisteredForQuorums()); uint192 newBitmap = uint192(currentBitmap.plus(quorumsToAdd)); // Check that the operator can reregister if ejected @@ -622,7 +623,6 @@ contract RegistryCoordinator is serviceManager.registerOperatorToAVS(operator, operatorSignature); emit OperatorRegistered(operator, operatorId); - } // Register the operator with the BLSApkRegistry, StakeRegistry, and IndexRegistry @@ -654,13 +654,8 @@ contract RegistryCoordinator is uint192 quorumsToAdd = uint192(BitmapUtils.orderedBytesArrayToBitmap(quorumNumbers, quorumCount)); uint192 currentBitmap = _currentOperatorBitmap(operatorId); - require( - !quorumsToAdd.isEmpty(), BitmapEmpty() - ); - require( - quorumsToAdd.noBitsInCommon(currentBitmap), - AlreadyRegisteredForQuorums() - ); + require(!quorumsToAdd.isEmpty(), BitmapEmpty()); + require(quorumsToAdd.noBitsInCommon(currentBitmap), AlreadyRegisteredForQuorums()); uint192 newBitmap = uint192(currentBitmap.plus(quorumsToAdd)); // Check that the operator can reregister if ejected @@ -709,11 +704,10 @@ contract RegistryCoordinator is * @param quorumNumber The quorum number to check * @dev Reverts if the quorum does not exist */ - function _checkQuorumExists(uint8 quorumNumber) internal view { - require( - quorumNumber < quorumCount, - QuorumDoesNotExist() - ); + function _checkQuorumExists( + uint8 quorumNumber + ) internal view { + require(quorumNumber < quorumCount, QuorumDoesNotExist()); } /** @@ -765,14 +759,8 @@ contract RegistryCoordinator is ) internal view { address operatorToKick = kickParams.operator; bytes32 idToKick = _operatorInfo[operatorToKick].operatorId; - require( - newOperator != operatorToKick, - CannotChurnSelf() - ); - require( - kickParams.quorumNumber == quorumNumber, - QuorumOperatorCountMismatch() - ); + require(newOperator != operatorToKick, CannotChurnSelf()); + require(kickParams.quorumNumber == quorumNumber, QuorumOperatorCountMismatch()); // Get the target operator's stake and check that it is below the kick thresholds uint96 operatorToKickStake = stakeRegistry.getCurrentStake(idToKick, quorumNumber); @@ -795,10 +783,7 @@ contract RegistryCoordinator is // Fetch the operator's info and ensure they are registered OperatorInfo storage operatorInfo = _operatorInfo[operator]; bytes32 operatorId = operatorInfo.operatorId; - require( - operatorInfo.status == OperatorStatus.REGISTERED, - NotRegistered() - ); + require(operatorInfo.status == OperatorStatus.REGISTERED, NotRegistered()); /** * Get bitmap of quorums to deregister from and operator's current bitmap. Validate that: @@ -810,14 +795,8 @@ contract RegistryCoordinator is uint192 quorumsToRemove = uint192(BitmapUtils.orderedBytesArrayToBitmap(quorumNumbers, quorumCount)); uint192 currentBitmap = _currentOperatorBitmap(operatorId); - require( - !quorumsToRemove.isEmpty(), - BitmapCannotBeZero() - ); - require( - quorumsToRemove.isSubsetOf(currentBitmap), - NotRegisteredForQuorum() - ); + require(!quorumsToRemove.isEmpty(), BitmapCannotBeZero()); + require(quorumsToRemove.isSubsetOf(currentBitmap), NotRegisteredForQuorum()); uint192 newBitmap = uint192(currentBitmap.minus(quorumsToRemove)); // Update operator's bitmap and status @@ -893,14 +872,8 @@ contract RegistryCoordinator is SignatureWithSaltAndExpiry memory churnApproverSignature ) internal { // make sure the salt hasn't been used already - require( - !isChurnApproverSaltUsed[churnApproverSignature.salt], - ChurnApproverSaltUsed() - ); - require( - churnApproverSignature.expiry >= block.timestamp, - SignatureExpired() - ); + require(!isChurnApproverSaltUsed[churnApproverSignature.salt], ChurnApproverSaltUsed()); + require(churnApproverSignature.expiry >= block.timestamp, SignatureExpired()); // set salt used to true isChurnApproverSaltUsed[churnApproverSignature.salt] = true; @@ -936,10 +909,7 @@ contract RegistryCoordinator is ) internal { // Increment the total quorum count. Fails if we're already at the max uint8 prevQuorumCount = quorumCount; - require( - prevQuorumCount < MAX_QUORUM_COUNT, - MaxQuorumsReached() - ); + require(prevQuorumCount < MAX_QUORUM_COUNT, MaxQuorumsReached()); quorumCount = prevQuorumCount + 1; // The previous count is the new quorum's number @@ -951,7 +921,8 @@ contract RegistryCoordinator is /// Update the AllocationManager if operatorSetQuorum if (isOperatorSetAVS && !isM2Quorum[quorumNumber]) { // Create array of CreateSetParams for the new quorum - IAllocationManagerTypes.CreateSetParams[] memory createSetParams = new IAllocationManagerTypes.CreateSetParams[](1); + IAllocationManagerTypes.CreateSetParams[] memory createSetParams = + new IAllocationManagerTypes.CreateSetParams[](1); // Extract strategies from strategyParams IStrategy[] memory strategies = new IStrategy[](strategyParams.length); @@ -973,7 +944,9 @@ contract RegistryCoordinator is if (stakeType == StakeType.TOTAL_DELEGATED) { stakeRegistry.initializeDelegatedStakeQuorum(quorumNumber, minimumStake, strategyParams); } else if (stakeType == StakeType.TOTAL_SLASHABLE) { - stakeRegistry.initializeSlashableStakeQuorum(quorumNumber, minimumStake, lookAheadPeriod, strategyParams); + stakeRegistry.initializeSlashableStakeQuorum( + quorumNumber, minimumStake, lookAheadPeriod, strategyParams + ); } indexRegistry.initializeQuorum(quorumNumber); @@ -990,7 +963,9 @@ contract RegistryCoordinator is /// @notice Get the most recent bitmap for the operator, returning an empty bitmap if /// the operator is not registered. - function _currentOperatorBitmap(bytes32 operatorId) internal view returns (uint192) { + function _currentOperatorBitmap( + bytes32 operatorId + ) internal view returns (uint192) { return QuorumBitmapHistoryLib.currentOperatorBitmap(_operatorBitmapHistory, operatorId); } @@ -1003,7 +978,9 @@ contract RegistryCoordinator is uint32 blockNumber, bytes32 operatorId ) internal view returns (uint32 index) { - return QuorumBitmapHistoryLib.getQuorumBitmapIndexAtBlockNumber(_operatorBitmapHistory,blockNumber, operatorId); + return QuorumBitmapHistoryLib.getQuorumBitmapIndexAtBlockNumber( + _operatorBitmapHistory, blockNumber, operatorId + ); } function _setOperatorSetParams( @@ -1014,12 +991,16 @@ contract RegistryCoordinator is emit OperatorSetParamsUpdated(quorumNumber, operatorSetParams); } - function _setChurnApprover(address newChurnApprover) internal { + function _setChurnApprover( + address newChurnApprover + ) internal { emit ChurnApproverUpdated(churnApprover, newChurnApprover); churnApprover = newChurnApprover; } - function _setEjector(address newEjector) internal { + function _setEjector( + address newEjector + ) internal { emit EjectorUpdated(ejector, newEjector); ejector = newEjector; } @@ -1031,35 +1012,37 @@ contract RegistryCoordinator is */ /// @notice Returns the operator set params for the given `quorumNumber` - function getOperatorSetParams(uint8 quorumNumber) - external - view - returns (OperatorSetParam memory) - { + function getOperatorSetParams( + uint8 quorumNumber + ) external view returns (OperatorSetParam memory) { return _quorumParams[quorumNumber]; } /// @notice Returns the operator struct for the given `operator` - function getOperator(address operator) external view returns (OperatorInfo memory) { + function getOperator( + address operator + ) external view returns (OperatorInfo memory) { return _operatorInfo[operator]; } /// @notice Returns the operatorId for the given `operator` - function getOperatorId(address operator) external view returns (bytes32) { + function getOperatorId( + address operator + ) external view returns (bytes32) { return _operatorInfo[operator].operatorId; } /// @notice Returns the operator address for the given `operatorId` - function getOperatorFromId(bytes32 operatorId) external view returns (address) { + function getOperatorFromId( + bytes32 operatorId + ) external view returns (address) { return blsApkRegistry.getOperatorFromPubkeyHash(operatorId); } /// @notice Returns the status for the given `operator` - function getOperatorStatus(address operator) - external - view - returns (IRegistryCoordinator.OperatorStatus) - { + function getOperatorStatus( + address operator + ) external view returns (IRegistryCoordinator.OperatorStatus) { return _operatorInfo[operator].status; } @@ -1072,7 +1055,9 @@ contract RegistryCoordinator is uint32 blockNumber, bytes32[] memory operatorIds ) external view returns (uint32[] memory) { - return QuorumBitmapHistoryLib.getQuorumBitmapIndicesAtBlockNumber(_operatorBitmapHistory, blockNumber, operatorIds); + return QuorumBitmapHistoryLib.getQuorumBitmapIndicesAtBlockNumber( + _operatorBitmapHistory, blockNumber, operatorIds + ); } /** @@ -1086,7 +1071,9 @@ contract RegistryCoordinator is uint32 blockNumber, uint256 index ) external view returns (uint192) { - return QuorumBitmapHistoryLib.getQuorumBitmapAtBlockNumberByIndex(_operatorBitmapHistory, operatorId, blockNumber, index); + return QuorumBitmapHistoryLib.getQuorumBitmapAtBlockNumberByIndex( + _operatorBitmapHistory, operatorId, blockNumber, index + ); } /// @notice Returns the `index`th entry in the operator with `operatorId`'s bitmap history @@ -1098,12 +1085,16 @@ contract RegistryCoordinator is } /// @notice Returns the current quorum bitmap for the given `operatorId` or 0 if the operator is not registered for any quorum - function getCurrentQuorumBitmap(bytes32 operatorId) external view returns (uint192) { + function getCurrentQuorumBitmap( + bytes32 operatorId + ) external view returns (uint192) { return _currentOperatorBitmap(operatorId); } /// @notice Returns the length of the quorum bitmap history for the given `operatorId` - function getQuorumBitmapHistoryLength(bytes32 operatorId) external view returns (uint256) { + function getQuorumBitmapHistoryLength( + bytes32 operatorId + ) external view returns (uint256) { return _operatorBitmapHistory[operatorId].length; } @@ -1145,11 +1136,9 @@ contract RegistryCoordinator is * @notice Returns the message hash that an operator must sign to register their BLS public key. * @param operator is the address of the operator registering their BLS public key */ - function pubkeyRegistrationMessageHash(address operator) - public - view - returns (BN254.G1Point memory) - { + function pubkeyRegistrationMessageHash( + address operator + ) public view returns (BN254.G1Point memory) { return BN254.hashToG1( _hashTypedDataV4(keccak256(abi.encode(PUBKEY_REGISTRATION_TYPEHASH, operator))) ); diff --git a/src/RegistryCoordinatorStorage.sol b/src/RegistryCoordinatorStorage.sol index 296da275..00a422ba 100644 --- a/src/RegistryCoordinatorStorage.sol +++ b/src/RegistryCoordinatorStorage.sol @@ -6,24 +6,31 @@ import {IStakeRegistry} from "./interfaces/IStakeRegistry.sol"; import {IIndexRegistry} from "./interfaces/IIndexRegistry.sol"; import {IServiceManager} from "./interfaces/IServiceManager.sol"; import {IAVSDirectory} from "eigenlayer-contracts/src/contracts/interfaces/IAVSDirectory.sol"; -import {IAllocationManager, OperatorSet, IAllocationManagerTypes} from "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; +import { + IAllocationManager, + OperatorSet, + IAllocationManagerTypes +} from "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; import {IRegistryCoordinator} from "./interfaces/IRegistryCoordinator.sol"; abstract contract RegistryCoordinatorStorage is IRegistryCoordinator { - - /******************************************************************************* - CONSTANTS AND IMMUTABLES - *******************************************************************************/ + /** + * + * CONSTANTS AND IMMUTABLES + * + */ /// @notice The EIP-712 typehash for the `DelegationApproval` struct used by the contract - bytes32 public constant OPERATOR_CHURN_APPROVAL_TYPEHASH = - keccak256("OperatorChurnApproval(address registeringOperator,bytes32 registeringOperatorId,OperatorKickParam[] operatorKickParams,bytes32 salt,uint256 expiry)OperatorKickParam(uint8 quorumNumber,address operator)"); + bytes32 public constant OPERATOR_CHURN_APPROVAL_TYPEHASH = keccak256( + "OperatorChurnApproval(address registeringOperator,bytes32 registeringOperatorId,OperatorKickParam[] operatorKickParams,bytes32 salt,uint256 expiry)OperatorKickParam(uint8 quorumNumber,address operator)" + ); /// @notice The EIP-712 typehash used for registering BLS public keys - bytes32 public constant PUBKEY_REGISTRATION_TYPEHASH = keccak256("BN254PubkeyRegistration(address operator)"); + bytes32 public constant PUBKEY_REGISTRATION_TYPEHASH = + keccak256("BN254PubkeyRegistration(address operator)"); /// @notice The maximum value of a quorum bitmap uint256 internal constant MAX_QUORUM_BITMAP = type(uint192).max; /// @notice The basis point denominator - uint16 internal constant BIPS_DENOMINATOR = 10000; + uint16 internal constant BIPS_DENOMINATOR = 10_000; /// @notice Index for flag that pauses operator registration uint8 internal constant PAUSED_REGISTER_OPERATOR = 0; /// @notice Index for flag that pauses operator deregistration @@ -46,9 +53,11 @@ abstract contract RegistryCoordinatorStorage is IRegistryCoordinator { /// @notice the AllocationManager that tracks OperatorSets and Slashing in EigenLayer IAllocationManager public immutable allocationManager; - /******************************************************************************* - STATE - *******************************************************************************/ + /** + * + * STATE + * + */ /// @notice the current number of quorums supported by the registry coordinator uint8 public quorumCount; diff --git a/src/ServiceManagerBase.sol b/src/ServiceManagerBase.sol index 72074630..a7be2742 100644 --- a/src/ServiceManagerBase.sol +++ b/src/ServiceManagerBase.sol @@ -7,7 +7,8 @@ import {IAVSDirectory} from "eigenlayer-contracts/src/contracts/interfaces/IAVSD import {IStrategy} from "eigenlayer-contracts/src/contracts/interfaces/IStrategy.sol"; import {IRewardsCoordinator} from "eigenlayer-contracts/src/contracts/interfaces/IRewardsCoordinator.sol"; -import {IPermissionController} from "eigenlayer-contracts/src/contracts/interfaces/IPermissionController.sol"; +import {IPermissionController} from + "eigenlayer-contracts/src/contracts/interfaces/IPermissionController.sol"; import {ServiceManagerBaseStorage} from "./ServiceManagerBaseStorage.sol"; import {IServiceManager} from "./interfaces/IServiceManager.sol"; @@ -67,39 +68,32 @@ abstract contract ServiceManagerBase is ServiceManagerBaseStorage { } /// @inheritdoc IServiceManager - function addPendingAdmin(address admin) external onlyOwner { - _permissionController.addPendingAdmin({ - account: address(this), - admin: admin - }); + function addPendingAdmin( + address admin + ) external onlyOwner { + _permissionController.addPendingAdmin({account: address(this), admin: admin}); } /// @inheritdoc IServiceManager - function removePendingAdmin(address pendingAdmin) external onlyOwner { - _permissionController.removePendingAdmin({ - account: address(this), - admin: pendingAdmin - }); + function removePendingAdmin( + address pendingAdmin + ) external onlyOwner { + _permissionController.removePendingAdmin({account: address(this), admin: pendingAdmin}); } /// @inheritdoc IServiceManager - function removeAdmin(address admin) external onlyOwner { - _permissionController.removeAdmin({ - account: address(this), - admin: admin - }); + function removeAdmin( + address admin + ) external onlyOwner { + _permissionController.removeAdmin({account: address(this), admin: admin}); } /// @inheritdoc IServiceManager - function setAppointee( - address appointee, - address target, - bytes4 selector - ) external onlyOwner { + function setAppointee(address appointee, address target, bytes4 selector) external onlyOwner { _permissionController.setAppointee({ - account: address(this), - appointee: appointee, - target: target, + account: address(this), + appointee: appointee, + target: target, selector: selector }); } @@ -123,7 +117,9 @@ abstract contract ServiceManagerBase is ServiceManagerBaseStorage { * @param _metadataURI is the metadata URI for the AVS * @dev only callable by the owner */ - function updateAVSMetadataURI(string memory _metadataURI) public virtual onlyOwner { + function updateAVSMetadataURI( + string memory _metadataURI + ) public virtual onlyOwner { _avsDirectory.updateAVSMetadataURI(_metadataURI); } @@ -173,7 +169,9 @@ abstract contract ServiceManagerBase is ServiceManagerBaseStorage { * @notice Forwards a call to EigenLayer's AVSDirectory contract to confirm operator deregistration from the AVS * @param operator The address of the operator to deregister. */ - function deregisterOperatorFromAVS(address operator) public virtual onlyRegistryCoordinator { + function deregisterOperatorFromAVS( + address operator + ) public virtual onlyRegistryCoordinator { _avsDirectory.deregisterOperatorFromAVS(operator); } @@ -182,11 +180,15 @@ abstract contract ServiceManagerBase is ServiceManagerBaseStorage { * @param newRewardsInitiator The new rewards initiator address * @dev only callable by the owner */ - function setRewardsInitiator(address newRewardsInitiator) external onlyOwner { + function setRewardsInitiator( + address newRewardsInitiator + ) external onlyOwner { _setRewardsInitiator(newRewardsInitiator); } - function _setRewardsInitiator(address newRewardsInitiator) internal { + function _setRewardsInitiator( + address newRewardsInitiator + ) internal { emit RewardsInitiatorUpdated(rewardsInitiator, newRewardsInitiator); rewardsInitiator = newRewardsInitiator; } @@ -197,7 +199,7 @@ abstract contract ServiceManagerBase is ServiceManagerBaseStorage { * @dev No guarantee is made on uniqueness of each element in the returned array. * The off-chain service should do that validation separately */ - function getRestakeableStrategies() external virtual view returns (address[] memory) { + function getRestakeableStrategies() external view virtual returns (address[] memory) { uint256 quorumCount = _registryCoordinator.quorumCount(); if (quorumCount == 0) { @@ -229,12 +231,9 @@ abstract contract ServiceManagerBase is ServiceManagerBaseStorage { * @dev No guarantee is made on whether the operator has shares for a strategy in a quorum or uniqueness * of each element in the returned array. The off-chain service should do that validation separately */ - function getOperatorRestakedStrategies(address operator) - external - virtual - view - returns (address[] memory) - { + function getOperatorRestakedStrategies( + address operator + ) external view virtual returns (address[] memory) { bytes32 operatorId = _registryCoordinator.getOperatorId(operator); uint192 operatorBitmap = _registryCoordinator.getCurrentQuorumBitmap(operatorId); diff --git a/src/ServiceManagerBaseStorage.sol b/src/ServiceManagerBaseStorage.sol index 6a4ef819..a94212ef 100644 --- a/src/ServiceManagerBaseStorage.sol +++ b/src/ServiceManagerBaseStorage.sol @@ -8,9 +8,12 @@ import {IRegistryCoordinator} from "./interfaces/IRegistryCoordinator.sol"; import {IStakeRegistry} from "./interfaces/IStakeRegistry.sol"; import {IAVSDirectory} from "eigenlayer-contracts/src/contracts/interfaces/IAVSDirectory.sol"; -import {IRewardsCoordinator} from "eigenlayer-contracts/src/contracts/interfaces/IRewardsCoordinator.sol"; -import {IAllocationManager} from "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; -import {IPermissionController} from "eigenlayer-contracts/src/contracts/interfaces/IPermissionController.sol"; +import {IRewardsCoordinator} from + "eigenlayer-contracts/src/contracts/interfaces/IRewardsCoordinator.sol"; +import {IAllocationManager} from + "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; +import {IPermissionController} from + "eigenlayer-contracts/src/contracts/interfaces/IPermissionController.sol"; /** * @title Storage variables for the `ServiceManagerBase` contract. diff --git a/src/ServiceManagerRouter.sol b/src/ServiceManagerRouter.sol index 05a56780..2589ea74 100644 --- a/src/ServiceManagerRouter.sol +++ b/src/ServiceManagerRouter.sol @@ -9,19 +9,19 @@ import {IServiceManagerUI} from "./interfaces/IServiceManagerUI.sol"; * errors to be handled gracefully. * @author Layr Labs, Inc. */ - contract ServiceManagerRouter { - - address public constant FAILED_CALL_ADDRESS = address(0x000000000000000000000000000000000000dEaD); + address public constant FAILED_CALL_ADDRESS = + address(0x000000000000000000000000000000000000dEaD); /** * @notice Returns the list of strategies that the AVS supports for restaking * @param serviceManager Address of AVS's ServiceManager contract */ - function getRestakeableStrategies(address serviceManager) external view returns (address[] memory) { - bytes memory data = abi.encodeWithSelector( - IServiceManagerUI.getRestakeableStrategies.selector - ); + function getRestakeableStrategies( + address serviceManager + ) external view returns (address[] memory) { + bytes memory data = + abi.encodeWithSelector(IServiceManagerUI.getRestakeableStrategies.selector); return _makeCall(serviceManager, data); } @@ -30,10 +30,12 @@ contract ServiceManagerRouter { * @param serviceManager Address of AVS's ServiceManager contract * @param operator Address of the operator to get restaked strategies for */ - function getOperatorRestakedStrategies(address serviceManager, address operator) external view returns (address[] memory) { + function getOperatorRestakedStrategies( + address serviceManager, + address operator + ) external view returns (address[] memory) { bytes memory data = abi.encodeWithSelector( - IServiceManagerUI.getOperatorRestakedStrategies.selector, - operator + IServiceManagerUI.getOperatorRestakedStrategies.selector, operator ); return _makeCall(serviceManager, data); } @@ -43,7 +45,10 @@ contract ServiceManagerRouter { * @dev Handles calls to contracts that don't implement the given function and to EOAs by * returning a failed call address */ - function _makeCall(address serviceManager, bytes memory data) internal view returns (address[] memory) { + function _makeCall( + address serviceManager, + bytes memory data + ) internal view returns (address[] memory) { (bool success, bytes memory strategiesBytes) = serviceManager.staticcall(data); if (success && strategiesBytes.length > 0) { return abi.decode(strategiesBytes, (address[])); diff --git a/src/StakeRegistry.sol b/src/StakeRegistry.sol index 359da941..d93763c3 100644 --- a/src/StakeRegistry.sol +++ b/src/StakeRegistry.sol @@ -1,10 +1,12 @@ // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.27; -import {IDelegationManager} from "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; -import {IAVSDirectory } from "eigenlayer-contracts/src/contracts/interfaces/IAVSDirectory.sol"; +import {IDelegationManager} from + "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; +import {IAVSDirectory} from "eigenlayer-contracts/src/contracts/interfaces/IAVSDirectory.sol"; import {OperatorSet} from "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; -import {IAllocationManager} from "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; +import {IAllocationManager} from + "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; import {IServiceManager} from "./interfaces/IServiceManager.sol"; import {StakeRegistryStorage, IStrategy} from "./StakeRegistryStorage.sol"; @@ -24,7 +26,6 @@ import {BitmapUtils} from "./libraries/BitmapUtils.sol"; * @author Layr Labs, Inc. */ contract StakeRegistry is StakeRegistryStorage { - using BitmapUtils for *; modifier onlyRegistryCoordinator() { @@ -37,7 +38,9 @@ contract StakeRegistry is StakeRegistryStorage { _; } - modifier quorumExists(uint8 quorumNumber) { + modifier quorumExists( + uint8 quorumNumber + ) { _checkQuorumExists(quorumNumber); _; } @@ -48,11 +51,21 @@ contract StakeRegistry is StakeRegistryStorage { IAVSDirectory _avsDirectory, IAllocationManager _allocationManager, IServiceManager _serviceManager - ) StakeRegistryStorage(_registryCoordinator, _delegationManager, _avsDirectory, _allocationManager, _serviceManager) {} + ) + StakeRegistryStorage( + _registryCoordinator, + _delegationManager, + _avsDirectory, + _allocationManager, + _serviceManager + ) + {} - /******************************************************************************* - EXTERNAL FUNCTIONS - REGISTRY COORDINATOR - *******************************************************************************/ + /** + * + * EXTERNAL FUNCTIONS - REGISTRY COORDINATOR + * + */ /** * @notice Registers the `operator` with `operatorId` for the specified `quorumNumbers`. @@ -72,17 +85,16 @@ contract StakeRegistry is StakeRegistryStorage { bytes32 operatorId, bytes calldata quorumNumbers ) public virtual onlyRegistryCoordinator returns (uint96[] memory, uint96[] memory) { - uint96[] memory currentStakes = new uint96[](quorumNumbers.length); uint96[] memory totalStakes = new uint96[](quorumNumbers.length); for (uint256 i = 0; i < quorumNumbers.length; i++) { - uint8 quorumNumber = uint8(quorumNumbers[i]); _checkQuorumExists(quorumNumber); // Retrieve the operator's current weighted stake for the quorum, reverting if they have not met // the minimum. - (uint96 currentStake, bool hasMinimumStake) = _weightOfOperatorForQuorum(quorumNumber, operator); + (uint96 currentStake, bool hasMinimumStake) = + _weightOfOperatorForQuorum(quorumNumber, operator); require(hasMinimumStake, BelowMinimumStakeRequirement()); // Update the operator's stake @@ -166,7 +178,8 @@ contract StakeRegistry is StakeRegistryStorage { // Fetch the operator's current stake, applying weighting parameters and checking // against the minimum stake requirements for the quorum. - (uint96 stakeWeight, bool hasMinimumStake) = _weightOfOperatorForQuorum(quorumNumber, operator); + (uint96 stakeWeight, bool hasMinimumStake) = + _weightOfOperatorForQuorum(quorumNumber, operator); // If the operator no longer meets the minimum stake, set their stake to zero and mark them for removal /// also handle setting the operator's stake to 0 and remove them from the quorum if (!hasMinimumStake) { @@ -200,14 +213,15 @@ contract StakeRegistry is StakeRegistryStorage { _setMinimumStakeForQuorum(quorumNumber, minimumStake); _setStakeType(quorumNumber, StakeType.TOTAL_DELEGATED); - _totalStakeHistory[quorumNumber].push(StakeUpdate({ - updateBlockNumber: uint32(block.number), - nextUpdateBlockNumber: 0, - stake: 0 - })); + _totalStakeHistory[quorumNumber].push( + StakeUpdate({ + updateBlockNumber: uint32(block.number), + nextUpdateBlockNumber: 0, + stake: 0 + }) + ); } - /// @notice Initialize a new quorum and push its first history update function initializeSlashableStakeQuorum( uint8 quorumNumber, @@ -221,11 +235,13 @@ contract StakeRegistry is StakeRegistryStorage { _setStakeType(quorumNumber, StakeType.TOTAL_SLASHABLE); _setLookAheadPeriod(quorumNumber, lookAheadPeriod); - _totalStakeHistory[quorumNumber].push(StakeUpdate({ - updateBlockNumber: uint32(block.number), - nextUpdateBlockNumber: 0, - stake: 0 - })); + _totalStakeHistory[quorumNumber].push( + StakeUpdate({ + updateBlockNumber: uint32(block.number), + nextUpdateBlockNumber: 0, + stake: 0 + }) + ); } function setMinimumStakeForQuorum( @@ -261,7 +277,7 @@ contract StakeRegistry is StakeRegistryStorage { uint256 numStratsToAdd = _strategyParams.length; - if (isOperatorSetQuorum(quorumNumber)){ + if (isOperatorSetQuorum(quorumNumber)) { IStrategy[] memory strategiesToAdd = new IStrategy[](numStratsToAdd); for (uint256 i = 0; i < numStratsToAdd; i++) { strategiesToAdd[i] = _strategyParams[i].strategy; @@ -291,20 +307,23 @@ contract StakeRegistry is StakeRegistryStorage { IStrategy[] memory _strategiesToRemove = new IStrategy[](toRemoveLength); for (uint256 i = 0; i < toRemoveLength; i++) { - _strategiesToRemove[i]=_strategyParams[indicesToRemove[i]].strategy; - emit StrategyRemovedFromQuorum(quorumNumber, _strategyParams[indicesToRemove[i]].strategy); - emit StrategyMultiplierUpdated(quorumNumber, _strategyParams[indicesToRemove[i]].strategy, 0); - - + _strategiesToRemove[i] = _strategyParams[indicesToRemove[i]].strategy; + emit StrategyRemovedFromQuorum( + quorumNumber, _strategyParams[indicesToRemove[i]].strategy + ); + emit StrategyMultiplierUpdated( + quorumNumber, _strategyParams[indicesToRemove[i]].strategy, 0 + ); // Replace index to remove with the last item in the list, then pop the last item _strategyParams[indicesToRemove[i]] = _strategyParams[_strategyParams.length - 1]; _strategyParams.pop(); - _strategiesPerQuorum[indicesToRemove[i]] = _strategiesPerQuorum[_strategiesPerQuorum.length - 1]; + _strategiesPerQuorum[indicesToRemove[i]] = + _strategiesPerQuorum[_strategiesPerQuorum.length - 1]; _strategiesPerQuorum.pop(); } - if (isOperatorSetQuorum(quorumNumber)){ + if (isOperatorSetQuorum(quorumNumber)) { allocationManager.removeStrategiesFromOperatorSet({ avs: address(serviceManager), operatorSetId: quorumNumber, @@ -333,14 +352,17 @@ contract StakeRegistry is StakeRegistryStorage { for (uint256 i = 0; i < numStrats; i++) { // Change the strategy's associated multiplier _strategyParams[strategyIndices[i]].multiplier = newMultipliers[i]; - emit StrategyMultiplierUpdated(quorumNumber, _strategyParams[strategyIndices[i]].strategy, newMultipliers[i]); + emit StrategyMultiplierUpdated( + quorumNumber, _strategyParams[strategyIndices[i]].strategy, newMultipliers[i] + ); } } - /******************************************************************************* - INTERNAL FUNCTIONS - *******************************************************************************/ - + /** + * + * INTERNAL FUNCTIONS + * + */ function _getStakeUpdateIndexForOperatorAtBlockNumber( bytes32 operatorId, uint8 quorumNumber, @@ -350,7 +372,10 @@ contract StakeRegistry is StakeRegistryStorage { // Iterate backwards through operatorStakeHistory until we find an update that preceeds blockNumber for (uint256 i = length; i > 0; i--) { - if (operatorStakeHistory[operatorId][quorumNumber][i - 1].updateBlockNumber <= blockNumber) { + if ( + operatorStakeHistory[operatorId][quorumNumber][i - 1].updateBlockNumber + <= blockNumber + ) { return uint32(i - 1); } } @@ -375,20 +400,22 @@ contract StakeRegistry is StakeRegistryStorage { uint8 quorumNumber, uint96 newStake ) internal returns (int256) { - uint96 prevStake; uint256 historyLength = operatorStakeHistory[operatorId][quorumNumber].length; if (historyLength == 0) { // No prior stake history - push our first entry - operatorStakeHistory[operatorId][quorumNumber].push(StakeUpdate({ - updateBlockNumber: uint32(block.number), - nextUpdateBlockNumber: 0, - stake: newStake - })); + operatorStakeHistory[operatorId][quorumNumber].push( + StakeUpdate({ + updateBlockNumber: uint32(block.number), + nextUpdateBlockNumber: 0, + stake: newStake + }) + ); } else { // We have prior stake history - fetch our last-recorded stake - StakeUpdate storage lastUpdate = operatorStakeHistory[operatorId][quorumNumber][historyLength-1]; + StakeUpdate storage lastUpdate = + operatorStakeHistory[operatorId][quorumNumber][historyLength - 1]; prevStake = lastUpdate.stake; // Short-circuit in case there's no change in stake @@ -404,22 +431,27 @@ contract StakeRegistry is StakeRegistryStorage { lastUpdate.stake = newStake; } else { lastUpdate.nextUpdateBlockNumber = uint32(block.number); - operatorStakeHistory[operatorId][quorumNumber].push(StakeUpdate({ - updateBlockNumber: uint32(block.number), - nextUpdateBlockNumber: 0, - stake: newStake - })); + operatorStakeHistory[operatorId][quorumNumber].push( + StakeUpdate({ + updateBlockNumber: uint32(block.number), + nextUpdateBlockNumber: 0, + stake: newStake + }) + ); } } // Log update and return stake delta emit OperatorStakeUpdate(operatorId, quorumNumber, newStake); - return _calculateDelta({ prev: prevStake, cur: newStake }); + return _calculateDelta({prev: prevStake, cur: newStake}); } /// @notice Applies a delta to the total stake recorded for `quorumNumber` /// @return Returns the new total stake for the quorum - function _recordTotalStakeUpdate(uint8 quorumNumber, int256 stakeDelta) internal returns (uint96) { + function _recordTotalStakeUpdate( + uint8 quorumNumber, + int256 stakeDelta + ) internal returns (uint96) { // Get our last-recorded stake update uint256 historyLength = _totalStakeHistory[quorumNumber].length; StakeUpdate storage lastStakeUpdate = _totalStakeHistory[quorumNumber][historyLength - 1]; @@ -440,11 +472,13 @@ contract StakeRegistry is StakeRegistryStorage { lastStakeUpdate.stake = newStake; } else { lastStakeUpdate.nextUpdateBlockNumber = uint32(block.number); - _totalStakeHistory[quorumNumber].push(StakeUpdate({ - updateBlockNumber: uint32(block.number), - nextUpdateBlockNumber: 0, - stake: newStake - })); + _totalStakeHistory[quorumNumber].push( + StakeUpdate({ + updateBlockNumber: uint32(block.number), + nextUpdateBlockNumber: 0, + stake: newStake + }) + ); } return newStake; @@ -480,9 +514,7 @@ contract StakeRegistry is StakeRegistryStorage { strategiesPerQuorum[quorumNumber].push(_strategyParams[i].strategy); emit StrategyAddedToQuorum(quorumNumber, _strategyParams[i].strategy); emit StrategyMultiplierUpdated( - quorumNumber, - _strategyParams[i].strategy, - _strategyParams[i].multiplier + quorumNumber, _strategyParams[i].strategy, _strategyParams[i].multiplier ); } } @@ -513,16 +545,21 @@ contract StakeRegistry is StakeRegistryStorage { */ require(blockNumber >= stakeUpdate.updateBlockNumber, InvalidBlockNumber()); require( - stakeUpdate.nextUpdateBlockNumber == 0 || blockNumber < stakeUpdate.nextUpdateBlockNumber, + stakeUpdate.nextUpdateBlockNumber == 0 + || blockNumber < stakeUpdate.nextUpdateBlockNumber, InvalidBlockNumber() ); } /// Returns total Slashable stake for an operator per strategy that can have the weights applied based on strategy multipliers - function _getSlashableStakePerStrategy(uint8 quorumNumber, address operator) internal view returns (uint256[] memory) { + function _getSlashableStakePerStrategy( + uint8 quorumNumber, + address operator + ) internal view returns (uint256[] memory) { address[] memory operators = new address[](1); operators[0] = operator; - uint32 beforeTimestamp = uint32(block.number + slashableStakeLookAheadPerQuorum[quorumNumber]); + uint32 beforeTimestamp = + uint32(block.number + slashableStakeLookAheadPerQuorum[quorumNumber]); uint256[][] memory slashableShares = allocationManager.getMinimumSlashableStake( OperatorSet(address(serviceManager), quorumNumber), @@ -540,30 +577,38 @@ contract StakeRegistry is StakeRegistryStorage { * @return `uint96` The weighted sum of the operator's shares across each strategy considered by the quorum * @return `bool` True if the operator meets the quorum's minimum stake */ - function _weightOfOperatorForQuorum(uint8 quorumNumber, address operator) internal virtual view returns (uint96, bool) { + function _weightOfOperatorForQuorum( + uint8 quorumNumber, + address operator + ) internal view virtual returns (uint96, bool) { uint96 weight; uint256 stratsLength = strategyParamsLength(quorumNumber); StrategyParams memory strategyAndMultiplier; uint256[] memory strategyShares; - if (stakeTypePerQuorum[quorumNumber]== StakeType.TOTAL_SLASHABLE) { + if (stakeTypePerQuorum[quorumNumber] == StakeType.TOTAL_SLASHABLE) { strategyShares = _getSlashableStakePerStrategy(quorumNumber, operator); for (uint256 i = 0; i < stratsLength; i++) { strategyAndMultiplier = strategyParams[quorumNumber][i]; if (strategyShares[i] > 0) { - weight += uint96(strategyShares[i] * strategyAndMultiplier.multiplier / WEIGHTING_DIVISOR); + weight += uint96( + strategyShares[i] * strategyAndMultiplier.multiplier / WEIGHTING_DIVISOR + ); } } } else { /// M2 Concept of delegated stake - strategyShares = delegation.getOperatorShares(operator, strategiesPerQuorum[quorumNumber]); + strategyShares = + delegation.getOperatorShares(operator, strategiesPerQuorum[quorumNumber]); for (uint256 i = 0; i < stratsLength; i++) { // accessing i^th StrategyParams struct for the quorumNumber strategyAndMultiplier = strategyParams[quorumNumber][i]; // add the weight from the shares for this strategy to the total weight if (strategyShares[i] > 0) { - weight += uint96(strategyShares[i] * strategyAndMultiplier.multiplier / WEIGHTING_DIVISOR); + weight += uint96( + strategyShares[i] * strategyAndMultiplier.multiplier / WEIGHTING_DIVISOR + ); } } } @@ -574,13 +619,17 @@ contract StakeRegistry is StakeRegistryStorage { } /// @notice Returns `true` if the quorum has been initialized - function _quorumExists(uint8 quorumNumber) internal view returns (bool) { + function _quorumExists( + uint8 quorumNumber + ) internal view returns (bool) { return _totalStakeHistory[quorumNumber].length != 0; } - /******************************************************************************* - VIEW FUNCTIONS - *******************************************************************************/ + /** + * + * VIEW FUNCTIONS + * + */ /** * @notice Returns whether a quorum is an operator set quorum based on its stake type @@ -589,7 +638,9 @@ contract StakeRegistry is StakeRegistryStorage { * @param quorumNumber The quorum number to check * @return True if the quorum is an operator set quorum */ - function isOperatorSetQuorum(uint8 quorumNumber) public view returns (bool) { + function isOperatorSetQuorum( + uint8 quorumNumber + ) public view returns (bool) { bool isM2 = IRegistryCoordinator(registryCoordinator).isM2Quorum(quorumNumber); bool isOperatorSet = IRegistryCoordinator(registryCoordinator).isOperatorSetAVS(); return isOperatorSet && !isM2; @@ -602,13 +653,15 @@ contract StakeRegistry is StakeRegistryStorage { function weightOfOperatorForQuorum( uint8 quorumNumber, address operator - ) public virtual view quorumExists(quorumNumber) returns (uint96) { - (uint96 stake, ) = _weightOfOperatorForQuorum(quorumNumber, operator); + ) public view virtual quorumExists(quorumNumber) returns (uint96) { + (uint96 stake,) = _weightOfOperatorForQuorum(quorumNumber, operator); return stake; } /// @notice Returns the length of the dynamic array stored in `strategyParams[quorumNumber]`. - function strategyParamsLength(uint8 quorumNumber) public view returns (uint256) { + function strategyParamsLength( + uint8 quorumNumber + ) public view returns (uint256) { return strategyParams[quorumNumber].length; } @@ -616,14 +669,15 @@ contract StakeRegistry is StakeRegistryStorage { function strategyParamsByIndex( uint8 quorumNumber, uint256 index - ) public view returns (StrategyParams memory) - { + ) public view returns (StrategyParams memory) { return strategyParams[quorumNumber][index]; } - /******************************************************************************* - VIEW FUNCTIONS - Operator Stake History - *******************************************************************************/ + /** + * + * VIEW FUNCTIONS - Operator Stake History + * + */ /** * @notice Returns the length of an operator's stake history for the given quorum @@ -651,7 +705,10 @@ contract StakeRegistry is StakeRegistryStorage { * @notice Returns the most recent stake weight for the `operatorId` for quorum `quorumNumber` * @dev Function returns weight of **0** in the event that the operator has no stake history */ - function getCurrentStake(bytes32 operatorId, uint8 quorumNumber) external view returns (uint96) { + function getCurrentStake( + bytes32 operatorId, + uint8 quorumNumber + ) external view returns (uint96) { StakeUpdate memory operatorStakeUpdate = getLatestStakeUpdate(operatorId, quorumNumber); return operatorStakeUpdate.stake; } @@ -695,10 +752,9 @@ contract StakeRegistry is StakeRegistryStorage { uint8 quorumNumber, uint32 blockNumber ) external view returns (uint96) { - return - operatorStakeHistory[operatorId][quorumNumber][ - _getStakeUpdateIndexForOperatorAtBlockNumber(operatorId, quorumNumber, blockNumber) - ].stake; + return operatorStakeHistory[operatorId][quorumNumber][_getStakeUpdateIndexForOperatorAtBlockNumber( + operatorId, quorumNumber, blockNumber + )].stake; } /// @notice Returns the indices of the operator stakes for the provided `quorumNumber` at the given `blockNumber` @@ -726,19 +782,24 @@ contract StakeRegistry is StakeRegistryStorage { bytes32 operatorId, uint256 index ) external view returns (uint96) { - StakeUpdate memory operatorStakeUpdate = operatorStakeHistory[operatorId][quorumNumber][index]; + StakeUpdate memory operatorStakeUpdate = + operatorStakeHistory[operatorId][quorumNumber][index]; _validateStakeUpdateAtBlockNumber(operatorStakeUpdate, blockNumber); return operatorStakeUpdate.stake; } - /******************************************************************************* - VIEW FUNCTIONS - Total Stake History - *******************************************************************************/ + /** + * + * VIEW FUNCTIONS - Total Stake History + * + */ /** * @notice Returns the length of the total stake history for the given quorum */ - function getTotalStakeHistoryLength(uint8 quorumNumber) external view returns (uint256) { + function getTotalStakeHistoryLength( + uint8 quorumNumber + ) external view returns (uint256) { return _totalStakeHistory[quorumNumber].length; } @@ -746,7 +807,9 @@ contract StakeRegistry is StakeRegistryStorage { * @notice Returns the stake weight from the latest entry in `_totalStakeHistory` for quorum `quorumNumber`. * @dev Will revert if `_totalStakeHistory[quorumNumber]` is empty. */ - function getCurrentTotalStake(uint8 quorumNumber) external view returns (uint96) { + function getCurrentTotalStake( + uint8 quorumNumber + ) external view returns (uint96) { return _totalStakeHistory[quorumNumber][_totalStakeHistory[quorumNumber].length - 1].stake; } @@ -800,7 +863,10 @@ contract StakeRegistry is StakeRegistryStorage { ); uint256 length = _totalStakeHistory[quorumNumber].length; for (uint256 j = 0; j < length; j++) { - if (_totalStakeHistory[quorumNumber][length - j - 1].updateBlockNumber <= blockNumber) { + if ( + _totalStakeHistory[quorumNumber][length - j - 1].updateBlockNumber + <= blockNumber + ) { indices[i] = uint32(length - j - 1); break; } @@ -830,16 +896,20 @@ contract StakeRegistry is StakeRegistryStorage { emit LookAheadPeriodChanged(oldLookAheadDays, _lookAheadBlocks); } - function _checkRegistryCoordinator() internal view { require(msg.sender == address(registryCoordinator), OnlyRegistryCoordinator()); } function _checkRegistryCoordinatorOwner() internal view { - require(msg.sender == IRegistryCoordinator(registryCoordinator).owner(), OnlyRegistryCoordinatorOwner()); + require( + msg.sender == IRegistryCoordinator(registryCoordinator).owner(), + OnlyRegistryCoordinatorOwner() + ); } - function _checkQuorumExists(uint8 quorumNumber) internal view { + function _checkQuorumExists( + uint8 quorumNumber + ) internal view { require(_quorumExists(quorumNumber), QuorumDoesNotExist()); } } diff --git a/src/StakeRegistryStorage.sol b/src/StakeRegistryStorage.sol index 26f72873..c0d7b933 100644 --- a/src/StakeRegistryStorage.sol +++ b/src/StakeRegistryStorage.sol @@ -1,14 +1,19 @@ // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.27; -import {IDelegationManager} from "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; +import {IDelegationManager} from + "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; import {IAVSDirectory} from "eigenlayer-contracts/src/contracts/interfaces/IAVSDirectory.sol"; -import {IAllocationManager} from "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; +import {IAllocationManager} from + "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; import {IServiceManager} from "./interfaces/IServiceManager.sol"; -import {IStrategyManager, IStrategy} from "eigenlayer-contracts/src/contracts/interfaces/IStrategyManager.sol"; +import { + IStrategyManager, + IStrategy +} from "eigenlayer-contracts/src/contracts/interfaces/IStrategyManager.sol"; import {IRegistryCoordinator} from "./interfaces/IRegistryCoordinator.sol"; -import {IStakeRegistry, StakeType} from "./interfaces/IStakeRegistry.sol"; +import {IStakeRegistry, StakeType} from "./interfaces/IStakeRegistry.sol"; /** * @title Storage variables for the `StakeRegistry` contract. @@ -16,13 +21,12 @@ import {IStakeRegistry, StakeType} from "./interfaces/IStakeRegistry.sol"; * @notice This storage contract is separate from the logic to simplify the upgrade process. */ abstract contract StakeRegistryStorage is IStakeRegistry { - /// @notice Constant used as a divisor in calculating weights. uint256 public constant WEIGHTING_DIVISOR = 1e18; /// @notice Maximum length of dynamic arrays in the `strategyParams` mapping. uint8 public constant MAX_WEIGHING_FUNCTION_LENGTH = 32; /// @notice Constant used as a divisor in dealing with BIPS amounts. - uint256 internal constant MAX_BIPS = 10000; + uint256 internal constant MAX_BIPS = 10_000; /// @notice The address of the Delegation contract for EigenLayer. IDelegationManager public immutable delegation; diff --git a/src/interfaces/IBLSApkRegistry.sol b/src/interfaces/IBLSApkRegistry.sol index a93d4d53..0b1370b5 100644 --- a/src/interfaces/IBLSApkRegistry.sol +++ b/src/interfaces/IBLSApkRegistry.sol @@ -58,21 +58,15 @@ interface IBLSApkRegistry is IRegistry, IBLSApkRegistryErrors { // EVENTS /// @notice Emitted when `operator` registers with the public keys `pubkeyG1` and `pubkeyG2`. - event NewPubkeyRegistration(address indexed operator, BN254.G1Point pubkeyG1, BN254.G2Point pubkeyG2); + event NewPubkeyRegistration( + address indexed operator, BN254.G1Point pubkeyG1, BN254.G2Point pubkeyG2 + ); // @notice Emitted when a new operator pubkey is registered for a set of quorums - event OperatorAddedToQuorums( - address operator, - bytes32 operatorId, - bytes quorumNumbers - ); + event OperatorAddedToQuorums(address operator, bytes32 operatorId, bytes quorumNumbers); // @notice Emitted when an operator pubkey is removed from a set of quorums - event OperatorRemovedFromQuorums( - address operator, - bytes32 operatorId, - bytes quorumNumbers - ); + event OperatorRemovedFromQuorums(address operator, bytes32 operatorId, bytes quorumNumbers); /** * @notice Registers the `operator`'s pubkey for the specified `quorumNumbers`. @@ -105,20 +99,26 @@ interface IBLSApkRegistry is IRegistry, IBLSApkRegistryErrors { * @notice Initializes a new quorum by pushing its first apk update * @param quorumNumber The number of the new quorum */ - function initializeQuorum(uint8 quorumNumber) external; + function initializeQuorum( + uint8 quorumNumber + ) external; /** * @notice mapping from operator address to pubkey hash. * Returns *zero* if the `operator` has never registered, and otherwise returns the hash of the public key of the operator. */ - function operatorToPubkeyHash(address operator) external view returns (bytes32); + function operatorToPubkeyHash( + address operator + ) external view returns (bytes32); /** * @notice mapping from pubkey hash to operator address. * Returns *zero* if no operator has ever registered the public key corresponding to `pubkeyHash`, * and otherwise returns the (unique) registered operator who owns the BLS public key that is the preimage of `pubkeyHash`. */ - function pubkeyHashToOperator(bytes32 pubkeyHash) external view returns (address); + function pubkeyHashToOperator( + bytes32 pubkeyHash + ) external view returns (address); /** * @notice Called by the RegistryCoordinator register an operator as the owner of a BLS public key. @@ -136,19 +136,31 @@ interface IBLSApkRegistry is IRegistry, IBLSApkRegistryErrors { * @notice Returns the pubkey and pubkey hash of an operator * @dev Reverts if the operator has not registered a valid pubkey */ - function getRegisteredPubkey(address operator) external view returns (BN254.G1Point memory, bytes32); + function getRegisteredPubkey( + address operator + ) external view returns (BN254.G1Point memory, bytes32); /// @notice Returns the current APK for the provided `quorumNumber ` - function getApk(uint8 quorumNumber) external view returns (BN254.G1Point memory); + function getApk( + uint8 quorumNumber + ) external view returns (BN254.G1Point memory); /// @notice Returns the index of the quorumApk index at `blockNumber` for the provided `quorumNumber` - function getApkIndicesAtBlockNumber(bytes calldata quorumNumbers, uint256 blockNumber) external view returns(uint32[] memory); + function getApkIndicesAtBlockNumber( + bytes calldata quorumNumbers, + uint256 blockNumber + ) external view returns (uint32[] memory); /// @notice Returns the `ApkUpdate` struct at `index` in the list of APK updates for the `quorumNumber` - function getApkUpdateAtIndex(uint8 quorumNumber, uint256 index) external view returns (ApkUpdate memory); + function getApkUpdateAtIndex( + uint8 quorumNumber, + uint256 index + ) external view returns (ApkUpdate memory); /// @notice Returns the operator address for the given `pubkeyHash` - function getOperatorFromPubkeyHash(bytes32 pubkeyHash) external view returns (address); + function getOperatorFromPubkeyHash( + bytes32 pubkeyHash + ) external view returns (address); /** * @notice get 24 byte hash of the apk of `quorumNumber` at `blockNumber` using the provided `index`; @@ -157,9 +169,15 @@ interface IBLSApkRegistry is IRegistry, IBLSApkRegistryErrors { * @param blockNumber is the number of the block for which the latest ApkHash will be retrieved * @param index is the index of the apkUpdate being retrieved from the list of quorum apkUpdates in storage */ - function getApkHashAtBlockNumberAndIndex(uint8 quorumNumber, uint32 blockNumber, uint256 index) external view returns (bytes24); + function getApkHashAtBlockNumberAndIndex( + uint8 quorumNumber, + uint32 blockNumber, + uint256 index + ) external view returns (bytes24); /// @notice returns the ID used to identify the `operator` within this AVS. /// @dev Returns zero in the event that the `operator` has never registered for the AVS - function getOperatorId(address operator) external view returns (bytes32); + function getOperatorId( + address operator + ) external view returns (bytes32); } diff --git a/src/interfaces/IBLSSignatureChecker.sol b/src/interfaces/IBLSSignatureChecker.sol index 4ab73f4c..6a7df2c5 100644 --- a/src/interfaces/IBLSSignatureChecker.sol +++ b/src/interfaces/IBLSSignatureChecker.sol @@ -54,7 +54,6 @@ interface IBLSSignatureChecker is IBLSSignatureCheckerErrors { * @notice this data structure is used for recording the details on the total stake of the registered * operators and those operators who are part of the quorum for a particular taskNumber */ - struct QuorumStakeTotals { // total stake of the operators in each quorum uint96[] signedStakeForQuorum; @@ -95,11 +94,5 @@ interface IBLSSignatureChecker is IBLSSignatureCheckerErrors { bytes calldata quorumNumbers, uint32 referenceBlockNumber, NonSignerStakesAndSignature memory nonSignerStakesAndSignature - ) - external - view - returns ( - QuorumStakeTotals memory, - bytes32 - ); + ) external view returns (QuorumStakeTotals memory, bytes32); } diff --git a/src/interfaces/IECDSAStakeRegistryEventsAndErrors.sol b/src/interfaces/IECDSAStakeRegistryEventsAndErrors.sol index b43743d3..96bea50a 100644 --- a/src/interfaces/IECDSAStakeRegistryEventsAndErrors.sol +++ b/src/interfaces/IECDSAStakeRegistryEventsAndErrors.sol @@ -36,20 +36,13 @@ interface ECDSAStakeRegistryEventsAndErrors { /// @notice Emitted when the weight required to be an operator changes /// @param oldMinimumWeight The previous weight /// @param newMinimumWeight The updated weight - event UpdateMinimumWeight( - uint256 oldMinimumWeight, - uint256 newMinimumWeight - ); + event UpdateMinimumWeight(uint256 oldMinimumWeight, uint256 newMinimumWeight); /// @notice Emitted when the system updates an operator's weight /// @param _operator The address of the operator updated /// @param oldWeight The operator's weight before the update /// @param newWeight The operator's weight after the update - event OperatorWeightUpdated( - address indexed _operator, - uint256 oldWeight, - uint256 newWeight - ); + event OperatorWeightUpdated(address indexed _operator, uint256 oldWeight, uint256 newWeight); /// @notice Emitted when the system updates the total weight /// @param oldTotalWeight The total weight before the update @@ -71,6 +64,7 @@ interface ECDSAStakeRegistryEventsAndErrors { address oldSigningKey ); /// @notice Indicates when the lengths of the signers array and signatures array do not match. + error LengthMismatch(); /// @notice Indicates encountering an invalid length for the signers or signatures array. diff --git a/src/interfaces/IEjectionManager.sol b/src/interfaces/IEjectionManager.sol index 478e21d8..a491a973 100644 --- a/src/interfaces/IEjectionManager.sol +++ b/src/interfaces/IEjectionManager.sol @@ -13,7 +13,6 @@ interface IEjectionManagerErrors { * @author Layr Labs, Inc. */ interface IEjectionManager is IEjectionManagerErrors { - /// @notice A quorum's ratelimit parameters struct QuorumEjectionParams { uint32 rateLimitWindow; // Time delta to track ejection over @@ -29,24 +28,31 @@ interface IEjectionManager is IEjectionManagerErrors { ///@notice Emitted when the ejector address is set event EjectorUpdated(address ejector, bool status); ///@notice Emitted when the ratelimit parameters for a quorum are set - event QuorumEjectionParamsSet(uint8 quorumNumber, uint32 rateLimitWindow, uint16 ejectableStakePercent); + event QuorumEjectionParamsSet( + uint8 quorumNumber, uint32 rateLimitWindow, uint16 ejectableStakePercent + ); ///@notice Emitted when an operator is ejected event OperatorEjected(bytes32 operatorId, uint8 quorumNumber); ///@notice Emitted when operators are ejected for a quroum event QuorumEjection(uint32 ejectedOperators, bool ratelimitHit); - /** + /** * @notice Ejects operators from the AVSs registryCoordinator under a ratelimit * @param _operatorIds The ids of the operators to eject for each quorum */ - function ejectOperators(bytes32[][] memory _operatorIds) external; + function ejectOperators( + bytes32[][] memory _operatorIds + ) external; /** * @notice Sets the ratelimit parameters for a quorum * @param _quorumNumber The quorum number to set the ratelimit parameters for * @param _quorumEjectionParams The quorum ratelimit parameters to set for the given quorum */ - function setQuorumEjectionParams(uint8 _quorumNumber, QuorumEjectionParams memory _quorumEjectionParams) external; + function setQuorumEjectionParams( + uint8 _quorumNumber, + QuorumEjectionParams memory _quorumEjectionParams + ) external; /** * @notice Sets the address permissioned to eject operators under a ratelimit @@ -58,5 +64,7 @@ interface IEjectionManager is IEjectionManagerErrors { * @notice Returns the amount of stake that can be ejected for a quorum at the current block.timestamp * @param _quorumNumber The quorum number to view ejectable stake for */ - function amountEjectableForQuorum(uint8 _quorumNumber) external view returns (uint256); + function amountEjectableForQuorum( + uint8 _quorumNumber + ) external view returns (uint256); } diff --git a/src/interfaces/IIndexRegistry.sol b/src/interfaces/IIndexRegistry.sol index df1e0e73..08b963ad 100644 --- a/src/interfaces/IIndexRegistry.sol +++ b/src/interfaces/IIndexRegistry.sol @@ -20,7 +20,9 @@ interface IIndexRegistry is IRegistry, IIndexRegistryErrors { // EVENTS // emitted when an operator's index in the ordered operator list for the quorum with number `quorumNumber` is updated - event QuorumIndexUpdate(bytes32 indexed operatorId, uint8 quorumNumber, uint32 newOperatorIndex); + event QuorumIndexUpdate( + bytes32 indexed operatorId, uint8 quorumNumber, uint32 newOperatorIndex + ); // DATA STRUCTURES @@ -53,7 +55,10 @@ interface IIndexRegistry is IRegistry, IIndexRegistryErrors { * 3) `quorumNumbers` is ordered in ascending order * 4) the operator is not already registered */ - function registerOperator(bytes32 operatorId, bytes calldata quorumNumbers) external returns(uint32[] memory); + function registerOperator( + bytes32 operatorId, + bytes calldata quorumNumbers + ) external returns (uint32[] memory); /** * @notice Deregisters the operator with the specified `operatorId` for the quorums specified by `quorumNumbers`. @@ -73,7 +78,9 @@ interface IIndexRegistry is IRegistry, IIndexRegistryErrors { * @notice Initialize a quorum by pushing its first quorum update * @param quorumNumber The number of the new quorum */ - function initializeQuorum(uint8 quorumNumber) external; + function initializeQuorum( + uint8 quorumNumber + ) external; /// @notice Returns the OperatorUpdate entry for the specified `operatorIndex` and `quorumNumber` at the specified `arrayIndex` function getOperatorUpdateAtIndex( @@ -83,17 +90,30 @@ interface IIndexRegistry is IRegistry, IIndexRegistryErrors { ) external view returns (OperatorUpdate memory); /// @notice Returns the QuorumUpdate entry for the specified `quorumNumber` at the specified `quorumIndex` - function getQuorumUpdateAtIndex(uint8 quorumNumber, uint32 quorumIndex) external view returns (QuorumUpdate memory); + function getQuorumUpdateAtIndex( + uint8 quorumNumber, + uint32 quorumIndex + ) external view returns (QuorumUpdate memory); /// @notice Returns the most recent OperatorUpdate entry for the specified quorumNumber and operatorIndex - function getLatestOperatorUpdate(uint8 quorumNumber, uint32 operatorIndex) external view returns (OperatorUpdate memory); + function getLatestOperatorUpdate( + uint8 quorumNumber, + uint32 operatorIndex + ) external view returns (OperatorUpdate memory); /// @notice Returns the most recent QuorumUpdate entry for the specified quorumNumber - function getLatestQuorumUpdate(uint8 quorumNumber) external view returns (QuorumUpdate memory); + function getLatestQuorumUpdate( + uint8 quorumNumber + ) external view returns (QuorumUpdate memory); /// @notice Returns the current number of operators of this service for `quorumNumber`. - function totalOperatorsForQuorum(uint8 quorumNumber) external view returns (uint32); + function totalOperatorsForQuorum( + uint8 quorumNumber + ) external view returns (uint32); /// @notice Returns an ordered list of operators of the services for the given `quorumNumber` at the given `blockNumber` - function getOperatorListAtBlockNumber(uint8 quorumNumber, uint32 blockNumber) external view returns (bytes32[] memory); + function getOperatorListAtBlockNumber( + uint8 quorumNumber, + uint32 blockNumber + ) external view returns (bytes32[] memory); } diff --git a/src/interfaces/IRegistryCoordinator.sol b/src/interfaces/IRegistryCoordinator.sol index 4ce2e917..3a7fcfd7 100644 --- a/src/interfaces/IRegistryCoordinator.sol +++ b/src/interfaces/IRegistryCoordinator.sol @@ -35,7 +35,8 @@ interface IRegistryCoordinatorErrors { * @title Interface for a contract that coordinates between various registries for an AVS. * @author Layr Labs, Inc. */ -interface IRegistryCoordinator is IRegistryCoordinatorErrors{ + +interface IRegistryCoordinator is IRegistryCoordinatorErrors { // EVENTS /// Emits when an operator is registered @@ -54,8 +55,7 @@ interface IRegistryCoordinator is IRegistryCoordinatorErrors{ event QuorumBlockNumberUpdated(uint8 indexed quorumNumber, uint256 blocknumber); // DATA STRUCTURES - enum OperatorStatus - { + enum OperatorStatus { // default is NEVER_REGISTERED NEVER_REGISTERED, REGISTERED, @@ -91,7 +91,7 @@ interface IRegistryCoordinator is IRegistryCoordinatorErrors{ * `kickBIPsOfOperatorStake` is the basis points of a new operator needs to have of an operator they are trying to kick from the quorum, * and `kickBIPsOfTotalStake` is the basis points of the total stake of the quorum that an operator needs to be below to be kicked. */ - struct OperatorSetParam { + struct OperatorSetParam { uint32 maxOperatorCount; uint16 kickBIPsOfOperatorStake; uint16 kickBIPsOfTotalStake; @@ -107,7 +107,9 @@ interface IRegistryCoordinator is IRegistryCoordinatorErrors{ } /// @notice Returns the operator set params for the given `quorumNumber` - function getOperatorSetParams(uint8 quorumNumber) external view returns (OperatorSetParam memory); + function getOperatorSetParams( + uint8 quorumNumber + ) external view returns (OperatorSetParam memory); /// @notice the Stake registry contract that will keep track of operators' stakes function stakeRegistry() external view returns (IStakeRegistry); /// @notice the BLS Aggregate Pubkey Registry contract that will keep track of operators' BLS aggregate pubkeys per quorum @@ -120,46 +122,67 @@ interface IRegistryCoordinator is IRegistryCoordinatorErrors{ * @param operator is the operator to eject * @param quorumNumbers are the quorum numbers to eject the operator from */ - function ejectOperator( - address operator, - bytes calldata quorumNumbers - ) external; + function ejectOperator(address operator, bytes calldata quorumNumbers) external; /// @notice Returns the number of quorums the registry coordinator has created function quorumCount() external view returns (uint8); /// @notice Returns the operator struct for the given `operator` - function getOperator(address operator) external view returns (OperatorInfo memory); + function getOperator( + address operator + ) external view returns (OperatorInfo memory); /// @notice Returns the operatorId for the given `operator` - function getOperatorId(address operator) external view returns (bytes32); + function getOperatorId( + address operator + ) external view returns (bytes32); /// @notice Returns the operator address for the given `operatorId` - function getOperatorFromId(bytes32 operatorId) external view returns (address operator); + function getOperatorFromId( + bytes32 operatorId + ) external view returns (address operator); /// @notice Returns the status for the given `operator` - function getOperatorStatus(address operator) external view returns (IRegistryCoordinator.OperatorStatus); + function getOperatorStatus( + address operator + ) external view returns (IRegistryCoordinator.OperatorStatus); /// @notice Returns the indices of the quorumBitmaps for the provided `operatorIds` at the given `blockNumber` - function getQuorumBitmapIndicesAtBlockNumber(uint32 blockNumber, bytes32[] memory operatorIds) external view returns (uint32[] memory); + function getQuorumBitmapIndicesAtBlockNumber( + uint32 blockNumber, + bytes32[] memory operatorIds + ) external view returns (uint32[] memory); /** * @notice Returns the quorum bitmap for the given `operatorId` at the given `blockNumber` via the `index` * @dev reverts if `index` is incorrect */ - function getQuorumBitmapAtBlockNumberByIndex(bytes32 operatorId, uint32 blockNumber, uint256 index) external view returns (uint192); + function getQuorumBitmapAtBlockNumberByIndex( + bytes32 operatorId, + uint32 blockNumber, + uint256 index + ) external view returns (uint192); /// @notice Returns the `index`th entry in the operator with `operatorId`'s bitmap history - function getQuorumBitmapUpdateByIndex(bytes32 operatorId, uint256 index) external view returns (QuorumBitmapUpdate memory); + function getQuorumBitmapUpdateByIndex( + bytes32 operatorId, + uint256 index + ) external view returns (QuorumBitmapUpdate memory); /// @notice Returns the current quorum bitmap for the given `operatorId` - function getCurrentQuorumBitmap(bytes32 operatorId) external view returns (uint192); + function getCurrentQuorumBitmap( + bytes32 operatorId + ) external view returns (uint192); /// @notice Returns the length of the quorum bitmap history for the given `operatorId` - function getQuorumBitmapHistoryLength(bytes32 operatorId) external view returns (uint256); + function getQuorumBitmapHistoryLength( + bytes32 operatorId + ) external view returns (uint256); /// @notice Returns the registry at the desired index - function registries(uint256) external view returns (address); + function registries( + uint256 + ) external view returns (address); /// @notice Returns the number of registries function numRegistries() external view returns (uint256); @@ -167,7 +190,9 @@ interface IRegistryCoordinator is IRegistryCoordinatorErrors{ /// @notice Returns whether a quorum is an M2 quorum /// @param quorumNumber The quorum number to check /// @return True if the quorum is an M2 quorum - function isM2Quorum(uint8 quorumNumber) external view returns (bool); + function isM2Quorum( + uint8 quorumNumber + ) external view returns (bool); /// @notice Returns whether the AVS is an operator set AVS /// @return True if the AVS is an operator set AVS @@ -177,10 +202,14 @@ interface IRegistryCoordinator is IRegistryCoordinatorErrors{ * @notice Returns the message hash that an operator must sign to register their BLS public key. * @param operator is the address of the operator registering their BLS public key */ - function pubkeyRegistrationMessageHash(address operator) external view returns (BN254.G1Point memory); + function pubkeyRegistrationMessageHash( + address operator + ) external view returns (BN254.G1Point memory); /// @notice returns the blocknumber the quorum was last updated all at once for all operators - function quorumUpdateBlockNumber(uint8 quorumNumber) external view returns (uint256); + function quorumUpdateBlockNumber( + uint8 quorumNumber + ) external view returns (uint256); /// @notice The owner of the registry coordinator function owner() external view returns (address); diff --git a/src/interfaces/IServiceManager.sol b/src/interfaces/IServiceManager.sol index 5f3ab220..28d9c2db 100644 --- a/src/interfaces/IServiceManager.sol +++ b/src/interfaces/IServiceManager.sol @@ -1,11 +1,14 @@ // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; -import {IRewardsCoordinator} from "eigenlayer-contracts/src/contracts/interfaces/IRewardsCoordinator.sol"; +import {IRewardsCoordinator} from + "eigenlayer-contracts/src/contracts/interfaces/IRewardsCoordinator.sol"; import {IServiceManagerUI} from "./IServiceManagerUI.sol"; import {ISignatureUtils} from "eigenlayer-contracts/src/contracts/interfaces/ISignatureUtils.sol"; -import {IAllocationManagerTypes} from "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; -import {IAllocationManager} from "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; +import {IAllocationManagerTypes} from + "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; +import {IAllocationManager} from + "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; import {IStrategy} from "eigenlayer-contracts/src/contracts/interfaces/IStrategy.sol"; import {IAVSRegistrar} from "eigenlayer-contracts/src/contracts/interfaces/IAVSRegistrar.sol"; @@ -41,18 +44,24 @@ interface IServiceManager is IServiceManagerUI, IServiceManagerErrors { * @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(IRewardsCoordinator.RewardsSubmission[] calldata rewardsSubmissions) external; + function createAVSRewardsSubmission( + IRewardsCoordinator.RewardsSubmission[] calldata rewardsSubmissions + ) external; - /******************************************************************************* - PERMISSIONCONTROLLER FUNCTIONS - *******************************************************************************/ + /** + * + * PERMISSIONCONTROLLER FUNCTIONS + * + */ /** * @notice Calls `addPendingAdmin` on the `PermissionController` contract * with `account` being the address of this contract. * @param admin The address of the admin to add * @dev Only callable by the owner of the contract */ - function addPendingAdmin(address admin) external; + function addPendingAdmin( + address admin + ) external; /** * @notice Calls `removePendingAdmin` on the `PermissionController` contract @@ -60,7 +69,9 @@ interface IServiceManager is IServiceManagerUI, IServiceManagerErrors { * @param pendingAdmin The address of the pending admin to remove * @dev Only callable by the owner of the contract */ - function removePendingAdmin(address pendingAdmin) external; + function removePendingAdmin( + address pendingAdmin + ) external; /** * @notice Calls `removeAdmin` on the `PermissionController` contract @@ -68,7 +79,9 @@ interface IServiceManager is IServiceManagerUI, IServiceManagerErrors { * @param admin The address of the admin to remove * @dev Only callable by the owner of the contract */ - function removeAdmin(address admin) external; + function removeAdmin( + address admin + ) external; /** * @notice Calls `setAppointee` on the `PermissionController` contract @@ -78,11 +91,7 @@ interface IServiceManager is IServiceManagerUI, IServiceManagerErrors { * @param selector The function selector to set the appointee for * @dev Only callable by the owner of the contract */ - function setAppointee( - address appointee, - address target, - bytes4 selector - ) external; + function setAppointee(address appointee, address target, bytes4 selector) external; /** * @notice Calls `removeAppointee` on the `PermissionController` contract @@ -92,9 +101,5 @@ interface IServiceManager is IServiceManagerUI, IServiceManagerErrors { * @param selector The function selector to remove the appointee for * @dev Only callable by the owner of the contract */ - function removeAppointee( - address appointee, - address target, - bytes4 selector - ) external; + function removeAppointee(address appointee, address target, bytes4 selector) external; } diff --git a/src/interfaces/IServiceManagerUI.sol b/src/interfaces/IServiceManagerUI.sol index 92cdce9c..558dca85 100644 --- a/src/interfaces/IServiceManagerUI.sol +++ b/src/interfaces/IServiceManagerUI.sol @@ -11,17 +11,19 @@ import {ISignatureUtils} from "eigenlayer-contracts/src/contracts/interfaces/ISi interface IServiceManagerUI { /** * Metadata should follow the format outlined by this example. - { - "name": "EigenLabs AVS 1", - "website": "https://www.eigenlayer.xyz/", - "description": "This is my 1st AVS", - "logo": "https://holesky-operator-metadata.s3.amazonaws.com/eigenlayer.png", - "twitter": "https://twitter.com/eigenlayer" - } + * { + * "name": "EigenLabs AVS 1", + * "website": "https://www.eigenlayer.xyz/", + * "description": "This is my 1st AVS", + * "logo": "https://holesky-operator-metadata.s3.amazonaws.com/eigenlayer.png", + * "twitter": "https://twitter.com/eigenlayer" + * } * @notice Updates the metadata URI for the AVS * @param _metadataURI is the metadata URI for the AVS */ - function updateAVSMetadataURI(string memory _metadataURI) external; + function updateAVSMetadataURI( + string memory _metadataURI + ) external; /** * @notice Forwards a call to EigenLayer's AVSDirectory contract to confirm operator registration with the AVS @@ -37,21 +39,25 @@ interface IServiceManagerUI { * @notice Forwards a call to EigenLayer's AVSDirectory contract to confirm operator deregistration from the AVS * @param operator The address of the operator to deregister. */ - function deregisterOperatorFromAVS(address operator) external; + function deregisterOperatorFromAVS( + address operator + ) external; /** * @notice Returns the list of strategies that the operator has potentially restaked on the AVS * @param operator The address of the operator to get restaked strategies for * @dev This function is intended to be called off-chain - * @dev No guarantee is made on whether the operator has shares for a strategy in a quorum or uniqueness + * @dev No guarantee is made on whether the operator has shares for a strategy in a quorum or uniqueness * of each element in the returned array. The off-chain service should do that validation separately */ - function getOperatorRestakedStrategies(address operator) external view returns (address[] memory); + function getOperatorRestakedStrategies( + address operator + ) external view returns (address[] memory); /** * @notice Returns the list of strategies that the AVS supports for restaking * @dev This function is intended to be called off-chain - * @dev No guarantee is made on uniqueness of each element in the returned array. + * @dev No guarantee is made on uniqueness of each element in the returned array. * The off-chain service should do that validation separately */ function getRestakeableStrategies() external view returns (address[] memory); diff --git a/src/interfaces/ISlasher.sol b/src/interfaces/ISlasher.sol index 44222150..b00fd65a 100644 --- a/src/interfaces/ISlasher.sol +++ b/src/interfaces/ISlasher.sol @@ -1,9 +1,9 @@ - // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.27; import {IStrategy} from "eigenlayer-contracts/src/contracts/interfaces/IStrategy.sol"; -import {IAllocationManager} from "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; +import {IAllocationManager} from + "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; interface ISlasherEvents { event SlashingRequested( @@ -53,7 +53,6 @@ interface ISlasherTypes { uint256 requestTimestamp; SlashingStatus status; } - } interface ISlasher is ISlasherEvents, ISlasherTypes, ISlasherErrors {} diff --git a/src/interfaces/ISocketUpdater.sol b/src/interfaces/ISocketUpdater.sol index dc17ecfa..921b1a46 100644 --- a/src/interfaces/ISocketUpdater.sol +++ b/src/interfaces/ISocketUpdater.sol @@ -16,5 +16,7 @@ interface ISocketUpdater { * @notice Updates the socket of the msg.sender given they are a registered operator * @param socket is the new socket of the operator */ - function updateSocket(string memory socket) external; + function updateSocket( + string memory socket + ) external; } diff --git a/src/interfaces/IStakeRegistry.sol b/src/interfaces/IStakeRegistry.sol index 85417ecc..a9d3d5a3 100644 --- a/src/interfaces/IStakeRegistry.sol +++ b/src/interfaces/IStakeRegistry.sol @@ -1,7 +1,8 @@ // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.27; -import {IDelegationManager} from "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; +import {IDelegationManager} from + "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; import {IStrategy} from "eigenlayer-contracts/src/contracts/interfaces/IStrategy.sol"; import {IRegistry} from "./IRegistry.sol"; @@ -67,11 +68,7 @@ interface IStakeRegistry is IRegistry, IStakeRegistryErrors { // EVENTS /// @notice emitted whenever the stake of `operator` is updated - event OperatorStakeUpdate( - bytes32 indexed operatorId, - uint8 quorumNumber, - uint96 stake - ); + event OperatorStakeUpdate(bytes32 indexed operatorId, uint8 quorumNumber, uint96 stake); /// @notice emitted when the look ahead time(in blocks) for checking operator shares is updated event LookAheadPeriodChanged(uint32 oldLookAheadBlocks, uint32 newLookAheadBlocks); @@ -87,7 +84,9 @@ interface IStakeRegistry is IRegistry, IStakeRegistryErrors { /// @notice emitted when `strategy` has removed from the array at `strategyParams[quorumNumber]` event StrategyRemovedFromQuorum(uint8 indexed quorumNumber, IStrategy strategy); /// @notice emitted when `strategy` has its `multiplier` updated in the array at `strategyParams[quorumNumber]` - event StrategyMultiplierUpdated(uint8 indexed quorumNumber, IStrategy strategy, uint256 multiplier); + event StrategyMultiplierUpdated( + uint8 indexed quorumNumber, IStrategy strategy, uint256 multiplier + ); /** * @notice Registers the `operator` with `operatorId` for the specified `quorumNumbers`. @@ -141,10 +140,7 @@ interface IStakeRegistry is IRegistry, IStakeRegistryErrors { ) external; /// @notice Adds new strategies and the associated multipliers to the @param quorumNumber. - function addStrategies( - uint8 quorumNumber, - StrategyParams[] memory strategyParams - ) external; + function addStrategies(uint8 quorumNumber, StrategyParams[] memory strategyParams) external; /** * @notice This function is used for removing strategies and their associated weights from the @@ -174,10 +170,14 @@ interface IStakeRegistry is IRegistry, IStakeRegistryErrors { function delegation() external view returns (IDelegationManager); /// @notice In order to register for a quorum i, an operator must have at least `minimumStakeForQuorum[i]` - function minimumStakeForQuorum(uint8 quorumNumber) external view returns (uint96); + function minimumStakeForQuorum( + uint8 quorumNumber + ) external view returns (uint96); /// @notice Returns the length of the dynamic array stored in `strategyParams[quorumNumber]`. - function strategyParamsLength(uint8 quorumNumber) external view returns (uint256); + function strategyParamsLength( + uint8 quorumNumber + ) external view returns (uint256); /// @notice Returns the strategy and weight multiplier for the `index`'th strategy in the quorum `quorumNumber` function strategyParamsByIndex( @@ -189,32 +189,47 @@ interface IStakeRegistry is IRegistry, IStakeRegistryErrors { * @notice This function computes the total weight of the @param operator in the quorum @param quorumNumber. * @dev reverts in the case that `quorumNumber` is greater than or equal to `quorumCount` */ - function weightOfOperatorForQuorum(uint8 quorumNumber, address operator) external view returns (uint96); + function weightOfOperatorForQuorum( + uint8 quorumNumber, + address operator + ) external view returns (uint96); /** * @notice Returns the entire `operatorIdToStakeHistory[operatorId][quorumNumber]` array. * @param operatorId The id of the operator of interest. * @param quorumNumber The quorum number to get the stake for. */ - function getStakeHistory(bytes32 operatorId, uint8 quorumNumber) external view returns (StakeUpdate[] memory); + function getStakeHistory( + bytes32 operatorId, + uint8 quorumNumber + ) external view returns (StakeUpdate[] memory); - function getTotalStakeHistoryLength(uint8 quorumNumber) external view returns (uint256); + function getTotalStakeHistoryLength( + uint8 quorumNumber + ) external view returns (uint256); /** * @notice Returns the `index`-th entry in the dynamic array of total stake, `totalStakeHistory` for quorum `quorumNumber`. * @param quorumNumber The quorum number to get the stake for. * @param index Array index for lookup, within the dynamic array `totalStakeHistory[quorumNumber]`. */ - function getTotalStakeUpdateAtIndex(uint8 quorumNumber, uint256 index) external view returns (StakeUpdate memory); + function getTotalStakeUpdateAtIndex( + uint8 quorumNumber, + uint256 index + ) external view returns (StakeUpdate memory); /// @notice Returns the indices of the operator stakes for the provided `quorumNumber` at the given `blockNumber` - function getStakeUpdateIndexAtBlockNumber(bytes32 operatorId, uint8 quorumNumber, uint32 blockNumber) - external - view - returns (uint32); + function getStakeUpdateIndexAtBlockNumber( + bytes32 operatorId, + uint8 quorumNumber, + uint32 blockNumber + ) external view returns (uint32); /// @notice Returns the indices of the total stakes for the provided `quorumNumbers` at the given `blockNumber` - function getTotalStakeIndicesAtBlockNumber(uint32 blockNumber, bytes calldata quorumNumbers) external view returns(uint32[] memory) ; + function getTotalStakeIndicesAtBlockNumber( + uint32 blockNumber, + bytes calldata quorumNumbers + ) external view returns (uint32[] memory); /** * @notice Returns the `index`-th entry in the `operatorIdToStakeHistory[operatorId][quorumNumber]` array. @@ -223,16 +238,20 @@ interface IStakeRegistry is IRegistry, IStakeRegistryErrors { * @param index Array index for lookup, within the dynamic array `operatorIdToStakeHistory[operatorId][quorumNumber]`. * @dev Function will revert if `index` is out-of-bounds. */ - function getStakeUpdateAtIndex(uint8 quorumNumber, bytes32 operatorId, uint256 index) - external - view - returns (StakeUpdate memory); + function getStakeUpdateAtIndex( + uint8 quorumNumber, + bytes32 operatorId, + uint256 index + ) external view returns (StakeUpdate memory); /** * @notice Returns the most recent stake weight for the `operatorId` for a certain quorum * @dev Function returns an StakeUpdate struct with **every entry equal to 0** in the event that the operator has no stake history */ - function getLatestStakeUpdate(bytes32 operatorId, uint8 quorumNumber) external view returns (StakeUpdate memory); + function getLatestStakeUpdate( + bytes32 operatorId, + uint8 quorumNumber + ) external view returns (StakeUpdate memory); /** * @notice Returns the stake weight corresponding to `operatorId` for quorum `quorumNumber`, at the @@ -245,10 +264,12 @@ interface IStakeRegistry is IRegistry, IStakeRegistryErrors { * @dev Function will revert if `index` is out-of-bounds. * @dev used the BLSSignatureChecker to get past stakes of signing operators */ - function getStakeAtBlockNumberAndIndex(uint8 quorumNumber, uint32 blockNumber, bytes32 operatorId, uint256 index) - external - view - returns (uint96); + function getStakeAtBlockNumberAndIndex( + uint8 quorumNumber, + uint32 blockNumber, + bytes32 operatorId, + uint256 index + ) external view returns (uint96); /** * @notice Returns the total stake weight for quorum `quorumNumber`, at the `index`-th entry in the @@ -260,25 +281,35 @@ interface IStakeRegistry is IRegistry, IStakeRegistryErrors { * @dev Function will revert if `index` is out-of-bounds. * @dev used the BLSSignatureChecker to get past stakes of signing operators */ - function getTotalStakeAtBlockNumberFromIndex(uint8 quorumNumber, uint32 blockNumber, uint256 index) external view returns (uint96); + function getTotalStakeAtBlockNumberFromIndex( + uint8 quorumNumber, + uint32 blockNumber, + uint256 index + ) external view returns (uint96); /** * @notice Returns the most recent stake weight for the `operatorId` for quorum `quorumNumber` * @dev Function returns weight of **0** in the event that the operator has no stake history */ - function getCurrentStake(bytes32 operatorId, uint8 quorumNumber) external view returns (uint96); + function getCurrentStake( + bytes32 operatorId, + uint8 quorumNumber + ) external view returns (uint96); /// @notice Returns the stake of the operator for the provided `quorumNumber` at the given `blockNumber` - function getStakeAtBlockNumber(bytes32 operatorId, uint8 quorumNumber, uint32 blockNumber) - external - view - returns (uint96); + function getStakeAtBlockNumber( + bytes32 operatorId, + uint8 quorumNumber, + uint32 blockNumber + ) external view returns (uint96); /** * @notice Returns the stake weight from the latest entry in `_totalStakeHistory` for quorum `quorumNumber`. * @dev Will revert if `_totalStakeHistory[quorumNumber]` is empty. */ - function getCurrentTotalStake(uint8 quorumNumber) external view returns (uint96); + function getCurrentTotalStake( + uint8 quorumNumber + ) external view returns (uint96); /** * @notice Called by the registry coordinator to update an operator's stake for one diff --git a/src/libraries/BN254.sol b/src/libraries/BN254.sol index dcda7a31..7a167efc 100644 --- a/src/libraries/BN254.sol +++ b/src/libraries/BN254.sol @@ -30,10 +30,10 @@ pragma solidity ^0.8.27; library BN254 { // modulus for the underlying field F_p of the elliptic curve uint256 internal constant FP_MODULUS = - 21888242871839275222246405745257275088696311157297823662689037894645226208583; + 21_888_242_871_839_275_222_246_405_745_257_275_088_696_311_157_297_823_662_689_037_894_645_226_208_583; // modulus for the underlying field F_r of the elliptic curve uint256 internal constant FR_MODULUS = - 21888242871839275222246405745257275088548364400416034343698204186575808495617; + 21_888_242_871_839_275_222_246_405_745_257_275_088_548_364_400_416_034_343_698_204_186_575_808_495_617; struct G1Point { uint256 X; @@ -63,10 +63,14 @@ library BN254 { // generator of group G2 /// @dev Generator point in F_q2 is of the form: (x0 + ix1, y0 + iy1). - uint256 internal constant G2x1 = 11559732032986387107991004021392285783925812861821192530917403151452391805634; - uint256 internal constant G2x0 = 10857046999023057135944570762232829481370756359578518086990519993285655852781; - uint256 internal constant G2y1 = 4082367875863433681332203403145435568316851327593401208105741076214120093531; - uint256 internal constant G2y0 = 8495653923123431417604973247489272438418190587263600148770280649306958101930; + uint256 internal constant G2x1 = + 11_559_732_032_986_387_107_991_004_021_392_285_783_925_812_861_821_192_530_917_403_151_452_391_805_634; + uint256 internal constant G2x0 = + 10_857_046_999_023_057_135_944_570_762_232_829_481_370_756_359_578_518_086_990_519_993_285_655_852_781; + uint256 internal constant G2y1 = + 4_082_367_875_863_433_681_332_203_403_145_435_568_316_851_327_593_401_208_105_741_076_214_120_093_531; + uint256 internal constant G2y0 = + 8_495_653_923_123_431_417_604_973_247_489_272_438_418_190_587_263_600_148_770_280_649_306_958_101_930; /// @notice returns the G2 generator /// @dev mind the ordering of the 1s and 0s! @@ -79,10 +83,14 @@ library BN254 { // negation of the generator of group G2 /// @dev Generator point in F_q2 is of the form: (x0 + ix1, y0 + iy1). - uint256 internal constant nG2x1 = 11559732032986387107991004021392285783925812861821192530917403151452391805634; - uint256 internal constant nG2x0 = 10857046999023057135944570762232829481370756359578518086990519993285655852781; - uint256 internal constant nG2y1 = 17805874995975841540914202342111839520379459829704422454583296818431106115052; - uint256 internal constant nG2y0 = 13392588948715843804641432497768002650278120570034223513918757245338268106653; + uint256 internal constant nG2x1 = + 11_559_732_032_986_387_107_991_004_021_392_285_783_925_812_861_821_192_530_917_403_151_452_391_805_634; + uint256 internal constant nG2x0 = + 10_857_046_999_023_057_135_944_570_762_232_829_481_370_756_359_578_518_086_990_519_993_285_655_852_781; + uint256 internal constant nG2y1 = + 17_805_874_995_975_841_540_914_202_342_111_839_520_379_459_829_704_422_454_583_296_818_431_106_115_052; + uint256 internal constant nG2y0 = + 13_392_588_948_715_843_804_641_432_497_768_002_650_278_120_570_034_223_513_918_757_245_338_268_106_653; function negGeneratorG2() internal pure returns (G2Point memory) { return G2Point([nG2x1, nG2x0], [nG2y1, nG2y0]); @@ -95,7 +103,9 @@ library BN254 { * @param p Some point in G1. * @return The negation of `p`, i.e. p.plus(p.negate()) should be zero. */ - function negate(G1Point memory p) internal pure returns (G1Point memory) { + function negate( + G1Point memory p + ) internal pure returns (G1Point memory) { // The prime q in the base field F_q for G1 if (p.X == 0 && p.Y == 0) { return G1Point(0, 0); @@ -120,9 +130,7 @@ library BN254 { success := staticcall(sub(gas(), 2000), 6, input, 0x80, r, 0x40) // Use "invalid" to make gas estimation work switch success - case 0 { - invalid() - } + case 0 { invalid() } } require(success, ECAddFailed()); @@ -134,11 +142,14 @@ library BN254 { * @param s the scalar to multiply by * @dev this function is only safe to use if the scalar is 9 bits or less */ - function scalar_mul_tiny(BN254.G1Point memory p, uint16 s) internal view returns (BN254.G1Point memory) { - require(s < 2**9, ScalarTooLarge()); + function scalar_mul_tiny( + BN254.G1Point memory p, + uint16 s + ) internal view returns (BN254.G1Point memory) { + require(s < 2 ** 9, ScalarTooLarge()); // if s is 1 return p - if(s == 1) { + if (s == 1) { return p; } @@ -152,7 +163,7 @@ library BN254 { uint8 i = 0; //loop until we reach the most significant bit - while(s >= m){ + while (s >= m) { unchecked { // if the current bit is 1, add the 2^n*p to the accumulated product if ((s >> i) & 1 == 1) { @@ -187,9 +198,7 @@ library BN254 { success := staticcall(sub(gas(), 2000), 7, input, 0x60, r, 0x40) // Use "invalid" to make gas estimation work switch success - case 0 { - invalid() - } + case 0 { invalid() } } require(success, ECMulFailed()); } @@ -229,9 +238,7 @@ library BN254 { success := staticcall(sub(gas(), 2000), 8, input, mul(12, 0x20), out, 0x20) // Use "invalid" to make gas estimation work switch success - case 0 { - invalid() - } + case 0 { invalid() } } require(success, ECPairingFailed()); @@ -281,7 +288,9 @@ library BN254 { /// @return hashedG1 the keccak256 hash of the G1 Point /// @dev used for BLS signatures - function hashG1Point(BN254.G1Point memory pk) internal pure returns (bytes32 hashedG1) { + function hashG1Point( + BN254.G1Point memory pk + ) internal pure returns (bytes32 hashedG1) { assembly { mstore(0, mload(pk)) mstore(0x20, mload(add(0x20, pk))) @@ -300,7 +309,9 @@ library BN254 { /** * @notice adapted from https://github.com/HarryR/solcrypto/blob/master/contracts/altbn128.sol */ - function hashToG1(bytes32 _x) internal view returns (G1Point memory) { + function hashToG1( + bytes32 _x + ) internal view returns (G1Point memory) { uint256 beta = 0; uint256 y = 0; @@ -310,7 +321,7 @@ library BN254 { (beta, y) = findYFromX(x); // y^2 == beta - if( beta == mulmod(y, y, FP_MODULUS) ) { + if (beta == mulmod(y, y, FP_MODULUS)) { return G1Point(x, y); } @@ -326,21 +337,29 @@ library BN254 { * * Returns: (x^3 + b), y */ - function findYFromX(uint256 x) internal view returns (uint256, uint256) { + function findYFromX( + uint256 x + ) internal view returns (uint256, uint256) { // beta = (x^3 + b) % p uint256 beta = addmod(mulmod(mulmod(x, x, FP_MODULUS), x, FP_MODULUS), 3, FP_MODULUS); // y^2 = x^3 + b // this acts like: y = sqrt(beta) = beta^((p+1) / 4) - uint256 y = expMod(beta, 0xc19139cb84c680a6e14116da060561765e05aa45a1c72a34f082305b61f3f52, FP_MODULUS); + uint256 y = expMod( + beta, 0xc19139cb84c680a6e14116da060561765e05aa45a1c72a34f082305b61f3f52, FP_MODULUS + ); return (beta, y); } - function expMod(uint256 _base, uint256 _exponent, uint256 _modulus) internal view returns (uint256 retval) { + function expMod( + uint256 _base, + uint256 _exponent, + uint256 _modulus + ) internal view returns (uint256 retval) { bool success; uint256[1] memory output; - uint[6] memory input; + uint256[6] memory input; input[0] = 0x20; // baseLen = new(big.Int).SetBytes(getData(input, 0, 32)) input[1] = 0x20; // expLen = new(big.Int).SetBytes(getData(input, 32, 32)) input[2] = 0x20; // modLen = new(big.Int).SetBytes(getData(input, 64, 32)) @@ -351,9 +370,7 @@ library BN254 { success := staticcall(sub(gas(), 2000), 5, input, 0xc0, output, 0x20) // Use "invalid" to make gas estimation work switch success - case 0 { - invalid() - } + case 0 { invalid() } } require(success, ExpModFailed()); return output[0]; diff --git a/src/libraries/BitmapUtils.sol b/src/libraries/BitmapUtils.sol index 3930209a..4e4c9373 100644 --- a/src/libraries/BitmapUtils.sol +++ b/src/libraries/BitmapUtils.sol @@ -29,7 +29,9 @@ library BitmapUtils { * @dev This function will eventually revert in the event that the `orderedBytesArray` is not properly ordered (in ascending order). * @dev This function will also revert if the `orderedBytesArray` input contains any duplicate entries (i.e. duplicate bytes). */ - function orderedBytesArrayToBitmap(bytes memory orderedBytesArray) internal pure returns (uint256) { + function orderedBytesArrayToBitmap( + bytes memory orderedBytesArray + ) internal pure returns (uint256) { // sanity-check on input. a too-long input would fail later on due to having duplicate entry(s) require(orderedBytesArray.length <= MAX_BYTE_ARRAY_LENGTH, BytesArrayLengthTooLong()); @@ -65,7 +67,10 @@ library BitmapUtils { * @param bitUpperBound The exclusive largest bit. Each bit must be strictly less than this value. * @dev Reverts if bitmap contains a bit greater than or equal to `bitUpperBound` */ - function orderedBytesArrayToBitmap(bytes memory orderedBytesArray, uint8 bitUpperBound) internal pure returns (uint256) { + function orderedBytesArrayToBitmap( + bytes memory orderedBytesArray, + uint8 bitUpperBound + ) internal pure returns (uint256) { uint256 bitmap = orderedBytesArrayToBitmap(orderedBytesArray); require((1 << bitUpperBound) > bitmap, BitmapValueTooLarge()); @@ -80,7 +85,9 @@ library BitmapUtils { * @dev This function returns 'true' for the edge case of the `bytesArray` having zero length. * It also returns 'false' early for arrays with length in excess of MAX_BYTE_ARRAY_LENGTH (i.e. so long that they cannot be strictly ordered) */ - function isArrayStrictlyAscendingOrdered(bytes calldata bytesArray) internal pure returns (bool) { + function isArrayStrictlyAscendingOrdered( + bytes calldata bytesArray + ) internal pure returns (bool) { // Return early if the array is too long, or has a length of 0 if (bytesArray.length > MAX_BYTE_ARRAY_LENGTH) { return false; @@ -113,7 +120,9 @@ library BitmapUtils { * @return bytesArray The resulting bitmap array of bytes. * @dev Each byte in the input is processed as indicating a single bit to flip in the bitmap */ - function bitmapToBytesArray(uint256 bitmap) internal pure returns (bytes memory /*bytesArray*/) { + function bitmapToBytesArray( + uint256 bitmap + ) internal pure returns (bytes memory /*bytesArray*/ ) { // initialize an empty uint256 to be used as a bitmask inside the loop uint256 bitMask; // allocate only the needed amount of memory @@ -133,14 +142,18 @@ library BitmapUtils { // if the i-th bit is flipped, then add a byte encoding the value 'i' to the `bytesArray` bytesArray[arrayIndex] = bytes1(uint8(i)); // increment the bytesArray slot since we've assigned one more byte of memory - unchecked{ ++arrayIndex; } + unchecked { + ++arrayIndex; + } } } return bytesArray; } /// @return count number of ones in binary representation of `n` - function countNumOnes(uint256 n) internal pure returns (uint16) { + function countNumOnes( + uint256 n + ) internal pure returns (uint16) { uint16 count = 0; while (n > 0) { n &= (n - 1); // Clear the least significant bit (turn off the rightmost set bit). @@ -167,7 +180,9 @@ library BitmapUtils { /** * @notice Returns true if `bitmap` has no set bits */ - function isEmpty(uint256 bitmap) internal pure returns (bool) { + function isEmpty( + uint256 bitmap + ) internal pure returns (bool) { return bitmap == 0; } diff --git a/src/libraries/LibMergeSort.sol b/src/libraries/LibMergeSort.sol index 11eb91b1..e8d05da2 100644 --- a/src/libraries/LibMergeSort.sol +++ b/src/libraries/LibMergeSort.sol @@ -1,9 +1,10 @@ - // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.27; library LibMergeSort { - function sort(address[] memory array) internal pure returns (address[] memory) { + function sort( + address[] memory array + ) internal pure returns (address[] memory) { if (array.length <= 1) { return array; } @@ -21,7 +22,11 @@ library LibMergeSort { return mergeSortArrays(sort(left), sort(right)); } - function mergeSortArrays(address[] memory left, address[] memory right) internal pure returns (address[] memory) { + + function mergeSortArrays( + address[] memory left, + address[] memory right + ) internal pure returns (address[] memory) { uint256 leftLength = left.length; uint256 rightLength = right.length; address[] memory merged = new address[](leftLength + rightLength); @@ -53,9 +58,10 @@ library LibMergeSort { } // Resize the merged array to remove unused space - assembly { mstore(merged, k) } + assembly { + mstore(merged, k) + } return merged; } - -} \ No newline at end of file +} diff --git a/src/libraries/QuorumBitmapHistoryLib.sol b/src/libraries/QuorumBitmapHistoryLib.sol index 50f6880b..92848aba 100644 --- a/src/libraries/QuorumBitmapHistoryLib.sol +++ b/src/libraries/QuorumBitmapHistoryLib.sol @@ -93,8 +93,7 @@ library QuorumBitmapHistoryLib { * - the next update block number should be either 0 or strictly greater than blockNumber */ require( - blockNumber >= quorumBitmapUpdate.updateBlockNumber, - BitmapUpdateIsAfterBlockNumber() + blockNumber >= quorumBitmapUpdate.updateBlockNumber, BitmapUpdateIsAfterBlockNumber() ); require( quorumBitmapUpdate.nextUpdateBlockNumber == 0 diff --git a/src/slashers/InstantSlasher.sol b/src/slashers/InstantSlasher.sol index 536259ba..5575525a 100644 --- a/src/slashers/InstantSlasher.sol +++ b/src/slashers/InstantSlasher.sol @@ -2,19 +2,21 @@ pragma solidity ^0.8.27; import {IStrategy} from "eigenlayer-contracts/src/contracts/interfaces/IStrategy.sol"; -import {IAllocationManager} from "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; +import {IAllocationManager} from + "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; import {IServiceManager} from "../interfaces/IServiceManager.sol"; import {SlasherBase} from "./base/SlasherBase.sol"; contract InstantSlasher is SlasherBase { - constructor( IAllocationManager _allocationManager, IServiceManager _serviceManager, address _slasher ) SlasherBase(_allocationManager, _serviceManager) {} - function initialize(address _slasher) external initializer { + function initialize( + address _slasher + ) external initializer { __SlasherBase_init(_slasher); } @@ -24,4 +26,4 @@ contract InstantSlasher is SlasherBase { uint256 requestId = nextRequestId++; _fulfillSlashingRequest(requestId, _slashingParams); } -} \ No newline at end of file +} diff --git a/src/slashers/VetoableSlasher.sol b/src/slashers/VetoableSlasher.sol index 37cbb3b9..87112d21 100644 --- a/src/slashers/VetoableSlasher.sol +++ b/src/slashers/VetoableSlasher.sol @@ -2,11 +2,11 @@ pragma solidity ^0.8.27; import {IStrategy} from "eigenlayer-contracts/src/contracts/interfaces/IStrategy.sol"; -import {IAllocationManager} from "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; +import {IAllocationManager} from + "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; import {SlasherBase} from "./base/SlasherBase.sol"; import {IServiceManager} from "../interfaces/IServiceManager.sol"; - contract VetoableSlasher is SlasherBase { uint256 public constant VETO_PERIOD = 3 days; address public vetoCommittee; @@ -24,42 +24,47 @@ contract VetoableSlasher is SlasherBase { address _slasher ) SlasherBase(_allocationManager, _serviceManager) {} - function initialize( - address _vetoCommittee, - address _slasher - ) external virtual initializer { + function initialize(address _vetoCommittee, address _slasher) external virtual initializer { __SlasherBase_init(_slasher); vetoCommittee = _vetoCommittee; } - function queueSlashingRequest(IAllocationManager.SlashingParams memory params) external virtual onlySlasher { + function queueSlashingRequest( + IAllocationManager.SlashingParams memory params + ) external virtual onlySlasher { _queueSlashingRequest(params); } - function cancelSlashingRequest(uint256 requestId) external virtual onlyVetoCommittee { + function cancelSlashingRequest( + uint256 requestId + ) external virtual onlyVetoCommittee { require( block.timestamp < slashingRequests[requestId].requestTimestamp + VETO_PERIOD, VetoPeriodPassed() ); - require(slashingRequests[requestId].status == SlashingStatus.Requested, SlashingRequestNotRequested()); + require( + slashingRequests[requestId].status == SlashingStatus.Requested, + SlashingRequestNotRequested() + ); _cancelSlashingRequest(requestId); } - function fulfillSlashingRequest(uint256 requestId) external virtual onlySlasher { + function fulfillSlashingRequest( + uint256 requestId + ) external virtual onlySlasher { SlashingRequest storage request = slashingRequests[requestId]; require(block.timestamp >= request.requestTimestamp + VETO_PERIOD, VetoPeriodNotPassed()); require(request.status == SlashingStatus.Requested, SlashingRequestIsCancelled()); request.status = SlashingStatus.Completed; - _fulfillSlashingRequest( - requestId, - request.params - ); + _fulfillSlashingRequest(requestId, request.params); } - function _queueSlashingRequest(IAllocationManager.SlashingParams memory params) internal virtual { + function _queueSlashingRequest( + IAllocationManager.SlashingParams memory params + ) internal virtual { uint256 requestId = nextRequestId++; slashingRequests[requestId] = SlashingRequest({ params: params, @@ -67,15 +72,21 @@ contract VetoableSlasher is SlasherBase { status: SlashingStatus.Requested }); - emit SlashingRequested(requestId, params.operator, params.operatorSetId, params.wadsToSlash, params.description); + emit SlashingRequested( + requestId, params.operator, params.operatorSetId, params.wadsToSlash, params.description + ); } - function _cancelSlashingRequest(uint256 requestId) internal virtual { + function _cancelSlashingRequest( + uint256 requestId + ) internal virtual { slashingRequests[requestId].status = SlashingStatus.Cancelled; emit SlashingRequestCancelled(requestId); } - function _checkVetoCommittee(address account) internal view virtual { + function _checkVetoCommittee( + address account + ) internal view virtual { require(account == vetoCommittee, OnlyVetoCommittee()); } } diff --git a/src/slashers/base/SlasherBase.sol b/src/slashers/base/SlasherBase.sol index 30a269f6..370e60b1 100644 --- a/src/slashers/base/SlasherBase.sol +++ b/src/slashers/base/SlasherBase.sol @@ -4,11 +4,13 @@ pragma solidity ^0.8.27; import {Initializable} from "@openzeppelin-upgrades/contracts/proxy/utils/Initializable.sol"; import {IServiceManager} from "../../interfaces/IServiceManager.sol"; import {SlasherStorage} from "./SlasherStorage.sol"; -import {IAllocationManagerTypes, IAllocationManager} from "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; +import { + IAllocationManagerTypes, + IAllocationManager +} from "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; import {IStrategy} from "eigenlayer-contracts/src/contracts/interfaces/IStrategy.sol"; abstract contract SlasherBase is Initializable, SlasherStorage { - modifier onlySlasher() { _checkSlasher(msg.sender); _; @@ -21,7 +23,9 @@ abstract contract SlasherBase is Initializable, SlasherStorage { _disableInitializers(); } - function __SlasherBase_init(address _slasher) internal onlyInitializing { + function __SlasherBase_init( + address _slasher + ) internal onlyInitializing { slasher = _slasher; } @@ -29,14 +33,19 @@ abstract contract SlasherBase is Initializable, SlasherStorage { uint256 _requestId, IAllocationManager.SlashingParams memory _params ) internal virtual { - allocationManager.slashOperator({ - avs: address(serviceManager), - params: _params - }); - emit OperatorSlashed(_requestId, _params.operator, _params.operatorSetId, _params.wadsToSlash, _params.description); + allocationManager.slashOperator({avs: address(serviceManager), params: _params}); + emit OperatorSlashed( + _requestId, + _params.operator, + _params.operatorSetId, + _params.wadsToSlash, + _params.description + ); } - function _checkSlasher(address account) internal view virtual { + function _checkSlasher( + address account + ) internal view virtual { require(account == slasher, OnlySlasher()); } } diff --git a/src/slashers/base/SlasherStorage.sol b/src/slashers/base/SlasherStorage.sol index 3e5e9860..1b8d0b1b 100644 --- a/src/slashers/base/SlasherStorage.sol +++ b/src/slashers/base/SlasherStorage.sol @@ -1,24 +1,28 @@ // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.27; -import {IAllocationManager} from "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; +import {IAllocationManager} from + "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; import {ISlasher} from "../../interfaces/ISlasher.sol"; import {IServiceManager} from "../../interfaces/IServiceManager.sol"; -contract SlasherStorage is ISlasher { - /******************************************************************************* - CONSTANTS AND IMMUTABLES - *******************************************************************************/ +contract SlasherStorage is ISlasher { + /** + * + * CONSTANTS AND IMMUTABLES + * + */ /// @notice the AllocationManager that tracks OperatorSets and Slashing in EigenLayer IAllocationManager public immutable allocationManager; /// @notice the ServiceManager for this AVS, which forwards calls onto EigenLayer's core contracts IServiceManager public immutable serviceManager; - /******************************************************************************* - STATE - *******************************************************************************/ - + /** + * + * STATE + * + */ address public slasher; uint256 public nextRequestId; @@ -29,4 +33,4 @@ contract SlasherStorage is ISlasher { } uint256[48] private __gap; -} \ No newline at end of file +} diff --git a/src/unaudited/ECDSAServiceManagerBase.sol b/src/unaudited/ECDSAServiceManagerBase.sol index e9fd55a3..a2fa81b6 100644 --- a/src/unaudited/ECDSAServiceManagerBase.sol +++ b/src/unaudited/ECDSAServiceManagerBase.sol @@ -6,21 +6,19 @@ import {ISignatureUtils} from "eigenlayer-contracts/src/contracts/interfaces/ISi import {IAVSDirectory} from "eigenlayer-contracts/src/contracts/interfaces/IAVSDirectory.sol"; import {IServiceManager} from "../interfaces/IServiceManager.sol"; import {IServiceManagerUI} from "../interfaces/IServiceManagerUI.sol"; -import {IDelegationManager} from "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; +import {IDelegationManager} from + "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; import {IStrategy} from "eigenlayer-contracts/src/contracts/interfaces/IStrategy.sol"; import {IStakeRegistry} from "../interfaces/IStakeRegistry.sol"; -import {IRewardsCoordinator} from "eigenlayer-contracts/src/contracts/interfaces/IRewardsCoordinator.sol"; +import {IRewardsCoordinator} from + "eigenlayer-contracts/src/contracts/interfaces/IRewardsCoordinator.sol"; import {Quorum} from "../interfaces/IECDSAStakeRegistryEventsAndErrors.sol"; import {ECDSAStakeRegistry} from "../unaudited/ECDSAStakeRegistry.sol"; import {IAVSRegistrar} from "eigenlayer-contracts/src/contracts/interfaces/IAVSRegistrar.sol"; -import {IAllocationManager} from "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; +import {IAllocationManager} from + "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; - - -abstract contract ECDSAServiceManagerBase is - IServiceManager, - OwnableUpgradeable -{ +abstract contract ECDSAServiceManagerBase is IServiceManager, OwnableUpgradeable { /// @notice Address of the stake registry contract, which manages registration and stake recording. address public immutable stakeRegistry; @@ -125,12 +123,7 @@ abstract contract ECDSAServiceManagerBase is } /// @inheritdoc IServiceManagerUI - function getRestakeableStrategies() - external - view - virtual - returns (address[] memory) - { + function getRestakeableStrategies() external view virtual returns (address[] memory) { return _getRestakeableStrategies(); } @@ -162,10 +155,7 @@ abstract contract ECDSAServiceManagerBase is address operator, ISignatureUtils.SignatureWithSaltAndExpiry memory operatorSignature ) internal virtual { - IAVSDirectory(avsDirectory).registerOperatorToAVS( - operator, - operatorSignature - ); + IAVSDirectory(avsDirectory).registerOperatorToAVS(operator, operatorSignature); } /** @@ -173,7 +163,9 @@ abstract contract ECDSAServiceManagerBase is * @dev This internal function is a proxy to the `deregisterOperatorFromAVS` function of the AVSDirectory contract. * @param operator The address of the operator to deregister. */ - function _deregisterOperatorFromAVS(address operator) internal virtual { + function _deregisterOperatorFromAVS( + address operator + ) internal virtual { IAVSDirectory(avsDirectory).deregisterOperatorFromAVS(operator); } @@ -187,17 +179,12 @@ abstract contract ECDSAServiceManagerBase is ) internal virtual { for (uint256 i = 0; i < rewardsSubmissions.length; ++i) { rewardsSubmissions[i].token.transferFrom( - msg.sender, - address(this), - rewardsSubmissions[i].amount - ); - uint256 allowance = rewardsSubmissions[i].token.allowance( - address(this), - rewardsCoordinator + msg.sender, address(this), rewardsSubmissions[i].amount ); + uint256 allowance = + rewardsSubmissions[i].token.allowance(address(this), rewardsCoordinator); rewardsSubmissions[i].token.approve( - rewardsCoordinator, - rewardsSubmissions[i].amount + allowance + rewardsCoordinator, rewardsSubmissions[i].amount + allowance ); } @@ -209,12 +196,7 @@ abstract contract ECDSAServiceManagerBase is * @dev Fetches the quorum configuration from the ECDSAStakeRegistry and extracts the strategy addresses. * @return strategies An array of addresses representing the strategies in the current quorum. */ - function _getRestakeableStrategies() - internal - view - virtual - returns (address[] memory) - { + function _getRestakeableStrategies() internal view virtual returns (address[] memory) { Quorum memory quorum = ECDSAStakeRegistry(stakeRegistry).quorum(); address[] memory strategies = new address[](quorum.strategies.length); for (uint256 i = 0; i < quorum.strategies.length; i++) { @@ -228,7 +210,9 @@ abstract contract ECDSAServiceManagerBase is * @param registrar The new AVS registrar address * @dev Only callable by the registry coordinator */ - function setAVSRegistrar(IAVSRegistrar registrar) external onlyOwner { + function setAVSRegistrar( + IAVSRegistrar registrar + ) external onlyOwner { IAllocationManager(allocationManager).setAVSRegistrar(address(this), registrar); } @@ -284,7 +268,9 @@ abstract contract ECDSAServiceManagerBase is _setRewardsInitiator(newRewardsInitiator); } - function _setRewardsInitiator(address newRewardsInitiator) internal { + function _setRewardsInitiator( + address newRewardsInitiator + ) internal { emit RewardsInitiatorUpdated(rewardsInitiator, newRewardsInitiator); rewardsInitiator = newRewardsInitiator; } diff --git a/src/unaudited/ECDSAStakeRegistry.sol b/src/unaudited/ECDSAStakeRegistry.sol index 0e341067..edbb6778 100644 --- a/src/unaudited/ECDSAStakeRegistry.sol +++ b/src/unaudited/ECDSAStakeRegistry.sol @@ -3,14 +3,18 @@ pragma solidity ^0.8.27; import {ECDSAStakeRegistryStorage, Quorum, StrategyParams} from "./ECDSAStakeRegistryStorage.sol"; import {IStrategy} from "eigenlayer-contracts/src/contracts/interfaces/IStrategy.sol"; -import {IDelegationManager} from "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; +import {IDelegationManager} from + "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; import {ISignatureUtils} from "eigenlayer-contracts/src/contracts/interfaces/ISignatureUtils.sol"; import {IServiceManager} from "../interfaces/IServiceManager.sol"; import {OwnableUpgradeable} from "@openzeppelin-upgrades/contracts/access/OwnableUpgradeable.sol"; -import {CheckpointsUpgradeable} from "@openzeppelin-upgrades/contracts/utils/CheckpointsUpgradeable.sol"; -import {SignatureCheckerUpgradeable} from "@openzeppelin-upgrades/contracts/utils/cryptography/SignatureCheckerUpgradeable.sol"; -import {IERC1271Upgradeable} from "@openzeppelin-upgrades/contracts/interfaces/IERC1271Upgradeable.sol"; +import {CheckpointsUpgradeable} from + "@openzeppelin-upgrades/contracts/utils/CheckpointsUpgradeable.sol"; +import {SignatureCheckerUpgradeable} from + "@openzeppelin-upgrades/contracts/utils/cryptography/SignatureCheckerUpgradeable.sol"; +import {IERC1271Upgradeable} from + "@openzeppelin-upgrades/contracts/interfaces/IERC1271Upgradeable.sol"; /// @title ECDSA Stake Registry /// @dev THIS CONTRACT IS NOT AUDITED @@ -63,7 +67,9 @@ contract ECDSAStakeRegistry is * @dev Only callable by the operator themselves * @param _newSigningKey The new signing key to set for the operator */ - function updateOperatorSigningKey(address _newSigningKey) external { + function updateOperatorSigningKey( + address _newSigningKey + ) external { if (!_operatorRegistered[msg.sender]) { revert OperatorNotRegistered(); } @@ -75,7 +81,9 @@ contract ECDSAStakeRegistry is * @dev Queries stakes from the Eigenlayer core DelegationManager contract * @param _operators A list of operator addresses to update */ - function updateOperators(address[] memory _operators) external { + function updateOperators( + address[] memory _operators + ) external { _updateOperators(_operators); } @@ -113,7 +121,9 @@ contract ECDSAStakeRegistry is * cumulative weight that must be met or exceeded by the sum of the stakes of the signatories for * a message to be deemed valid. */ - function updateStakeThreshold(uint256 _thresholdWeight) external onlyOwner { + function updateStakeThreshold( + uint256 _thresholdWeight + ) external onlyOwner { _updateStakeThreshold(_thresholdWeight); } @@ -125,11 +135,8 @@ contract ECDSAStakeRegistry is bytes32 _dataHash, bytes memory _signatureData ) external view returns (bytes4) { - ( - address[] memory operators, - bytes[] memory signatures, - uint32 referenceBlock - ) = abi.decode(_signatureData, (address[], bytes[], uint32)); + (address[] memory operators, bytes[] memory signatures, uint32 referenceBlock) = + abi.decode(_signatureData, (address[], bytes[], uint32)); _checkSignatures(_dataHash, operators, signatures, referenceBlock); return IERC1271Upgradeable.isValidSignature.selector; } @@ -161,14 +168,7 @@ contract ECDSAStakeRegistry is address _operator, uint256 _blockNumber ) external view returns (address) { - return - address( - uint160( - _operatorSigningKeyHistory[_operator].getAtBlock( - _blockNumber - ) - ) - ); + return address(uint160(_operatorSigningKeyHistory[_operator].getAtBlock(_blockNumber))); } /// @notice Retrieves the last recorded weight for a given operator. @@ -188,11 +188,7 @@ contract ECDSAStakeRegistry is /// @notice Retrieves the last recorded threshold weight /// @return uint256 - The latest threshold weight. - function getLastCheckpointThresholdWeight() - external - view - returns (uint256) - { + function getLastCheckpointThresholdWeight() external view returns (uint256) { return _thresholdWeightHistory.latest(); } @@ -248,10 +244,7 @@ contract ECDSAStakeRegistry is for (uint256 i; i < strategyParams.length; i++) { strategies[i] = strategyParams[i].strategy; } - uint256[] memory shares = DELEGATION_MANAGER.getOperatorShares( - _operator, - strategies - ); + uint256[] memory shares = DELEGATION_MANAGER.getOperatorShares(_operator, strategies); for (uint256 i; i < strategyParams.length; i++) { weight += shares[i] * strategyParams[i].multiplier; } @@ -290,7 +283,9 @@ contract ECDSAStakeRegistry is /// @dev Updates the list of operators if the provided list has the correct number of operators. /// Reverts if the provided list of operators does not match the expected total count of operators. /// @param _operators The list of operator addresses to update. - function _updateAllOperators(address[] memory _operators) internal { + function _updateAllOperators( + address[] memory _operators + ) internal { if (_operators.length != _totalOperators) { revert MustUpdateAllOperators(); } @@ -300,7 +295,9 @@ contract ECDSAStakeRegistry is /// @dev Updates the weights for a given list of operator addresses. /// When passing an operator that isn't registered, then 0 is added to their history /// @param _operators An array of addresses for which to update the weights. - function _updateOperators(address[] memory _operators) internal { + function _updateOperators( + address[] memory _operators + ) internal { int256 delta; for (uint256 i; i < _operators.length; i++) { delta += _updateOperatorWeight(_operators[i]); @@ -310,14 +307,18 @@ contract ECDSAStakeRegistry is /// @dev Updates the stake threshold weight and records the history. /// @param _thresholdWeight The new threshold weight to set and record in the history. - function _updateStakeThreshold(uint256 _thresholdWeight) internal { + function _updateStakeThreshold( + uint256 _thresholdWeight + ) internal { _thresholdWeightHistory.push(_thresholdWeight); emit ThresholdWeightUpdated(_thresholdWeight); } /// @dev Updates the weight an operator must have to join the operator set /// @param _newMinimumWeight The new weight an operator must have to join the operator set - function _updateMinimumWeight(uint256 _newMinimumWeight) internal { + function _updateMinimumWeight( + uint256 _newMinimumWeight + ) internal { uint256 oldMinimumWeight = _minimumWeight; _minimumWeight = _newMinimumWeight; emit MinimumWeightUpdated(oldMinimumWeight, _newMinimumWeight); @@ -328,7 +329,9 @@ contract ECDSAStakeRegistry is /// Reverts with `InvalidQuorum` if the new quorum configuration is not valid. /// Emits `QuorumUpdated` event with the old and new quorum configurations. /// @param _newQuorum The new quorum configuration to set. - function _updateQuorumConfig(Quorum memory _newQuorum) internal { + function _updateQuorumConfig( + Quorum memory _newQuorum + ) internal { if (!_isValidQuorum(_newQuorum)) { revert InvalidQuorum(); } @@ -342,7 +345,9 @@ contract ECDSAStakeRegistry is /// @dev Internal function to deregister an operator /// @param _operator The operator's address to deregister - function _deregisterOperator(address _operator) internal { + function _deregisterOperator( + address _operator + ) internal { if (!_operatorRegistered[_operator]) { revert OperatorNotRegistered(); } @@ -370,33 +375,20 @@ contract ECDSAStakeRegistry is int256 delta = _updateOperatorWeight(_operator); _updateTotalWeight(delta); _updateOperatorSigningKey(_operator, _signingKey); - IServiceManager(_serviceManager).registerOperatorToAVS( - _operator, - _operatorSignature - ); + IServiceManager(_serviceManager).registerOperatorToAVS(_operator, _operatorSignature); emit OperatorRegistered(_operator, _serviceManager); } /// @dev Internal function to update an operator's signing key /// @param _operator The address of the operator to update the signing key for /// @param _newSigningKey The new signing key to set for the operator - function _updateOperatorSigningKey( - address _operator, - address _newSigningKey - ) internal { - address oldSigningKey = address( - uint160(_operatorSigningKeyHistory[_operator].latest()) - ); + function _updateOperatorSigningKey(address _operator, address _newSigningKey) internal { + address oldSigningKey = address(uint160(_operatorSigningKeyHistory[_operator].latest())); if (_newSigningKey == oldSigningKey) { return; } _operatorSigningKeyHistory[_operator].push(uint160(_newSigningKey)); - emit SigningKeyUpdate( - _operator, - block.number, - _newSigningKey, - oldSigningKey - ); + emit SigningKeyUpdate(_operator, block.number, _newSigningKey, oldSigningKey); } /// @notice Updates the weight of an operator and returns the previous and current weights. @@ -494,10 +486,7 @@ contract ECDSAStakeRegistry is _validateSignature(signer, _dataHash, _signatures[i]); lastOperator = currentOperator; - uint256 operatorWeight = _getOperatorWeight( - currentOperator, - _referenceBlock - ); + uint256 operatorWeight = _getOperatorWeight(currentOperator, _referenceBlock); signedWeight += operatorWeight; } @@ -522,10 +511,7 @@ contract ECDSAStakeRegistry is /// @notice Ensures that signers are sorted in ascending order by address. /// @param _lastSigner The address of the last signer. /// @param _currentSigner The address of the current signer. - function _validateSortedSigners( - address _lastSigner, - address _currentSigner - ) internal pure { + function _validateSortedSigners(address _lastSigner, address _currentSigner) internal pure { if (_lastSigner >= _currentSigner) { revert NotSorted(); } @@ -556,14 +542,7 @@ contract ECDSAStakeRegistry is if (_referenceBlock >= block.number) { revert InvalidReferenceBlock(); } - return - address( - uint160( - _operatorSigningKeyHistory[_operator].getAtBlock( - _referenceBlock - ) - ) - ); + return address(uint160(_operatorSigningKeyHistory[_operator].getAtBlock(_referenceBlock))); } /// @notice Retrieves the operator weight for a signer, either at the last checkpoint or a specified block. @@ -609,10 +588,7 @@ contract ECDSAStakeRegistry is /// @notice Validates that the cumulative stake of signed messages meets or exceeds the required threshold. /// @param _signedWeight The cumulative weight of the signers that have signed the message. /// @param _referenceBlock The block number to verify the stake threshold for - function _validateThresholdStake( - uint256 _signedWeight, - uint32 _referenceBlock - ) internal view { + function _validateThresholdStake(uint256 _signedWeight, uint32 _referenceBlock) internal view { uint256 totalWeight = _getTotalWeight(_referenceBlock); if (_signedWeight > totalWeight) { revert InvalidSignedWeight(); diff --git a/src/unaudited/ECDSAStakeRegistryStorage.sol b/src/unaudited/ECDSAStakeRegistryStorage.sol index 6509f214..a47701e3 100644 --- a/src/unaudited/ECDSAStakeRegistryStorage.sol +++ b/src/unaudited/ECDSAStakeRegistryStorage.sol @@ -1,13 +1,17 @@ // SPDX-License-Identifier: MIT pragma solidity ^0.8.27; -import {IDelegationManager} from "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; -import {CheckpointsUpgradeable} from "@openzeppelin-upgrades/contracts/utils/CheckpointsUpgradeable.sol"; -import {ECDSAStakeRegistryEventsAndErrors, Quorum, StrategyParams} from "../interfaces/IECDSAStakeRegistryEventsAndErrors.sol"; - -abstract contract ECDSAStakeRegistryStorage is - ECDSAStakeRegistryEventsAndErrors -{ +import {IDelegationManager} from + "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; +import {CheckpointsUpgradeable} from + "@openzeppelin-upgrades/contracts/utils/CheckpointsUpgradeable.sol"; +import { + ECDSAStakeRegistryEventsAndErrors, + Quorum, + StrategyParams +} from "../interfaces/IECDSAStakeRegistryEventsAndErrors.sol"; + +abstract contract ECDSAStakeRegistryStorage is ECDSAStakeRegistryEventsAndErrors { /// @notice Manages staking delegations through the DelegationManager interface IDelegationManager internal immutable DELEGATION_MANAGER; @@ -30,8 +34,7 @@ abstract contract ECDSAStakeRegistryStorage is uint256 internal _stakeExpiry; /// @notice Maps an operator to their signing key history using checkpoints - mapping(address => CheckpointsUpgradeable.History) - internal _operatorSigningKeyHistory; + mapping(address => CheckpointsUpgradeable.History) internal _operatorSigningKeyHistory; /// @notice Tracks the total stake history over time using checkpoints CheckpointsUpgradeable.History internal _totalWeightHistory; @@ -40,14 +43,15 @@ abstract contract ECDSAStakeRegistryStorage is CheckpointsUpgradeable.History internal _thresholdWeightHistory; /// @notice Maps operator addresses to their respective stake histories using checkpoints - mapping(address => CheckpointsUpgradeable.History) - internal _operatorWeightHistory; + mapping(address => CheckpointsUpgradeable.History) internal _operatorWeightHistory; /// @notice Maps an operator to their registration status mapping(address => bool) internal _operatorRegistered; /// @param _delegationManager Connects this registry with the DelegationManager - constructor(IDelegationManager _delegationManager) { + constructor( + IDelegationManager _delegationManager + ) { DELEGATION_MANAGER = _delegationManager; } diff --git a/src/unaudited/examples/ECDSAStakeRegistryEqualWeight.sol b/src/unaudited/examples/ECDSAStakeRegistryEqualWeight.sol index adfd2751..3edd6278 100644 --- a/src/unaudited/examples/ECDSAStakeRegistryEqualWeight.sol +++ b/src/unaudited/examples/ECDSAStakeRegistryEqualWeight.sol @@ -3,8 +3,10 @@ pragma solidity ^0.8.27; import {ISignatureUtils} from "eigenlayer-contracts/src/contracts/interfaces/ISignatureUtils.sol"; import {ECDSAStakeRegistryPermissioned} from "./ECDSAStakeRegistryPermissioned.sol"; -import {IDelegationManager} from "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; -import {CheckpointsUpgradeable} from "@openzeppelin-upgrades/contracts/utils/CheckpointsUpgradeable.sol"; +import {IDelegationManager} from + "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; +import {CheckpointsUpgradeable} from + "@openzeppelin-upgrades/contracts/utils/CheckpointsUpgradeable.sol"; /// @title ECDSA Stake Registry with Equal Weight /// @dev THIS CONTRACT IS NOT AUDITED @@ -25,16 +27,18 @@ contract ECDSAStakeRegistryEqualWeight is ECDSAStakeRegistryPermissioned { /// @dev Overrides the _updateOperatorWeight function from the parent class to implement equal weighting. /// Emits an OperatorWeightUpdated event upon successful update. /// @param _operator The address of the operator whose weight is being updated. - function _updateOperatorWeight(address _operator) internal override returns (int256){ + function _updateOperatorWeight( + address _operator + ) internal override returns (int256) { uint256 oldWeight; uint256 newWeight; int256 delta; if (_operatorRegistered[_operator]) { - (oldWeight, ) = _operatorWeightHistory[_operator].push(1); - delta = int256(1) - int(oldWeight); // handles if they were already registered + (oldWeight,) = _operatorWeightHistory[_operator].push(1); + delta = int256(1) - int256(oldWeight); // handles if they were already registered } else { - (oldWeight, ) = _operatorWeightHistory[_operator].push(0); - delta = int256(0) - int(oldWeight); + (oldWeight,) = _operatorWeightHistory[_operator].push(0); + delta = int256(0) - int256(oldWeight); } emit OperatorWeightUpdated(_operator, oldWeight, newWeight); return delta; diff --git a/src/unaudited/examples/ECDSAStakeRegistryPermissioned.sol b/src/unaudited/examples/ECDSAStakeRegistryPermissioned.sol index ab0bca02..f6afffdf 100644 --- a/src/unaudited/examples/ECDSAStakeRegistryPermissioned.sol +++ b/src/unaudited/examples/ECDSAStakeRegistryPermissioned.sol @@ -3,7 +3,8 @@ pragma solidity ^0.8.27; import {ISignatureUtils} from "eigenlayer-contracts/src/contracts/interfaces/ISignatureUtils.sol"; import {ECDSAStakeRegistry} from "../ECDSAStakeRegistry.sol"; -import {IDelegationManager} from "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; +import {IDelegationManager} from + "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; /// @title ECDSA Stake Registry with an Operator Allowlist /// @dev THIS CONTRACT IS NOT AUDITED @@ -36,27 +37,35 @@ contract ECDSAStakeRegistryPermissioned is ECDSAStakeRegistry { /// @notice Adds an operator to the allowlisted operator set /// @dev An allowlisted operator isn't a part of the operator set. They must subsequently register themselves /// @param _operator The address of the operator to be allowlisted - function permitOperator(address _operator) external onlyOwner { + function permitOperator( + address _operator + ) external onlyOwner { _permitOperator(_operator); } /// @notice Revokes an operator's permission and deregisters them /// @dev Emits the OperatorRevoked event if the operator was previously allowlisted. /// @param _operator The address of the operator to remove from the allowlist and deregistered. - function revokeOperator(address _operator) external onlyOwner { + function revokeOperator( + address _operator + ) external onlyOwner { _revokeOperator(_operator); } /// @notice Directly deregisters an operator without removing from the allowlist /// @dev Does not emit an event because it does not modify the allowlist. /// @param _operator The address of the operator to deregister - function ejectOperator(address _operator) external onlyOwner { + function ejectOperator( + address _operator + ) external onlyOwner { _ejectOperator(_operator); } /// @dev Deregisters and operator from the active operator set /// @param _operator The address of the operator to remove. - function _ejectOperator(address _operator) internal { + function _ejectOperator( + address _operator + ) internal { _deregisterOperator(_operator); emit OperatorEjected(_operator); } @@ -64,7 +73,9 @@ contract ECDSAStakeRegistryPermissioned is ECDSAStakeRegistry { /// @dev Adds an operator to the allowlisted operator set /// Doesn't register the operator into the operator set /// @param _operator The address of the operator to allowlist. - function _permitOperator(address _operator) internal { + function _permitOperator( + address _operator + ) internal { if (allowlistedOperators[_operator]) { revert OperatorAlreadyAllowlisted(); } @@ -75,7 +86,9 @@ contract ECDSAStakeRegistryPermissioned is ECDSAStakeRegistry { /// @dev Removes an operator from the allowlist. /// If the operator is registered, also deregisters the operator. /// @param _operator The address of the operator to be revoked. - function _revokeOperator(address _operator) internal { + function _revokeOperator( + address _operator + ) internal { if (!allowlistedOperators[_operator]) { revert OperatorNotAllowlisted(); } @@ -95,10 +108,6 @@ contract ECDSAStakeRegistryPermissioned is ECDSAStakeRegistry { if (allowlistedOperators[_operator] != true) { revert OperatorNotAllowlisted(); } - super._registerOperatorWithSig( - _operator, - _operatorSignature, - _operatorSigningKey - ); + super._registerOperatorWithSig(_operator, _operatorSignature, _operatorSigningKey); } } diff --git a/test/events/IBLSApkRegistryEvents.sol b/test/events/IBLSApkRegistryEvents.sol index 6921203d..4b5e299f 100644 --- a/test/events/IBLSApkRegistryEvents.sol +++ b/test/events/IBLSApkRegistryEvents.sol @@ -6,19 +6,13 @@ import {BN254} from "../../src/libraries/BN254.sol"; interface IBLSApkRegistryEvents { // EVENTS /// @notice Emitted when `operator` registers with the public keys `pubkeyG1` and `pubkeyG2`. - event NewPubkeyRegistration(address indexed operator, BN254.G1Point pubkeyG1, BN254.G2Point pubkeyG2); + event NewPubkeyRegistration( + address indexed operator, BN254.G1Point pubkeyG1, BN254.G2Point pubkeyG2 + ); // @notice Emitted when a new operator pubkey is registered for a set of quorums - event OperatorAddedToQuorums( - address operator, - bytes32 operatorId, - bytes quorumNumbers - ); + event OperatorAddedToQuorums(address operator, bytes32 operatorId, bytes quorumNumbers); // @notice Emitted when an operator pubkey is removed from a set of quorums - event OperatorRemovedFromQuorums( - address operator, - bytes32 operatorId, - bytes quorumNumbers - ); + event OperatorRemovedFromQuorums(address operator, bytes32 operatorId, bytes quorumNumbers); } diff --git a/test/events/IIndexRegistryEvents.sol b/test/events/IIndexRegistryEvents.sol index 21a0f0f2..6e13714b 100644 --- a/test/events/IIndexRegistryEvents.sol +++ b/test/events/IIndexRegistryEvents.sol @@ -3,5 +3,7 @@ pragma solidity ^0.8.27; interface IIndexRegistryEvents { // emitted when an operator's index in the ordered operator list for the quorum with number `quorumNumber` is updated - event QuorumIndexUpdate(bytes32 indexed operatorId, uint8 quorumNumber, uint32 newOperatorIndex); + event QuorumIndexUpdate( + bytes32 indexed operatorId, uint8 quorumNumber, uint32 newOperatorIndex + ); } diff --git a/test/events/IServiceManagerBaseEvents.sol b/test/events/IServiceManagerBaseEvents.sol index 1efb8fa0..45b12cf5 100644 --- a/test/events/IServiceManagerBaseEvents.sol +++ b/test/events/IServiceManagerBaseEvents.sol @@ -26,13 +26,13 @@ interface IServiceManagerBaseEvents { /// @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 + address indexed rewardsForAllSubmitter, bool indexed oldValue, bool indexed newValue ); event ActivationDelaySet(uint32 oldActivationDelay, uint32 newActivationDelay); event GlobalCommissionBipsSet(uint16 oldGlobalCommissionBips, uint16 newGlobalCommissionBips); - event ClaimerForSet(address indexed earner, address indexed oldClaimer, address indexed claimer); + 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, @@ -50,8 +50,6 @@ interface IServiceManagerBaseEvents { uint256 claimedAmount ); - - /// TOKEN EVENTS FOR TESTING /// /** * @dev Emitted when `value` tokens are moved from one account (`from`) to diff --git a/test/events/IStakeRegistryEvents.sol b/test/events/IStakeRegistryEvents.sol index 1b585ceb..81426dfa 100644 --- a/test/events/IStakeRegistryEvents.sol +++ b/test/events/IStakeRegistryEvents.sol @@ -5,11 +5,7 @@ import {IStakeRegistry, IStrategy} from "src/interfaces/IStakeRegistry.sol"; interface IStakeRegistryEvents { /// @notice emitted whenever the stake of `operator` is updated - event OperatorStakeUpdate( - bytes32 indexed operatorId, - uint8 quorumNumber, - uint96 stake - ); + event OperatorStakeUpdate(bytes32 indexed operatorId, uint8 quorumNumber, uint96 stake); /// @notice emitted when the minimum stake for a quorum is updated event MinimumStakeForQuorumUpdated(uint8 indexed quorumNumber, uint96 minimumStake); /// @notice emitted when a new quorum is created @@ -19,5 +15,7 @@ interface IStakeRegistryEvents { /// @notice emitted when `strategy` has removed from the array at `strategyParams[quorumNumber]` event StrategyRemovedFromQuorum(uint8 indexed quorumNumber, IStrategy strategy); /// @notice emitted when `strategy` has its `multiplier` updated in the array at `strategyParams[quorumNumber]` - event StrategyMultiplierUpdated(uint8 indexed quorumNumber, IStrategy strategy, uint256 multiplier); + event StrategyMultiplierUpdated( + uint8 indexed quorumNumber, IStrategy strategy, uint256 multiplier + ); } diff --git a/test/ffi/BLSPubKeyCompendiumFFI.t.sol b/test/ffi/BLSPubKeyCompendiumFFI.t.sol index 4f3906ba..b2c078b2 100644 --- a/test/ffi/BLSPubKeyCompendiumFFI.t.sol +++ b/test/ffi/BLSPubKeyCompendiumFFI.t.sol @@ -23,28 +23,46 @@ contract BLSApkRegistryFFITests is G2Operations { blsApkRegistry = new BLSApkRegistry(registryCoordinator); } - function testRegisterBLSPublicKey(uint256 _privKey) public { + function testRegisterBLSPublicKey( + uint256 _privKey + ) public { cheats.assume(_privKey != 0); _setKeys(_privKey); pubkeyRegistrationParams.pubkeyRegistrationSignature = _signMessage(alice); vm.prank(address(registryCoordinator)); - blsApkRegistry.registerBLSPublicKey(alice, pubkeyRegistrationParams, registryCoordinator.pubkeyRegistrationMessageHash(alice)); + blsApkRegistry.registerBLSPublicKey( + alice, + pubkeyRegistrationParams, + registryCoordinator.pubkeyRegistrationMessageHash(alice) + ); - assertEq(blsApkRegistry.operatorToPubkeyHash(alice), BN254.hashG1Point(pubkeyRegistrationParams.pubkeyG1), - "pubkey hash not stored correctly"); - assertEq(blsApkRegistry.pubkeyHashToOperator(BN254.hashG1Point(pubkeyRegistrationParams.pubkeyG1)), alice, - "operator address not stored correctly"); + assertEq( + blsApkRegistry.operatorToPubkeyHash(alice), + BN254.hashG1Point(pubkeyRegistrationParams.pubkeyG1), + "pubkey hash not stored correctly" + ); + assertEq( + blsApkRegistry.pubkeyHashToOperator( + BN254.hashG1Point(pubkeyRegistrationParams.pubkeyG1) + ), + alice, + "operator address not stored correctly" + ); } - function _setKeys(uint256 _privKey) internal { + function _setKeys( + uint256 _privKey + ) internal { privKey = _privKey; pubkeyRegistrationParams.pubkeyG1 = BN254.generatorG1().scalar_mul(_privKey); pubkeyRegistrationParams.pubkeyG2 = G2Operations.mul(_privKey); } - function _signMessage(address signer) internal view returns(BN254.G1Point memory) { + function _signMessage( + address signer + ) internal view returns (BN254.G1Point memory) { BN254.G1Point memory messageHash = registryCoordinator.pubkeyRegistrationMessageHash(signer); return BN254.scalar_mul(messageHash, privKey); } diff --git a/test/ffi/BLSSignatureCheckerFFI.t.sol b/test/ffi/BLSSignatureCheckerFFI.t.sol index 16c22ebe..55e6c0c4 100644 --- a/test/ffi/BLSSignatureCheckerFFI.t.sol +++ b/test/ffi/BLSSignatureCheckerFFI.t.sol @@ -8,9 +8,7 @@ import {OperatorStateRetriever} from "../../src/OperatorStateRetriever.sol"; import {BN254} from "../../src/libraries/BN254.sol"; import {BitmapUtils} from "../../src/libraries/BitmapUtils.sol"; - contract BLSSignatureCheckerFFITests is MockAVSDeployer, G2Operations { - using BN254 for BN254.G1Point; bytes32 msgHash = keccak256(abi.encodePacked("hello world")); @@ -21,7 +19,7 @@ contract BLSSignatureCheckerFFITests is MockAVSDeployer, G2Operations { BLSSignatureChecker blsSignatureChecker; - function setUp() virtual public { + function setUp() public virtual { _deployMockEigenLayerAndAVS(); blsSignatureChecker = new BLSSignatureChecker(registryCoordinator); @@ -30,24 +28,27 @@ contract BLSSignatureCheckerFFITests is MockAVSDeployer, G2Operations { // this test checks that a valid signature from maxOperatorsToRegister with a random number of nonsigners is checked // correctly on the BLSSignatureChecker contract when all operators are only regsitered for a single quorum and // the signature is only checked for stakes on that quorum - function testBLSSignatureChecker_SingleQuorum_Valid(uint256 pseudoRandomNumber) public { + function testBLSSignatureChecker_SingleQuorum_Valid( + uint256 pseudoRandomNumber + ) public { uint256 numNonSigners = pseudoRandomNumber % (maxOperatorsToRegister - 1); uint256 quorumBitmap = 1; bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmap); - (uint32 referenceBlockNumber, BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature) = - _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom(pseudoRandomNumber, numNonSigners, quorumBitmap); + ( + uint32 referenceBlockNumber, + BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature + ) = _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom( + pseudoRandomNumber, numNonSigners, quorumBitmap + ); uint256 gasBefore = gasleft(); ( BLSSignatureChecker.QuorumStakeTotals memory quorumStakeTotals, /* bytes32 signatoryRecordHash */ ) = blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - nonSignerStakesAndSignature + msgHash, quorumNumbers, referenceBlockNumber, nonSignerStakesAndSignature ); uint256 gasAfter = gasleft(); emit log_named_uint("gasUsed", gasBefore - gasAfter); @@ -61,32 +62,37 @@ contract BLSSignatureCheckerFFITests is MockAVSDeployer, G2Operations { // this test checks that a valid signature from maxOperatorsToRegister with a random number of nonsigners is checked // correctly on the BLSSignatureChecker contract when all operators are registered for the first 100 quorums // and the signature is only checked for stakes on those quorums - function testBLSSignatureChecker_100Quorums_Valid(uint256 pseudoRandomNumber) public { + function testBLSSignatureChecker_100Quorums_Valid( + uint256 pseudoRandomNumber + ) public { uint256 numNonSigners = pseudoRandomNumber % (maxOperatorsToRegister - 1); // 100 set bits uint256 quorumBitmap = (1 << 100) - 1; bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmap); - (uint32 referenceBlockNumber, BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature) = - _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom(pseudoRandomNumber, numNonSigners, quorumBitmap); + ( + uint32 referenceBlockNumber, + BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature + ) = _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom( + pseudoRandomNumber, numNonSigners, quorumBitmap + ); nonSignerStakesAndSignature.sigma = sigma.scalar_mul(quorumNumbers.length); nonSignerStakesAndSignature.apkG2 = oneHundredQuorumApkG2; uint256 gasBefore = gasleft(); blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - nonSignerStakesAndSignature + msgHash, quorumNumbers, referenceBlockNumber, nonSignerStakesAndSignature ); uint256 gasAfter = gasleft(); emit log_named_uint("gasUsed", gasBefore - gasAfter); } - function _setAggregatePublicKeysAndSignature(uint256 pseudoRandomNumber) internal { - if(pseudoRandomNumber > type(uint256).max / 100) { + function _setAggregatePublicKeysAndSignature( + uint256 pseudoRandomNumber + ) internal { + if (pseudoRandomNumber > type(uint256).max / 100) { pseudoRandomNumber = type(uint256).max / 100; } aggSignerPrivKey = pseudoRandomNumber; @@ -95,29 +101,45 @@ contract BLSSignatureCheckerFFITests is MockAVSDeployer, G2Operations { sigma = BN254.hashToG1(msgHash).scalar_mul(aggSignerPrivKey); } - function _generateSignerAndNonSignerPrivateKeys(uint256 pseudoRandomNumber, uint256 numSigners, uint256 numNonSigners) internal returns (uint256[] memory, uint256[] memory) { + function _generateSignerAndNonSignerPrivateKeys( + uint256 pseudoRandomNumber, + uint256 numSigners, + uint256 numNonSigners + ) internal returns (uint256[] memory, uint256[] memory) { _setAggregatePublicKeysAndSignature(pseudoRandomNumber); uint256[] memory signerPrivateKeys = new uint256[](numSigners); // generate numSigners numbers that add up to aggSignerPrivKey mod BN254.FR_MODULUS uint256 sum = 0; - for (uint i = 0; i < numSigners - 1; i++) { - signerPrivateKeys[i] = uint256(keccak256(abi.encodePacked("signerPrivateKey", pseudoRandomNumber, i))) % BN254.FR_MODULUS; + for (uint256 i = 0; i < numSigners - 1; i++) { + signerPrivateKeys[i] = uint256( + keccak256(abi.encodePacked("signerPrivateKey", pseudoRandomNumber, i)) + ) % BN254.FR_MODULUS; sum = addmod(sum, signerPrivateKeys[i], BN254.FR_MODULUS); } // signer private keys need to add to aggSignerPrivKey - signerPrivateKeys[numSigners - 1] = addmod(aggSignerPrivKey, BN254.FR_MODULUS - sum % BN254.FR_MODULUS, BN254.FR_MODULUS); + signerPrivateKeys[numSigners - 1] = + addmod(aggSignerPrivKey, BN254.FR_MODULUS - sum % BN254.FR_MODULUS, BN254.FR_MODULUS); uint256[] memory nonSignerPrivateKeys = new uint256[](numNonSigners); - for (uint i = 0; i < numNonSigners; i++) { - nonSignerPrivateKeys[i] = uint256(keccak256(abi.encodePacked("nonSignerPrivateKey", pseudoRandomNumber, i))) % BN254.FR_MODULUS; + for (uint256 i = 0; i < numNonSigners; i++) { + nonSignerPrivateKeys[i] = uint256( + keccak256(abi.encodePacked("nonSignerPrivateKey", pseudoRandomNumber, i)) + ) % BN254.FR_MODULUS; } return (signerPrivateKeys, nonSignerPrivateKeys); } - function _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom(uint256 pseudoRandomNumber, uint256 numNonSigners, uint256 quorumBitmap) internal returns(uint32, BLSSignatureChecker.NonSignerStakesAndSignature memory) { - (uint256[] memory signerPrivateKeys, uint256[] memory nonSignerPrivateKeys) = _generateSignerAndNonSignerPrivateKeys(pseudoRandomNumber, maxOperatorsToRegister - numNonSigners, numNonSigners); + function _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom( + uint256 pseudoRandomNumber, + uint256 numNonSigners, + uint256 quorumBitmap + ) internal returns (uint32, BLSSignatureChecker.NonSignerStakesAndSignature memory) { + (uint256[] memory signerPrivateKeys, uint256[] memory nonSignerPrivateKeys) = + _generateSignerAndNonSignerPrivateKeys( + pseudoRandomNumber, maxOperatorsToRegister - numNonSigners, numNonSigners + ); bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmap); // randomly combine signer and non-signer private keys @@ -132,15 +154,17 @@ contract BLSSignatureCheckerFFITests is MockAVSDeployer, G2Operations { { uint256 signerIndex = 0; uint256 nonSignerIndex = 0; - for (uint i = 0; i < maxOperatorsToRegister; i++) { + for (uint256 i = 0; i < maxOperatorsToRegister; i++) { uint256 randomSeed = uint256(keccak256(abi.encodePacked("privKeyCombination", i))); if (randomSeed % 2 == 0 && signerIndex < signerPrivateKeys.length) { privateKeys[i] = signerPrivateKeys[signerIndex]; signerIndex++; } else if (nonSignerIndex < nonSignerPrivateKeys.length) { privateKeys[i] = nonSignerPrivateKeys[nonSignerIndex]; - nonSignerStakesAndSignature.nonSignerPubkeys[nonSignerIndex] = BN254.generatorG1().scalar_mul(privateKeys[i]); - nonSignerOperatorIds[nonSignerIndex] = nonSignerStakesAndSignature.nonSignerPubkeys[nonSignerIndex].hashG1Point(); + nonSignerStakesAndSignature.nonSignerPubkeys[nonSignerIndex] = + BN254.generatorG1().scalar_mul(privateKeys[i]); + nonSignerOperatorIds[nonSignerIndex] = + nonSignerStakesAndSignature.nonSignerPubkeys[nonSignerIndex].hashG1Point(); nonSignerIndex++; } else { privateKeys[i] = signerPrivateKeys[signerIndex]; @@ -151,36 +175,37 @@ contract BLSSignatureCheckerFFITests is MockAVSDeployer, G2Operations { pubkeys[i] = BN254.generatorG1().scalar_mul(privateKeys[i]); // add the public key to each quorum - for (uint j = 0; j < nonSignerStakesAndSignature.quorumApks.length; j++) { - nonSignerStakesAndSignature.quorumApks[j] = nonSignerStakesAndSignature.quorumApks[j].plus(pubkeys[i]); + for (uint256 j = 0; j < nonSignerStakesAndSignature.quorumApks.length; j++) { + nonSignerStakesAndSignature.quorumApks[j] = + nonSignerStakesAndSignature.quorumApks[j].plus(pubkeys[i]); } } } // register all operators for the first quorum - for (uint i = 0; i < maxOperatorsToRegister; i++) { + for (uint256 i = 0; i < maxOperatorsToRegister; i++) { cheats.roll(registrationBlockNumber + blocksBetweenRegistrations * i); _registerOperatorWithCoordinator(operators[i], quorumBitmap, pubkeys[i], defaultStake); } - uint32 referenceBlockNumber = registrationBlockNumber + blocksBetweenRegistrations * uint32(maxOperatorsToRegister) + 1; + uint32 referenceBlockNumber = registrationBlockNumber + + blocksBetweenRegistrations * uint32(maxOperatorsToRegister) + 1; cheats.roll(referenceBlockNumber + 100); - OperatorStateRetriever.CheckSignaturesIndices memory checkSignaturesIndices = operatorStateRetriever.getCheckSignaturesIndices( - registryCoordinator, - referenceBlockNumber, - quorumNumbers, - nonSignerOperatorIds + OperatorStateRetriever.CheckSignaturesIndices memory checkSignaturesIndices = + operatorStateRetriever.getCheckSignaturesIndices( + registryCoordinator, referenceBlockNumber, quorumNumbers, nonSignerOperatorIds ); - nonSignerStakesAndSignature.nonSignerQuorumBitmapIndices = checkSignaturesIndices.nonSignerQuorumBitmapIndices; + nonSignerStakesAndSignature.nonSignerQuorumBitmapIndices = + checkSignaturesIndices.nonSignerQuorumBitmapIndices; nonSignerStakesAndSignature.apkG2 = aggSignerApkG2; nonSignerStakesAndSignature.sigma = sigma; nonSignerStakesAndSignature.quorumApkIndices = checkSignaturesIndices.quorumApkIndices; nonSignerStakesAndSignature.totalStakeIndices = checkSignaturesIndices.totalStakeIndices; - nonSignerStakesAndSignature.nonSignerStakeIndices = checkSignaturesIndices.nonSignerStakeIndices; + nonSignerStakesAndSignature.nonSignerStakeIndices = + checkSignaturesIndices.nonSignerStakeIndices; return (referenceBlockNumber, nonSignerStakesAndSignature); } - } diff --git a/test/ffi/UpdateOperators.t.sol b/test/ffi/UpdateOperators.t.sol index 64e3ecbc..b7bba5b0 100644 --- a/test/ffi/UpdateOperators.t.sol +++ b/test/ffi/UpdateOperators.t.sol @@ -10,7 +10,1008 @@ contract Integration_AVS_Sync_GasCosts_FFI is IntegrationChecks { using BitmapUtils for *; // Private keys sorted by operatorIds. - uint256[] public privateKeys = [853, 690, 815, 398, 987, 432, 946, 717, 760, 840, 719, 714, 11, 554, 528, 368, 160, 22, 562, 266, 827, 488, 335, 566, 365, 54, 6, 733, 835, 656, 496, 472, 126, 50, 643, 632, 421, 797, 610, 737, 154, 918, 819, 694, 556, 608, 203, 521, 188, 908, 400, 349, 290, 463, 680, 973, 204, 439, 822, 799, 795, 251, 482, 326, 411, 839, 851, 652, 458, 108, 92, 278, 8, 773, 302, 699, 936, 427, 321, 700, 683, 36, 828, 732, 963, 664, 776, 161, 460, 426, 878, 96, 572, 678, 898, 372, 764, 579, 215, 507, 533, 965, 72, 708, 706, 334, 722, 665, 446, 397, 151, 802, 224, 753, 206, 190, 569, 253, 735, 578, 859, 711, 135, 944, 344, 655, 202, 743, 292, 176, 262, 961, 270, 117, 502, 546, 247, 31, 663, 515, 850, 509, 728, 424, 197, 239, 905, 545, 121, 438, 513, 881, 233, 221, 593, 831, 491, 282, 979, 410, 873, 316, 210, 371, 40, 255, 329, 483, 975, 742, 214, 813, 691, 467, 830, 808, 951, 924, 147, 705, 772, 30, 486, 576, 469, 331, 27, 313, 849, 805, 499, 404, 178, 10, 399, 485, 627, 60, 709, 570, 97, 894, 88, 264, 245, 129, 818, 218, 395, 387, 110, 455, 695, 199, 648, 444, 435, 230, 84, 489, 649, 385, 274, 95, 442, 899, 999, 651, 310, 227, 823, 538, 345, 229, 551, 24, 686, 877, 707, 671, 585, 530, 952, 28, 692, 336, 673, 777, 789, 366, 781, 872, 386, 64, 342, 244, 445, 816, 332, 436, 596, 148, 425, 863, 967, 611, 153, 749, 940, 150, 280, 634, 631, 954, 891, 666, 319, 93, 807, 82, 79, 91, 146, 291, 78, 923, 910, 320, 529, 857, 945, 205, 602, 974, 41, 503, 868, 783, 303, 536, 523, 357, 409, 832, 474, 862, 516, 140, 617, 543, 356, 77, 328, 976, 46, 834, 750, 99, 633, 949, 568, 636, 766, 363, 174, 138, 112, 574, 541, 703, 81, 412, 98, 477, 452, 755, 598, 464, 880, 884, 418, 829, 645, 607, 279, 820, 66, 416, 517, 384, 29, 192, 59, 15, 573, 94, 383, 981, 889, 914, 172, 322, 248, 845, 775, 1000, 854, 817, 668, 724, 786, 575, 710, 825, 407, 592, 890, 911, 641, 544, 989, 347, 196, 125, 370, 459, 803, 454, 564, 939, 658, 624, 996, 142, 514, 758, 848, 980, 955, 855, 298, 119, 391, 341, 130, 577, 798, 323, 986, 58, 171, 14, 959, 234, 838, 811, 958, 715, 902, 846, 571, 456, 268, 882, 257, 591, 497, 630, 20, 136, 672, 621, 744, 791, 314, 252, 367, 833, 23, 693, 726, 595, 276, 620, 167, 325, 401, 481, 63, 730, 771, 613, 614, 943, 526, 604, 104, 932, 856, 263, 650, 590, 232, 462, 931, 236, 915, 402, 644, 315, 213, 249, 869, 179, 312, 718, 675, 493, 903, 542, 287, 752, 285, 487, 661, 616, 182, 888, 929, 842, 364, 720, 935, 396, 763, 235, 226, 879, 346, 916, 615, 800, 972, 906, 547, 997, 198, 500, 39, 193, 864, 837, 301, 484, 362, 836, 293, 913, 324, 269, 520, 25, 169, 745, 960, 883, 61, 741, 382, 115, 220, 953, 612, 970, 207, 796, 901, 865, 53, 275, 408, 639, 875, 265, 756, 887, 133, 586, 296, 450, 433, 200, 49, 662, 2, 4, 183, 697, 222, 479, 429, 747, 143, 713, 784, 982, 539, 380, 75, 667, 601, 992, 457, 70, 103, 587, 785, 107, 186, 679, 804, 821, 567, 201, 928, 461, 413, 120, 67, 164, 441, 89, 962, 738, 801, 242, 740, 373, 759, 68, 490, 43, 358, 677, 937, 778, 589, 947, 565, 414, 861, 712, 299, 83, 904, 978, 886, 969, 701, 453, 933, 757, 76, 721, 286, 311, 968, 156, 184, 998, 994, 921, 159, 790, 934, 12, 128, 519, 307, 809, 687, 228, 393, 52, 912, 217, 113, 736, 195, 858, 925, 21, 170, 305, 892, 977, 360, 139, 810, 71, 727, 669, 622, 919, 32, 173, 208, 34, 535, 957, 782, 792, 874, 48, 132, 177, 57, 13, 475, 243, 647, 352, 5, 494, 277, 681, 580, 338, 158, 920, 350, 300, 284, 626, 297, 369, 806, 470, 895, 603, 420, 768, 761, 33, 191, 449, 359, 375, 844, 561, 86, 355, 606, 676, 734, 271, 381, 716, 767, 337, 688, 938, 746, 540, 942, 209, 451, 267, 907, 731, 674, 180, 619, 166, 893, 100, 704, 993, 294, 583, 770, 739, 256, 508, 495, 440, 289, 145, 237, 557, 109, 187, 102, 80, 843, 273, 37, 38, 354, 584, 794, 134, 194, 927, 922, 885, 118, 65, 684, 45, 431, 419, 281, 582, 531, 504, 471, 900, 51, 896, 124, 216, 466, 26, 378, 9, 137, 116, 588, 988, 423, 729, 157, 600, 152, 698, 106, 774, 448, 950, 56, 876, 379, 956, 163, 702, 511, 69, 3, 473, 990, 181, 555, 563, 165, 549, 447, 560, 510, 552, 304, 629, 930, 518, 826, 991, 17, 16, 35, 505, 723, 480, 478, 841, 254, 640, 405, 867, 522, 175, 468, 926, 852, 241, 860, 74, 443, 501, 769, 394, 246, 225, 966, 388, 111, 272, 259, 376, 985, 765, 984, 231, 597, 548, 374, 295, 870, 917, 897, 725, 642, 780, 422, 283, 971, 415, 240, 787, 238, 340, 149, 527, 550, 377, 964, 558, 144, 553, 788, 618, 351, 330, 525, 685, 625, 85, 42, 465, 941, 762, 47, 476, 751, 871, 189, 212, 754, 824, 223, 748, 7, 532, 670, 162, 403, 1, 659, 306, 657, 317, 623, 318, 605, 537, 131, 689, 308, 430, 168, 309, 599, 682, 654, 866, 90, 327, 581, 909, 635, 114, 559, 123, 127, 660, 646, 288, 19, 389, 793, 406, 638, 812, 343, 62, 498, 437, 44, 260, 122, 101, 628, 779, 417, 847, 696, 492, 211, 434, 339, 594, 333, 219, 348, 18, 250, 105, 512, 185, 524, 506, 155, 948, 141, 55, 428, 637, 392, 609, 995, 361, 983, 261, 653, 258, 87, 353, 390, 73, 534, 814]; + uint256[] public privateKeys = [ + 853, + 690, + 815, + 398, + 987, + 432, + 946, + 717, + 760, + 840, + 719, + 714, + 11, + 554, + 528, + 368, + 160, + 22, + 562, + 266, + 827, + 488, + 335, + 566, + 365, + 54, + 6, + 733, + 835, + 656, + 496, + 472, + 126, + 50, + 643, + 632, + 421, + 797, + 610, + 737, + 154, + 918, + 819, + 694, + 556, + 608, + 203, + 521, + 188, + 908, + 400, + 349, + 290, + 463, + 680, + 973, + 204, + 439, + 822, + 799, + 795, + 251, + 482, + 326, + 411, + 839, + 851, + 652, + 458, + 108, + 92, + 278, + 8, + 773, + 302, + 699, + 936, + 427, + 321, + 700, + 683, + 36, + 828, + 732, + 963, + 664, + 776, + 161, + 460, + 426, + 878, + 96, + 572, + 678, + 898, + 372, + 764, + 579, + 215, + 507, + 533, + 965, + 72, + 708, + 706, + 334, + 722, + 665, + 446, + 397, + 151, + 802, + 224, + 753, + 206, + 190, + 569, + 253, + 735, + 578, + 859, + 711, + 135, + 944, + 344, + 655, + 202, + 743, + 292, + 176, + 262, + 961, + 270, + 117, + 502, + 546, + 247, + 31, + 663, + 515, + 850, + 509, + 728, + 424, + 197, + 239, + 905, + 545, + 121, + 438, + 513, + 881, + 233, + 221, + 593, + 831, + 491, + 282, + 979, + 410, + 873, + 316, + 210, + 371, + 40, + 255, + 329, + 483, + 975, + 742, + 214, + 813, + 691, + 467, + 830, + 808, + 951, + 924, + 147, + 705, + 772, + 30, + 486, + 576, + 469, + 331, + 27, + 313, + 849, + 805, + 499, + 404, + 178, + 10, + 399, + 485, + 627, + 60, + 709, + 570, + 97, + 894, + 88, + 264, + 245, + 129, + 818, + 218, + 395, + 387, + 110, + 455, + 695, + 199, + 648, + 444, + 435, + 230, + 84, + 489, + 649, + 385, + 274, + 95, + 442, + 899, + 999, + 651, + 310, + 227, + 823, + 538, + 345, + 229, + 551, + 24, + 686, + 877, + 707, + 671, + 585, + 530, + 952, + 28, + 692, + 336, + 673, + 777, + 789, + 366, + 781, + 872, + 386, + 64, + 342, + 244, + 445, + 816, + 332, + 436, + 596, + 148, + 425, + 863, + 967, + 611, + 153, + 749, + 940, + 150, + 280, + 634, + 631, + 954, + 891, + 666, + 319, + 93, + 807, + 82, + 79, + 91, + 146, + 291, + 78, + 923, + 910, + 320, + 529, + 857, + 945, + 205, + 602, + 974, + 41, + 503, + 868, + 783, + 303, + 536, + 523, + 357, + 409, + 832, + 474, + 862, + 516, + 140, + 617, + 543, + 356, + 77, + 328, + 976, + 46, + 834, + 750, + 99, + 633, + 949, + 568, + 636, + 766, + 363, + 174, + 138, + 112, + 574, + 541, + 703, + 81, + 412, + 98, + 477, + 452, + 755, + 598, + 464, + 880, + 884, + 418, + 829, + 645, + 607, + 279, + 820, + 66, + 416, + 517, + 384, + 29, + 192, + 59, + 15, + 573, + 94, + 383, + 981, + 889, + 914, + 172, + 322, + 248, + 845, + 775, + 1000, + 854, + 817, + 668, + 724, + 786, + 575, + 710, + 825, + 407, + 592, + 890, + 911, + 641, + 544, + 989, + 347, + 196, + 125, + 370, + 459, + 803, + 454, + 564, + 939, + 658, + 624, + 996, + 142, + 514, + 758, + 848, + 980, + 955, + 855, + 298, + 119, + 391, + 341, + 130, + 577, + 798, + 323, + 986, + 58, + 171, + 14, + 959, + 234, + 838, + 811, + 958, + 715, + 902, + 846, + 571, + 456, + 268, + 882, + 257, + 591, + 497, + 630, + 20, + 136, + 672, + 621, + 744, + 791, + 314, + 252, + 367, + 833, + 23, + 693, + 726, + 595, + 276, + 620, + 167, + 325, + 401, + 481, + 63, + 730, + 771, + 613, + 614, + 943, + 526, + 604, + 104, + 932, + 856, + 263, + 650, + 590, + 232, + 462, + 931, + 236, + 915, + 402, + 644, + 315, + 213, + 249, + 869, + 179, + 312, + 718, + 675, + 493, + 903, + 542, + 287, + 752, + 285, + 487, + 661, + 616, + 182, + 888, + 929, + 842, + 364, + 720, + 935, + 396, + 763, + 235, + 226, + 879, + 346, + 916, + 615, + 800, + 972, + 906, + 547, + 997, + 198, + 500, + 39, + 193, + 864, + 837, + 301, + 484, + 362, + 836, + 293, + 913, + 324, + 269, + 520, + 25, + 169, + 745, + 960, + 883, + 61, + 741, + 382, + 115, + 220, + 953, + 612, + 970, + 207, + 796, + 901, + 865, + 53, + 275, + 408, + 639, + 875, + 265, + 756, + 887, + 133, + 586, + 296, + 450, + 433, + 200, + 49, + 662, + 2, + 4, + 183, + 697, + 222, + 479, + 429, + 747, + 143, + 713, + 784, + 982, + 539, + 380, + 75, + 667, + 601, + 992, + 457, + 70, + 103, + 587, + 785, + 107, + 186, + 679, + 804, + 821, + 567, + 201, + 928, + 461, + 413, + 120, + 67, + 164, + 441, + 89, + 962, + 738, + 801, + 242, + 740, + 373, + 759, + 68, + 490, + 43, + 358, + 677, + 937, + 778, + 589, + 947, + 565, + 414, + 861, + 712, + 299, + 83, + 904, + 978, + 886, + 969, + 701, + 453, + 933, + 757, + 76, + 721, + 286, + 311, + 968, + 156, + 184, + 998, + 994, + 921, + 159, + 790, + 934, + 12, + 128, + 519, + 307, + 809, + 687, + 228, + 393, + 52, + 912, + 217, + 113, + 736, + 195, + 858, + 925, + 21, + 170, + 305, + 892, + 977, + 360, + 139, + 810, + 71, + 727, + 669, + 622, + 919, + 32, + 173, + 208, + 34, + 535, + 957, + 782, + 792, + 874, + 48, + 132, + 177, + 57, + 13, + 475, + 243, + 647, + 352, + 5, + 494, + 277, + 681, + 580, + 338, + 158, + 920, + 350, + 300, + 284, + 626, + 297, + 369, + 806, + 470, + 895, + 603, + 420, + 768, + 761, + 33, + 191, + 449, + 359, + 375, + 844, + 561, + 86, + 355, + 606, + 676, + 734, + 271, + 381, + 716, + 767, + 337, + 688, + 938, + 746, + 540, + 942, + 209, + 451, + 267, + 907, + 731, + 674, + 180, + 619, + 166, + 893, + 100, + 704, + 993, + 294, + 583, + 770, + 739, + 256, + 508, + 495, + 440, + 289, + 145, + 237, + 557, + 109, + 187, + 102, + 80, + 843, + 273, + 37, + 38, + 354, + 584, + 794, + 134, + 194, + 927, + 922, + 885, + 118, + 65, + 684, + 45, + 431, + 419, + 281, + 582, + 531, + 504, + 471, + 900, + 51, + 896, + 124, + 216, + 466, + 26, + 378, + 9, + 137, + 116, + 588, + 988, + 423, + 729, + 157, + 600, + 152, + 698, + 106, + 774, + 448, + 950, + 56, + 876, + 379, + 956, + 163, + 702, + 511, + 69, + 3, + 473, + 990, + 181, + 555, + 563, + 165, + 549, + 447, + 560, + 510, + 552, + 304, + 629, + 930, + 518, + 826, + 991, + 17, + 16, + 35, + 505, + 723, + 480, + 478, + 841, + 254, + 640, + 405, + 867, + 522, + 175, + 468, + 926, + 852, + 241, + 860, + 74, + 443, + 501, + 769, + 394, + 246, + 225, + 966, + 388, + 111, + 272, + 259, + 376, + 985, + 765, + 984, + 231, + 597, + 548, + 374, + 295, + 870, + 917, + 897, + 725, + 642, + 780, + 422, + 283, + 971, + 415, + 240, + 787, + 238, + 340, + 149, + 527, + 550, + 377, + 964, + 558, + 144, + 553, + 788, + 618, + 351, + 330, + 525, + 685, + 625, + 85, + 42, + 465, + 941, + 762, + 47, + 476, + 751, + 871, + 189, + 212, + 754, + 824, + 223, + 748, + 7, + 532, + 670, + 162, + 403, + 1, + 659, + 306, + 657, + 317, + 623, + 318, + 605, + 537, + 131, + 689, + 308, + 430, + 168, + 309, + 599, + 682, + 654, + 866, + 90, + 327, + 581, + 909, + 635, + 114, + 559, + 123, + 127, + 660, + 646, + 288, + 19, + 389, + 793, + 406, + 638, + 812, + 343, + 62, + 498, + 437, + 44, + 260, + 122, + 101, + 628, + 779, + 417, + 847, + 696, + 492, + 211, + 434, + 339, + 594, + 333, + 219, + 348, + 18, + 250, + 105, + 512, + 185, + 524, + 506, + 155, + 948, + 141, + 55, + 428, + 637, + 392, + 609, + 995, + 361, + 983, + 261, + 653, + 258, + 87, + 353, + 390, + 73, + 534, + 814 + ]; bytes32[] public operatorIds; address[] public operatorAddresses; @@ -29,31 +1030,19 @@ contract Integration_AVS_Sync_GasCosts_FFI is IntegrationChecks { IBLSApkRegistry.PubkeyRegistrationParams memory pubkey; uint256 privateKey = privateKeys[i]; // G1 - pubkey.pubkeyG1.X = stdJson.readUint( - config_data, - string.concat(".G1x[", vm.toString(i), "]") - ); - pubkey.pubkeyG1.Y = stdJson.readUint( - config_data, - string.concat(".G1y[", vm.toString(i), "]") - ); + pubkey.pubkeyG1.X = + stdJson.readUint(config_data, string.concat(".G1x[", vm.toString(i), "]")); + pubkey.pubkeyG1.Y = + stdJson.readUint(config_data, string.concat(".G1y[", vm.toString(i), "]")); // G2 - pubkey.pubkeyG2.X[1] = stdJson.readUint( - config_data, - string.concat(".G2x1[", vm.toString(i), "]") - ); - pubkey.pubkeyG2.Y[1] = stdJson.readUint( - config_data, - string.concat(".G2y1[", vm.toString(i), "]") - ); - pubkey.pubkeyG2.X[0] = stdJson.readUint( - config_data, - string.concat(".G2x0[", vm.toString(i), "]") - ); - pubkey.pubkeyG2.Y[0] = stdJson.readUint( - config_data, - string.concat(".G2y0[", vm.toString(i), "]") - ); + pubkey.pubkeyG2.X[1] = + stdJson.readUint(config_data, string.concat(".G2x1[", vm.toString(i), "]")); + pubkey.pubkeyG2.Y[1] = + stdJson.readUint(config_data, string.concat(".G2y1[", vm.toString(i), "]")); + pubkey.pubkeyG2.X[0] = + stdJson.readUint(config_data, string.concat(".G2x0[", vm.toString(i), "]")); + pubkey.pubkeyG2.Y[0] = + stdJson.readUint(config_data, string.concat(".G2y0[", vm.toString(i), "]")); privKeys.push(privateKey); pubkeys.push(pubkey); } @@ -146,11 +1135,13 @@ contract Integration_AVS_Sync_GasCosts_FFI is IntegrationChecks { console.log("Gas used for updateOperatorsForQuorum: ", gasBefore - gasAfter); } - function _sortArray(address[] memory arr) internal pure returns (address[] memory) { + function _sortArray( + address[] memory arr + ) internal pure returns (address[] memory) { uint256 l = arr.length; - for(uint i = 0; i < l; i++) { - for(uint j = i+1; j < l ;j++) { - if(arr[i] > arr[j]) { + for (uint256 i = 0; i < l; i++) { + for (uint256 j = i + 1; j < l; j++) { + if (arr[i] > arr[j]) { address temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; diff --git a/test/ffi/util/G2Operations.sol b/test/ffi/util/G2Operations.sol index 016011da..52127f9a 100644 --- a/test/ffi/util/G2Operations.sol +++ b/test/ffi/util/G2Operations.sol @@ -8,7 +8,9 @@ import "../../../src/libraries/BN254.sol"; contract G2Operations is Test { using Strings for uint256; - function mul(uint256 x) public returns (BN254.G2Point memory g2Point) { + function mul( + uint256 x + ) public returns (BN254.G2Point memory g2Point) { string[] memory inputs = new string[](5); inputs[0] = "go"; inputs[1] = "run"; @@ -31,5 +33,4 @@ contract G2Operations is Test { res = vm.ffi(inputs); g2Point.Y[0] = abi.decode(res, (uint256)); } - } diff --git a/test/harnesses/AVSDirectoryHarness.sol b/test/harnesses/AVSDirectoryHarness.sol index 995f62a6..d452da82 100644 --- a/test/harnesses/AVSDirectoryHarness.sol +++ b/test/harnesses/AVSDirectoryHarness.sol @@ -8,5 +8,5 @@ import {IPauserRegistry} from "eigenlayer-contracts/src/contracts/interfaces/IPa // wrapper around the AVSDirectory contract that exposes internal functionality, for unit testing contract AVSDirectoryHarness is AVSDirectory { - constructor(IDelegationManager _dm, IPauserRegistry _pauser)AVSDirectory(_dm, _pauser){} -} \ No newline at end of file + constructor(IDelegationManager _dm, IPauserRegistry _pauser) AVSDirectory(_dm, _pauser) {} +} diff --git a/test/harnesses/BLSApkRegistryHarness.sol b/test/harnesses/BLSApkRegistryHarness.sol index 7cc8ec60..1ee7df30 100644 --- a/test/harnesses/BLSApkRegistryHarness.sol +++ b/test/harnesses/BLSApkRegistryHarness.sol @@ -5,13 +5,11 @@ import "../../src/BLSApkRegistry.sol"; // wrapper around the BLSApkRegistry contract that exposes internal functionality, for unit testing _other functionality_. contract BLSApkRegistryHarness is BLSApkRegistry { - constructor( IRegistryCoordinator _registryCoordinator ) BLSApkRegistry(_registryCoordinator) {} function setBLSPublicKey(address account, BN254.G1Point memory pk) external { - bytes32 pubkeyHash = BN254.hashG1Point(pk); // store updates operatorToPubkeyHash[account] = pubkeyHash; diff --git a/test/harnesses/BitmapUtilsWrapper.sol b/test/harnesses/BitmapUtilsWrapper.sol index 95322d21..982d2e1a 100644 --- a/test/harnesses/BitmapUtilsWrapper.sol +++ b/test/harnesses/BitmapUtilsWrapper.sol @@ -5,19 +5,27 @@ import "../../src/libraries/BitmapUtils.sol"; // wrapper around the BitmapUtils library that exposes the internal functions contract BitmapUtilsWrapper { - function orderedBytesArrayToBitmap(bytes calldata orderedBytesArray) external pure returns (uint256) { + function orderedBytesArrayToBitmap( + bytes calldata orderedBytesArray + ) external pure returns (uint256) { return BitmapUtils.orderedBytesArrayToBitmap(orderedBytesArray); } - function isArrayStrictlyAscendingOrdered(bytes calldata bytesArray) external pure returns (bool) { + function isArrayStrictlyAscendingOrdered( + bytes calldata bytesArray + ) external pure returns (bool) { return BitmapUtils.isArrayStrictlyAscendingOrdered(bytesArray); } - function bitmapToBytesArray(uint256 bitmap) external pure returns (bytes memory bytesArray) { + function bitmapToBytesArray( + uint256 bitmap + ) external pure returns (bytes memory bytesArray) { return BitmapUtils.bitmapToBytesArray(bitmap); } - function countNumOnes(uint256 n) external pure returns (uint16) { + function countNumOnes( + uint256 n + ) external pure returns (uint16) { return BitmapUtils.countNumOnes(n); } @@ -29,7 +37,9 @@ contract BitmapUtilsWrapper { return BitmapUtils.setBit(bitmap, bit); } - function isEmpty(uint256 bitmap) external pure returns (bool) { + function isEmpty( + uint256 bitmap + ) external pure returns (bool) { return BitmapUtils.isEmpty(bitmap); } diff --git a/test/harnesses/RegistryCoordinatorHarness.t.sol b/test/harnesses/RegistryCoordinatorHarness.t.sol index c1006682..c6b6cb3b 100644 --- a/test/harnesses/RegistryCoordinatorHarness.t.sol +++ b/test/harnesses/RegistryCoordinatorHarness.t.sol @@ -14,11 +14,22 @@ contract RegistryCoordinatorHarness is RegistryCoordinator, Test { IIndexRegistry _indexRegistry, IAllocationManager _allocationManager, IPauserRegistry _pauserRegistry - ) RegistryCoordinator(_serviceManager, _stakeRegistry, _blsApkRegistry, _indexRegistry, _allocationManager, _pauserRegistry) { + ) + RegistryCoordinator( + _serviceManager, + _stakeRegistry, + _blsApkRegistry, + _indexRegistry, + _allocationManager, + _pauserRegistry + ) + { _transferOwnership(msg.sender); } - function setQuorumCount(uint8 count) external { + function setQuorumCount( + uint8 count + ) external { quorumCount = count; } @@ -38,10 +49,7 @@ contract RegistryCoordinatorHarness is RegistryCoordinator, Test { } // @notice exposes the internal `_deregisterOperator` function, overriding all access controls - function _deregisterOperatorExternal( - address operator, - bytes calldata quorumNumbers - ) external { + function _deregisterOperatorExternal(address operator, bytes calldata quorumNumbers) external { _deregisterOperator(operator, quorumNumbers); } diff --git a/test/harnesses/StakeRegistryHarness.sol b/test/harnesses/StakeRegistryHarness.sol index 38ee15e8..4e156aac 100644 --- a/test/harnesses/StakeRegistryHarness.sol +++ b/test/harnesses/StakeRegistryHarness.sol @@ -11,10 +11,21 @@ contract StakeRegistryHarness is StakeRegistry { IAVSDirectory _avsDirectory, IAllocationManager _allocationManager, IServiceManager _serviceManager - ) StakeRegistry(_registryCoordinator, _delegationManager, _avsDirectory, _allocationManager, _serviceManager) { - } + ) + StakeRegistry( + _registryCoordinator, + _delegationManager, + _avsDirectory, + _allocationManager, + _serviceManager + ) + {} - function recordOperatorStakeUpdate(bytes32 operatorId, uint8 quorumNumber, uint96 newStake) external returns(int256) { + function recordOperatorStakeUpdate( + bytes32 operatorId, + uint8 quorumNumber, + uint96 newStake + ) external returns (int256) { return _recordOperatorStakeUpdate(operatorId, quorumNumber, newStake); } diff --git a/test/integration/CoreRegistration.t.sol b/test/integration/CoreRegistration.t.sol index 68f586a9..6599af9c 100644 --- a/test/integration/CoreRegistration.t.sol +++ b/test/integration/CoreRegistration.t.sol @@ -2,14 +2,22 @@ pragma solidity ^0.8.27; import "../utils/MockAVSDeployer.sol"; -import { AVSDirectory } from "eigenlayer-contracts/src/contracts/core/AVSDirectory.sol"; -import { IAVSDirectory, IAVSDirectoryTypes} from "eigenlayer-contracts/src/contracts/interfaces/IAVSDirectory.sol"; -import { IStrategyManager } from "eigenlayer-contracts/src/contracts/interfaces/IStrategyManager.sol"; -import { DelegationManager } from "eigenlayer-contracts/src/contracts/core/DelegationManager.sol"; -import { IDelegationManager, IDelegationManagerTypes } from "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; -import { RewardsCoordinator } from "eigenlayer-contracts/src/contracts/core/RewardsCoordinator.sol"; -import { IRewardsCoordinator } from "eigenlayer-contracts/src/contracts/interfaces/IRewardsCoordinator.sol"; -import { PermissionController } from "eigenlayer-contracts/src/contracts/permissions/PermissionController.sol"; +import {AVSDirectory} from "eigenlayer-contracts/src/contracts/core/AVSDirectory.sol"; +import { + IAVSDirectory, + IAVSDirectoryTypes +} from "eigenlayer-contracts/src/contracts/interfaces/IAVSDirectory.sol"; +import {IStrategyManager} from "eigenlayer-contracts/src/contracts/interfaces/IStrategyManager.sol"; +import {DelegationManager} from "eigenlayer-contracts/src/contracts/core/DelegationManager.sol"; +import { + IDelegationManager, + IDelegationManagerTypes +} from "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; +import {RewardsCoordinator} from "eigenlayer-contracts/src/contracts/core/RewardsCoordinator.sol"; +import {IRewardsCoordinator} from + "eigenlayer-contracts/src/contracts/interfaces/IRewardsCoordinator.sol"; +import {PermissionController} from + "eigenlayer-contracts/src/contracts/permissions/PermissionController.sol"; contract Test_CoreRegistration is MockAVSDeployer { // Contracts @@ -49,7 +57,7 @@ contract Test_CoreRegistration is MockAVSDeployer { address(this), pauserRegistry, 0, // 0 is initialPausedStatus - 50400, // Initial withdrawal delay blocks + 50_400, // Initial withdrawal delay blocks initializeStrategiesToSetDelayBlocks, initializeWithdrawalDelayBlocks ) @@ -58,7 +66,8 @@ contract Test_CoreRegistration is MockAVSDeployer { ); // Deploy New AVS Directory - AVSDirectory avsDirectoryImplementation = new AVSDirectory(delegationManager, pauserRegistry); // TODO: Fix Config + AVSDirectory avsDirectoryImplementation = + new AVSDirectory(delegationManager, pauserRegistry); // TODO: Fix Config avsDirectory = AVSDirectory( address( new TransparentUpgradeableProxy( @@ -122,7 +131,7 @@ contract Test_CoreRegistration is MockAVSDeployer { // Set operator weight in single quorum bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(MAX_QUORUM_BITMAP); - for (uint i = 0; i < quorumNumbers.length; i++) { + for (uint256 i = 0; i < quorumNumbers.length; i++) { _setOperatorWeight(operator, uint8(quorumNumbers[i]), defaultStake); } } @@ -132,11 +141,7 @@ contract Test_CoreRegistration is MockAVSDeployer { // Get operator signature ISignatureUtils.SignatureWithSaltAndExpiry memory operatorSignature = _getOperatorSignature( - operatorPrivateKey, - operator, - address(serviceManager), - emptySalt, - maxExpiry + operatorPrivateKey, operator, address(serviceManager), emptySalt, maxExpiry ); // set operator as registered in Eigenlayer @@ -144,11 +149,17 @@ contract Test_CoreRegistration is MockAVSDeployer { // Register operator cheats.prank(operator); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, operatorSignature); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, operatorSignature + ); // Check operator is registered - IAVSDirectoryTypes.OperatorAVSRegistrationStatus operatorStatus = avsDirectory.avsOperatorStatus(address(serviceManager), operator); - assertEq(uint8(operatorStatus), uint8(IAVSDirectoryTypes.OperatorAVSRegistrationStatus.REGISTERED)); + IAVSDirectoryTypes.OperatorAVSRegistrationStatus operatorStatus = + avsDirectory.avsOperatorStatus(address(serviceManager), operator); + assertEq( + uint8(operatorStatus), + uint8(IAVSDirectoryTypes.OperatorAVSRegistrationStatus.REGISTERED) + ); } function test_deregisterOperator_coreStateChanges() public { @@ -161,8 +172,12 @@ contract Test_CoreRegistration is MockAVSDeployer { registryCoordinator.deregisterOperator(quorumNumbers); // Check operator is deregistered - IAVSDirectoryTypes.OperatorAVSRegistrationStatus operatorStatus = avsDirectory.avsOperatorStatus(address(serviceManager), operator); - assertEq(uint8(operatorStatus), uint8(IAVSDirectoryTypes.OperatorAVSRegistrationStatus.UNREGISTERED)); + IAVSDirectoryTypes.OperatorAVSRegistrationStatus operatorStatus = + avsDirectory.avsOperatorStatus(address(serviceManager), operator); + assertEq( + uint8(operatorStatus), + uint8(IAVSDirectoryTypes.OperatorAVSRegistrationStatus.UNREGISTERED) + ); } function test_deregisterOperator_notGloballyDeregistered() public { @@ -177,8 +192,12 @@ contract Test_CoreRegistration is MockAVSDeployer { registryCoordinator.deregisterOperator(quorumNumbers); // Check operator is still registered - IAVSDirectoryTypes.OperatorAVSRegistrationStatus operatorStatus = avsDirectory.avsOperatorStatus(address(serviceManager), operator); - assertEq(uint8(operatorStatus), uint8(IAVSDirectoryTypes.OperatorAVSRegistrationStatus.REGISTERED)); + IAVSDirectoryTypes.OperatorAVSRegistrationStatus operatorStatus = + avsDirectory.avsOperatorStatus(address(serviceManager), operator); + assertEq( + uint8(operatorStatus), + uint8(IAVSDirectoryTypes.OperatorAVSRegistrationStatus.REGISTERED) + ); } function test_setMetadataURI_fail_notServiceManagerOwner() public { @@ -199,14 +218,12 @@ contract Test_CoreRegistration is MockAVSDeployer { } // Utils - function _registerOperator(bytes memory quorumNumbers) internal { + function _registerOperator( + bytes memory quorumNumbers + ) internal { // Get operator signature ISignatureUtils.SignatureWithSaltAndExpiry memory operatorSignature = _getOperatorSignature( - operatorPrivateKey, - operator, - address(serviceManager), - emptySalt, - maxExpiry + operatorPrivateKey, operator, address(serviceManager), emptySalt, maxExpiry ); // set operator as registered in Eigenlayer @@ -214,7 +231,9 @@ contract Test_CoreRegistration is MockAVSDeployer { // Register operator cheats.prank(operator); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, operatorSignature); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, operatorSignature + ); } function _getOperatorSignature( @@ -227,11 +246,12 @@ contract Test_CoreRegistration is MockAVSDeployer { operatorSignature.salt = salt; operatorSignature.expiry = expiry; { - bytes32 digestHash = avsDirectory.calculateOperatorAVSRegistrationDigestHash(operatorToSign, avs, salt, expiry); + bytes32 digestHash = avsDirectory.calculateOperatorAVSRegistrationDigestHash( + operatorToSign, avs, salt, expiry + ); (uint8 v, bytes32 r, bytes32 s) = cheats.sign(_operatorPrivateKey, digestHash); operatorSignature.signature = abi.encodePacked(r, s, v); } return operatorSignature; } - } diff --git a/test/integration/IntegrationBase.t.sol b/test/integration/IntegrationBase.t.sol index 0baf32b4..15371667 100644 --- a/test/integration/IntegrationBase.t.sol +++ b/test/integration/IntegrationBase.t.sol @@ -14,7 +14,6 @@ import "test/integration/TimeMachine.t.sol"; import "test/integration/User.t.sol"; abstract contract IntegrationBase is IntegrationConfig { - using Strings for *; using BitmapUtils for *; using BN254 for *; @@ -37,13 +36,15 @@ abstract contract IntegrationBase is IntegrationConfig { } function assert_HasRegisteredStatus(User user, string memory err) internal { - IRegistryCoordinator.OperatorStatus status = registryCoordinator.getOperatorStatus(address(user)); + IRegistryCoordinator.OperatorStatus status = + registryCoordinator.getOperatorStatus(address(user)); assertTrue(status == IRegistryCoordinator.OperatorStatus.REGISTERED, err); } function assert_HasDeregisteredStatus(User user, string memory err) internal { - IRegistryCoordinator.OperatorStatus status = registryCoordinator.getOperatorStatus(address(user)); + IRegistryCoordinator.OperatorStatus status = + registryCoordinator.getOperatorStatus(address(user)); assertTrue(status == IRegistryCoordinator.OperatorStatus.DEREGISTERED, err); } @@ -54,10 +55,14 @@ abstract contract IntegrationBase is IntegrationConfig { assertTrue(bitmap == 0, err); } - function assert_NotRegisteredForQuorums(User user, bytes memory quorums, string memory err) internal { + function assert_NotRegisteredForQuorums( + User user, + bytes memory quorums, + string memory err + ) internal { uint192 bitmap = registryCoordinator.getCurrentQuorumBitmap(user.operatorId()); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { uint8 quorum = uint8(quorums[i]); assertFalse(bitmap.isSet(quorum), err); @@ -65,7 +70,11 @@ abstract contract IntegrationBase is IntegrationConfig { } /// @dev Checks that the user's current bitmap includes ALL of these quorums - function assert_IsRegisteredForQuorums(User user, bytes memory quorums, string memory err) internal { + function assert_IsRegisteredForQuorums( + User user, + bytes memory quorums, + string memory err + ) internal { uint192 currentBitmap = registryCoordinator.getCurrentQuorumBitmap(user.operatorId()); uint192 subsetBitmap = uint192(quorums.orderedBytesArrayToBitmap()); @@ -75,7 +84,7 @@ abstract contract IntegrationBase is IntegrationConfig { /// @dev Checks whether each of the quorums has been initialized in the RegistryCoordinator function assert_QuorumsExist(bytes memory quorums, string memory err) internal { uint8 count = registryCoordinator.quorumCount(); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { uint8 quorum = uint8(quorums[i]); assertTrue(quorum < count, err); @@ -85,7 +94,7 @@ abstract contract IntegrationBase is IntegrationConfig { /// BLSApkRegistry: function assert_NoRegisteredPubkey(User user, string memory err) internal { - (uint pubkeyX, uint pubkeyY) = blsApkRegistry.operatorToPubkey(address(user)); + (uint256 pubkeyX, uint256 pubkeyY) = blsApkRegistry.operatorToPubkey(address(user)); bytes32 pubkeyHash = blsApkRegistry.operatorToPubkeyHash(address(user)); assertEq(pubkeyX, 0, err); @@ -95,7 +104,7 @@ abstract contract IntegrationBase is IntegrationConfig { function assert_HasRegisteredPubkey(User user, string memory err) internal { BN254.G1Point memory expectedPubkey = user.pubkeyG1(); - (uint actualPkX, uint actualPkY) = blsApkRegistry.operatorToPubkey(address(user)); + (uint256 actualPkX, uint256 actualPkY) = blsApkRegistry.operatorToPubkey(address(user)); bytes32 expectedHash = expectedPubkey.hashG1Point(); bytes32 actualHash = blsApkRegistry.operatorToPubkeyHash(address(user)); @@ -113,7 +122,7 @@ abstract contract IntegrationBase is IntegrationConfig { function assert_NoExistingStake(User user, bytes memory quorums, string memory err) internal { bytes32 operatorId = user.operatorId(); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { uint8 quorum = uint8(quorums[i]); uint96 curStake = stakeRegistry.getCurrentStake(operatorId, quorum); @@ -123,8 +132,12 @@ abstract contract IntegrationBase is IntegrationConfig { } /// @dev Checks that the user meets the minimum weight required for each quorum - function assert_MeetsMinimumWeight(User user, bytes memory quorums, string memory err) internal { - for (uint i = 0; i < quorums.length; i++) { + function assert_MeetsMinimumWeight( + User user, + bytes memory quorums, + string memory err + ) internal { + for (uint256 i = 0; i < quorums.length; i++) { uint8 quorum = uint8(quorums[i]); uint96 minimum = stakeRegistry.minimumStakeForQuorum(quorum); @@ -135,10 +148,14 @@ abstract contract IntegrationBase is IntegrationConfig { } /// @dev Checks that the user meets the minimum stake required for each quorum - function assert_HasAtLeastMinimumStake(User user, bytes memory quorums, string memory err) internal { + function assert_HasAtLeastMinimumStake( + User user, + bytes memory quorums, + string memory err + ) internal { bytes32 operatorId = user.operatorId(); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { uint8 quorum = uint8(quorums[i]); uint96 minimum = stakeRegistry.minimumStakeForQuorum(quorum); @@ -153,10 +170,11 @@ abstract contract IntegrationBase is IntegrationConfig { /// @dev Checks that we're specifically UNDER the max operator count, i.e. we are allowing /// at least one more operator to register function assert_BelowMaxOperators(bytes memory quorums, string memory err) internal { - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { uint8 quorum = uint8(quorums[i]); - uint32 maxOperatorCount = registryCoordinator.getOperatorSetParams(quorum).maxOperatorCount; + uint32 maxOperatorCount = + registryCoordinator.getOperatorSetParams(quorum).maxOperatorCount; uint32 curOperatorCount = indexRegistry.totalOperatorsForQuorum(quorum); assertTrue(curOperatorCount < maxOperatorCount, err); @@ -166,27 +184,35 @@ abstract contract IntegrationBase is IntegrationConfig { /// AVSDirectory: function assert_NotRegisteredToAVS(User operator, string memory err) internal { - IAVSDirectoryTypes.OperatorAVSRegistrationStatus status = avsDirectory.avsOperatorStatus(address(serviceManager), address(operator)); + IAVSDirectoryTypes.OperatorAVSRegistrationStatus status = + avsDirectory.avsOperatorStatus(address(serviceManager), address(operator)); assertTrue(status == IAVSDirectoryTypes.OperatorAVSRegistrationStatus.UNREGISTERED, err); } function assert_IsRegisteredToAVS(User operator, string memory err) internal { - IAVSDirectory.OperatorAVSRegistrationStatus status = avsDirectory.avsOperatorStatus(address(serviceManager), address(operator)); + IAVSDirectory.OperatorAVSRegistrationStatus status = + avsDirectory.avsOperatorStatus(address(serviceManager), address(operator)); assertTrue(status == IAVSDirectoryTypes.OperatorAVSRegistrationStatus.REGISTERED, err); } - /******************************************************************************* - SNAPSHOT ASSERTIONS (MIDDLEWARE) - TIME TRAVELERS ONLY BEYOND THIS POINT - *******************************************************************************/ + /** + * + * SNAPSHOT ASSERTIONS (MIDDLEWARE) + * TIME TRAVELERS ONLY BEYOND THIS POINT + * + */ /// @dev Checks that `quorums` were added to the user's registered quorums /// NOTE: This means curBitmap - prevBitmap = quorums - function assert_Snap_Registered_ForQuorums(User user, bytes memory quorums, string memory err) internal { + function assert_Snap_Registered_ForQuorums( + User user, + bytes memory quorums, + string memory err + ) internal { bytes32 operatorId = user.operatorId(); - uint quorumsAdded = quorums.orderedBytesArrayToBitmap(); + uint256 quorumsAdded = quorums.orderedBytesArrayToBitmap(); uint192 curBitmap = _getQuorumBitmap(operatorId); uint192 prevBitmap = _getPrevQuorumBitmap(operatorId); @@ -195,9 +221,13 @@ abstract contract IntegrationBase is IntegrationConfig { assertTrue(curBitmap == prevBitmap.plus(quorumsAdded), err); } - function assert_Snap_Deregistered_FromQuorums(User user, bytes memory quorums, string memory err) internal { + function assert_Snap_Deregistered_FromQuorums( + User user, + bytes memory quorums, + string memory err + ) internal { bytes32 operatorId = user.operatorId(); - uint quorumsRemoved = quorums.orderedBytesArrayToBitmap(); + uint256 quorumsRemoved = quorums.orderedBytesArrayToBitmap(); uint192 curBitmap = _getQuorumBitmap(operatorId); uint192 prevBitmap = _getPrevQuorumBitmap(operatorId); @@ -230,26 +260,34 @@ abstract contract IntegrationBase is IntegrationConfig { } /// @dev Check that the user's pubkey was added to each quorum's apk - function assert_Snap_Added_QuorumApk(User user, bytes memory quorums, string memory err) internal { + function assert_Snap_Added_QuorumApk( + User user, + bytes memory quorums, + string memory err + ) internal { BN254.G1Point memory userPubkey = user.pubkeyG1(); BN254.G1Point[] memory curApks = _getQuorumApks(quorums); BN254.G1Point[] memory prevApks = _getPrevQuorumApks(quorums); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { BN254.G1Point memory expectedApk = prevApks[i].plus(userPubkey); assertEq(expectedApk.X, curApks[i].X, err); assertEq(expectedApk.Y, curApks[i].Y, err); } } - function assert_Snap_Removed_QuorumApk(User user, bytes memory quorums, string memory err) internal { + function assert_Snap_Removed_QuorumApk( + User user, + bytes memory quorums, + string memory err + ) internal { BN254.G1Point memory userPubkey = user.pubkeyG1(); BN254.G1Point[] memory curApks = _getQuorumApks(quorums); BN254.G1Point[] memory prevApks = _getPrevQuorumApks(quorums); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { BN254.G1Point memory expectedApk = prevApks[i].plus(userPubkey.negate()); assertEq(expectedApk.X, curApks[i].X, err); assertEq(expectedApk.Y, curApks[i].Y, err); @@ -260,7 +298,7 @@ abstract contract IntegrationBase is IntegrationConfig { BN254.G1Point[] memory curApks = _getQuorumApks(quorums); BN254.G1Point[] memory prevApks = _getPrevQuorumApks(quorums); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { assertEq(curApks[i].X, prevApks[i].X, err); assertEq(curApks[i].Y, prevApks[i].Y, err); } @@ -275,7 +313,11 @@ abstract contract IntegrationBase is IntegrationConfig { string memory err ) internal { // Sanity check input lengths - assertEq(churnedOperators.length, churnedQuorums.length, "assert_Snap_Churned_QuorumApk: input length mismatch"); + assertEq( + churnedOperators.length, + churnedQuorums.length, + "assert_Snap_Churned_QuorumApk: input length mismatch" + ); BN254.G1Point memory incomingPubkey = incomingOperator.pubkeyG1(); @@ -285,13 +327,11 @@ abstract contract IntegrationBase is IntegrationConfig { // For each churned quorum, check: // - that the corresponding churned operator pubkey was removed // - ... AND that the incomingOperator pubkey was added - for (uint i = 0; i < churnedQuorums.length; i++) { + for (uint256 i = 0; i < churnedQuorums.length; i++) { BN254.G1Point memory churnedPubkey = churnedOperators[i].pubkeyG1(); - BN254.G1Point memory expectedApk - = prevApks[i] - .plus(churnedPubkey.negate()) - .plus(incomingPubkey); + BN254.G1Point memory expectedApk = + prevApks[i].plus(churnedPubkey.negate()).plus(incomingPubkey); assertEq(expectedApk.X, curApks[i].X, err); assertEq(expectedApk.Y, curApks[i].Y, err); @@ -311,7 +351,7 @@ abstract contract IntegrationBase is IntegrationConfig { uint96[] memory curTotalStakes = _getTotalStakes(quorums); uint96[] memory prevTotalStakes = _getPrevTotalStakes(quorums); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { assertEq(curOperatorStakes[i], prevOperatorStakes[i] + addedWeights[i], err); assertEq(curTotalStakes[i], prevTotalStakes[i] + addedWeights[i], err); } @@ -338,12 +378,16 @@ abstract contract IntegrationBase is IntegrationConfig { string memory err ) internal { // Sanity check input lengths - assertEq(churnedOperators.length, churnedQuorums.length, "assert_Snap_Churned_OperatorWeight: input length mismatch"); + assertEq( + churnedOperators.length, + churnedQuorums.length, + "assert_Snap_Churned_OperatorWeight: input length mismatch" + ); // Get weights added and removed for each quorum uint96[] memory addedWeights = _getWeights(incomingOperator, churnedQuorums); uint96[] memory removedWeights = new uint96[](churnedOperators.length); - for (uint i = 0; i < churnedOperators.length; i++) { + for (uint256 i = 0; i < churnedOperators.length; i++) { removedWeights[i] = _getWeight(uint8(churnedQuorums[i]), churnedOperators[i]); } @@ -355,9 +399,11 @@ abstract contract IntegrationBase is IntegrationConfig { // For each quorum, check that the incoming operator's individual stake was increased by addedWeights // and that the total stake is plus addedWeights and minus removedWeights - for (uint i = 0; i < churnedQuorums.length; i++) { + for (uint256 i = 0; i < churnedQuorums.length; i++) { assertEq(curIncomingOpStakes[i], prevIncomingOpStakes[i] + addedWeights[i], err); - assertEq(curTotalStakes[i], prevTotalStakes[i] + addedWeights[i] - removedWeights[i], err); + assertEq( + curTotalStakes[i], prevTotalStakes[i] + addedWeights[i] - removedWeights[i], err + ); } } @@ -369,7 +415,7 @@ abstract contract IntegrationBase is IntegrationConfig { uint96[] memory curStakes = _getStakes(user, quorums); uint96[] memory prevStakes = _getPrevStakes(user, quorums); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { assertEq(curStakes[i], prevStakes[i], err); } } @@ -383,7 +429,7 @@ abstract contract IntegrationBase is IntegrationConfig { uint96[] memory curWeights = _getWeights(user, quorums); uint96[] memory prevWeights = _getPrevWeights(user, quorums); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { assertTrue(curWeights[i] >= prevWeights[i], err); } } @@ -397,7 +443,7 @@ abstract contract IntegrationBase is IntegrationConfig { uint96[] memory curWeights = _getWeights(user, quorums); uint96[] memory prevWeights = _getPrevWeights(user, quorums); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { assertTrue(curWeights[i] <= prevWeights[i], err); } } @@ -410,7 +456,7 @@ abstract contract IntegrationBase is IntegrationConfig { uint96[] memory curWeights = _getWeights(user, quorums); uint96[] memory prevWeights = _getPrevWeights(user, quorums); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { assertEq(curWeights[i], prevWeights[i], err); } } @@ -425,7 +471,7 @@ abstract contract IntegrationBase is IntegrationConfig { uint96[] memory curTotalStakes = _getTotalStakes(quorums); uint96[] memory prevTotalStakes = _getPrevTotalStakes(quorums); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { assertEq(curTotalStakes[i], prevTotalStakes[i] + addedWeights[i], err); } } @@ -441,19 +487,16 @@ abstract contract IntegrationBase is IntegrationConfig { uint96[] memory curTotalStakes = _getTotalStakes(quorums); uint96[] memory prevTotalStakes = _getPrevTotalStakes(quorums); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { assertEq(curTotalStakes[i], prevTotalStakes[i] - prevOperatorStakes[i], err); } } - function assert_Snap_Unchanged_TotalStake( - bytes memory quorums, - string memory err - ) internal { + function assert_Snap_Unchanged_TotalStake(bytes memory quorums, string memory err) internal { uint96[] memory curTotalStakes = _getTotalStakes(quorums); uint96[] memory prevTotalStakes = _getPrevTotalStakes(quorums); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { assertEq(curTotalStakes[i], prevTotalStakes[i], err); } } @@ -463,7 +506,7 @@ abstract contract IntegrationBase is IntegrationConfig { uint32[] memory curOperatorCounts = _getOperatorCounts(quorums); uint32[] memory prevOperatorCounts = _getPrevOperatorCounts(quorums); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { assertEq(curOperatorCounts[i], prevOperatorCounts[i] + 1, err); } } @@ -472,16 +515,19 @@ abstract contract IntegrationBase is IntegrationConfig { uint32[] memory curOperatorCounts = _getOperatorCounts(quorums); uint32[] memory prevOperatorCounts = _getPrevOperatorCounts(quorums); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { assertEq(curOperatorCounts[i], prevOperatorCounts[i] - 1, err); } } - function assert_Snap_Unchanged_OperatorCount(bytes memory quorums, string memory err) internal { + function assert_Snap_Unchanged_OperatorCount( + bytes memory quorums, + string memory err + ) internal { uint32[] memory curOperatorCounts = _getOperatorCounts(quorums); uint32[] memory prevOperatorCounts = _getPrevOperatorCounts(quorums); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { assertEq(curOperatorCounts[i], prevOperatorCounts[i], err); } } @@ -497,7 +543,7 @@ abstract contract IntegrationBase is IntegrationConfig { bytes32[][] memory curOperatorLists = _getOperatorLists(quorums); bytes32[][] memory prevOperatorLists = _getPrevOperatorLists(quorums); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { assertEq(curOperatorLists[i].length, prevOperatorLists[i].length + 1, err); assertTrue(_contains(curOperatorLists[i], operator), err); @@ -516,7 +562,7 @@ abstract contract IntegrationBase is IntegrationConfig { bytes32[][] memory curOperatorLists = _getOperatorLists(quorums); bytes32[][] memory prevOperatorLists = _getPrevOperatorLists(quorums); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { assertEq(curOperatorLists[i].length, prevOperatorLists[i].length - 1, err); assertFalse(_contains(curOperatorLists[i], operator), err); @@ -524,7 +570,10 @@ abstract contract IntegrationBase is IntegrationConfig { } } - function assert_Snap_Unchanged_OperatorListEntry(bytes memory quorums, string memory err) internal { + function assert_Snap_Unchanged_OperatorListEntry( + bytes memory quorums, + string memory err + ) internal { bytes32[][] memory curOperatorLists = _getOperatorLists(quorums); bytes32[][] memory prevOperatorLists = _getPrevOperatorLists(quorums); @@ -545,12 +594,16 @@ abstract contract IntegrationBase is IntegrationConfig { string memory err ) internal { // Sanity check input lengths - assertEq(churnedOperators.length, churnedQuorums.length, "assert_Snap_Replaced_OperatorListEntries: input length mismatch"); + assertEq( + churnedOperators.length, + churnedQuorums.length, + "assert_Snap_Replaced_OperatorListEntries: input length mismatch" + ); bytes32[][] memory curOperatorLists = _getOperatorLists(churnedQuorums); bytes32[][] memory prevOperatorLists = _getPrevOperatorLists(churnedQuorums); - for (uint i = 0; i < churnedQuorums.length; i++) { + for (uint256 i = 0; i < churnedQuorums.length; i++) { assertEq(curOperatorLists[i].length, prevOperatorLists[i].length, err); // check incomingOperator was added @@ -563,25 +616,27 @@ abstract contract IntegrationBase is IntegrationConfig { } } - /******************************************************************************* - SNAPSHOT ASSERTIONS (CORE) - TIME TRAVELERS ONLY BEYOND THIS POINT - *******************************************************************************/ + /** + * + * SNAPSHOT ASSERTIONS (CORE) + * TIME TRAVELERS ONLY BEYOND THIS POINT + * + */ /// @dev Check that the operator has `addedShares` additional operator shares // for each strategy since the last snapshot function assert_Snap_Added_OperatorShares( User operator, IStrategy[] memory strategies, - uint[] memory addedShares, + uint256[] memory addedShares, string memory err ) internal { - uint[] memory curShares = _getOperatorShares(operator, strategies); + uint256[] memory curShares = _getOperatorShares(operator, strategies); // Use timewarp to get previous operator shares - uint[] memory prevShares = _getPrevOperatorShares(operator, strategies); + uint256[] memory prevShares = _getPrevOperatorShares(operator, strategies); // For each strategy, check (prev + added == cur) - for (uint i = 0; i < strategies.length; i++) { + for (uint256 i = 0; i < strategies.length; i++) { assertEq(prevShares[i] + addedShares[i], curShares[i], err); } } @@ -594,12 +649,12 @@ abstract contract IntegrationBase is IntegrationConfig { uint256[] memory removedShares, string memory err ) internal { - uint[] memory curShares = _getOperatorShares(operator, strategies); + uint256[] memory curShares = _getOperatorShares(operator, strategies); // Use timewarp to get previous operator shares - uint[] memory prevShares = _getPrevOperatorShares(operator, strategies); + uint256[] memory prevShares = _getPrevOperatorShares(operator, strategies); // For each strategy, check (prev - removed == cur) - for (uint i = 0; i < strategies.length; i++) { + for (uint256 i = 0; i < strategies.length; i++) { assertEq(prevShares[i] - removedShares[i], curShares[i], err); } } @@ -609,15 +664,15 @@ abstract contract IntegrationBase is IntegrationConfig { function assert_Snap_Added_StakerShares( User staker, IStrategy[] memory strategies, - uint[] memory addedShares, + uint256[] memory addedShares, string memory err ) internal { - uint[] memory curShares = _getStakerShares(staker, strategies); + uint256[] memory curShares = _getStakerShares(staker, strategies); // Use timewarp to get previous staker shares - uint[] memory prevShares = _getPrevStakerShares(staker, strategies); + uint256[] memory prevShares = _getPrevStakerShares(staker, strategies); // For each strategy, check (prev + added == cur) - for (uint i = 0; i < strategies.length; i++) { + for (uint256 i = 0; i < strategies.length; i++) { assertEq(prevShares[i] + addedShares[i], curShares[i], err); } } @@ -627,15 +682,15 @@ abstract contract IntegrationBase is IntegrationConfig { function assert_Snap_Removed_StakerShares( User staker, IStrategy[] memory strategies, - uint[] memory removedShares, + uint256[] memory removedShares, string memory err ) internal { - uint[] memory curShares = _getStakerShares(staker, strategies); + uint256[] memory curShares = _getStakerShares(staker, strategies); // Use timewarp to get previous staker shares - uint[] memory prevShares = _getPrevStakerShares(staker, strategies); + uint256[] memory prevShares = _getPrevStakerShares(staker, strategies); // For each strategy, check (prev - removed == cur) - for (uint i = 0; i < strategies.length; i++) { + for (uint256 i = 0; i < strategies.length; i++) { assertEq(prevShares[i] - removedShares[i], curShares[i], err); } } @@ -645,41 +700,45 @@ abstract contract IntegrationBase is IntegrationConfig { IDelegationManager.Withdrawal[] memory withdrawals, string memory err ) internal { - uint curQueuedWithdrawals = _getCumulativeWithdrawals(staker); + uint256 curQueuedWithdrawals = _getCumulativeWithdrawals(staker); // Use timewarp to get previous cumulative withdrawals - uint prevQueuedWithdrawals = _getPrevCumulativeWithdrawals(staker); + uint256 prevQueuedWithdrawals = _getPrevCumulativeWithdrawals(staker); assertEq(prevQueuedWithdrawals + withdrawals.length, curQueuedWithdrawals, err); } - function assert_Snap_Added_QueuedWithdrawal( - User staker, - string memory err - ) internal { - uint curQueuedWithdrawal = _getCumulativeWithdrawals(staker); + function assert_Snap_Added_QueuedWithdrawal(User staker, string memory err) internal { + uint256 curQueuedWithdrawal = _getCumulativeWithdrawals(staker); // Use timewarp to get previous cumulative withdrawals - uint prevQueuedWithdrawal = _getPrevCumulativeWithdrawals(staker); + uint256 prevQueuedWithdrawal = _getPrevCumulativeWithdrawals(staker); assertEq(prevQueuedWithdrawal + 1, curQueuedWithdrawal, err); } - /******************************************************************************* - UTILITY METHODS - *******************************************************************************/ - - function _calcRemaining(bytes memory start, bytes memory removed) internal pure returns (bytes memory) { - uint startBM = start.orderedBytesArrayToBitmap(); - uint removeBM = removed.orderedBytesArrayToBitmap(); + /** + * + * UTILITY METHODS + * + */ + function _calcRemaining( + bytes memory start, + bytes memory removed + ) internal pure returns (bytes memory) { + uint256 startBM = start.orderedBytesArrayToBitmap(); + uint256 removeBM = removed.orderedBytesArrayToBitmap(); return startBM.minus(removeBM).bitmapToBytesArray(); } /// @dev For some strategies/underlying token balances, calculate the expected shares received /// from depositing all tokens - function _calculateExpectedShares(IStrategy[] memory strategies, uint[] memory tokenBalances) internal returns (uint[] memory) { - uint[] memory expectedShares = new uint[](strategies.length); + function _calculateExpectedShares( + IStrategy[] memory strategies, + uint256[] memory tokenBalances + ) internal returns (uint256[] memory) { + uint256[] memory expectedShares = new uint256[](strategies.length); - for (uint i = 0; i < strategies.length; i++) { + for (uint256 i = 0; i < strategies.length; i++) { IStrategy strat = strategies[i]; expectedShares[i] = strat.underlyingToShares(tokenBalances[i]); @@ -690,10 +749,13 @@ abstract contract IntegrationBase is IntegrationConfig { /// @dev For some strategies/underlying token balances, calculate the expected shares received /// from depositing all tokens - function _calculateExpectedTokens(IStrategy[] memory strategies, uint[] memory shares) internal returns (uint[] memory) { - uint[] memory expectedTokens = new uint[](strategies.length); + function _calculateExpectedTokens( + IStrategy[] memory strategies, + uint256[] memory shares + ) internal returns (uint256[] memory) { + uint256[] memory expectedTokens = new uint256[](strategies.length); - for (uint i = 0; i < strategies.length; i++) { + for (uint256 i = 0; i < strategies.length; i++) { IStrategy strat = strategies[i]; expectedTokens[i] = strat.sharesToUnderlying(shares[i]); @@ -703,10 +765,12 @@ abstract contract IntegrationBase is IntegrationConfig { } /// @dev Converts a list of strategies to underlying tokens - function _getUnderlyingTokens(IStrategy[] memory strategies) internal view returns (IERC20[] memory) { + function _getUnderlyingTokens( + IStrategy[] memory strategies + ) internal view returns (IERC20[] memory) { IERC20[] memory tokens = new IERC20[](strategies.length); - for (uint i = 0; i < tokens.length; i++) { + for (uint256 i = 0; i < tokens.length; i++) { IStrategy strat = strategies[i]; tokens[i] = strat.underlyingToken(); @@ -718,7 +782,7 @@ abstract contract IntegrationBase is IntegrationConfig { function _contains(bytes32[] memory operatorIds, User operator) internal view returns (bool) { bytes32 checkId = operator.operatorId(); - for (uint i = 0; i < operatorIds.length; i++) { + for (uint256 i = 0; i < operatorIds.length; i++) { if (operatorIds[i] == checkId) { return true; } @@ -727,12 +791,13 @@ abstract contract IntegrationBase is IntegrationConfig { return false; } - /******************************************************************************* - TIMEWARP GETTERS - *******************************************************************************/ - + /** + * + * TIMEWARP GETTERS + * + */ modifier timewarp() { - uint curState = timeMachine.warpToLast(); + uint256 curState = timeMachine.warpToLast(); _; timeMachine.warpToPresent(curState); } @@ -743,15 +808,18 @@ abstract contract IntegrationBase is IntegrationConfig { function _getPrevOperatorShares( User operator, IStrategy[] memory strategies - ) internal timewarp() returns (uint[] memory) { + ) internal timewarp returns (uint256[] memory) { return _getOperatorShares(operator, strategies); } /// @dev Looks up each strategy and returns a list of the operator's shares - function _getOperatorShares(User operator, IStrategy[] memory strategies) internal view returns (uint[] memory) { - uint[] memory curShares = new uint[](strategies.length); + function _getOperatorShares( + User operator, + IStrategy[] memory strategies + ) internal view returns (uint256[] memory) { + uint256[] memory curShares = new uint256[](strategies.length); - for (uint i = 0; i < strategies.length; i++) { + for (uint256 i = 0; i < strategies.length; i++) { curShares[i] = delegationManager.operatorShares(address(operator), strategies[i]); } @@ -762,15 +830,18 @@ abstract contract IntegrationBase is IntegrationConfig { function _getPrevStakerShares( User staker, IStrategy[] memory strategies - ) internal timewarp() returns (uint[] memory) { + ) internal timewarp returns (uint256[] memory) { return _getStakerShares(staker, strategies); } /// @dev Looks up each strategy and returns a list of the staker's shares - function _getStakerShares(User staker, IStrategy[] memory strategies) internal view returns (uint[] memory) { - uint[] memory curShares = new uint[](strategies.length); + function _getStakerShares( + User staker, + IStrategy[] memory strategies + ) internal view returns (uint256[] memory) { + uint256[] memory curShares = new uint256[](strategies.length); - for (uint i = 0; i < strategies.length; i++) { + for (uint256 i = 0; i < strategies.length; i++) { IStrategy strat = strategies[i]; curShares[i] = strategyManager.stakerDepositShares(address(staker), strat); @@ -779,45 +850,61 @@ abstract contract IntegrationBase is IntegrationConfig { return curShares; } - function _getPrevCumulativeWithdrawals(User staker) internal timewarp() returns (uint) { + function _getPrevCumulativeWithdrawals( + User staker + ) internal timewarp returns (uint256) { return _getCumulativeWithdrawals(staker); } - function _getCumulativeWithdrawals(User staker) internal view returns (uint) { + function _getCumulativeWithdrawals( + User staker + ) internal view returns (uint256) { return delegationManager.cumulativeWithdrawalsQueued(address(staker)); } /// RegistryCoordinator: - function _getOperatorInfo(User user) internal view returns (IRegistryCoordinator.OperatorInfo memory) { + function _getOperatorInfo( + User user + ) internal view returns (IRegistryCoordinator.OperatorInfo memory) { return registryCoordinator.getOperator(address(user)); } - function _getPrevOperatorInfo(User user) internal timewarp() returns (IRegistryCoordinator.OperatorInfo memory) { + function _getPrevOperatorInfo( + User user + ) internal timewarp returns (IRegistryCoordinator.OperatorInfo memory) { return _getOperatorInfo(user); } - function _getQuorumBitmap(bytes32 operatorId) internal view returns (uint192) { + function _getQuorumBitmap( + bytes32 operatorId + ) internal view returns (uint192) { return registryCoordinator.getCurrentQuorumBitmap(operatorId); } - function _getPrevQuorumBitmap(bytes32 operatorId) internal timewarp() returns (uint192) { + function _getPrevQuorumBitmap( + bytes32 operatorId + ) internal timewarp returns (uint192) { return _getQuorumBitmap(operatorId); } /// BLSApkRegistry: - function _getQuorumApks(bytes memory quorums) internal view returns (BN254.G1Point[] memory) { + function _getQuorumApks( + bytes memory quorums + ) internal view returns (BN254.G1Point[] memory) { BN254.G1Point[] memory apks = new BN254.G1Point[](quorums.length); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { apks[i] = blsApkRegistry.getApk(uint8(quorums[i])); } return apks; } - function _getPrevQuorumApks(bytes memory quorums) internal timewarp() returns (BN254.G1Point[] memory) { + function _getPrevQuorumApks( + bytes memory quorums + ) internal timewarp returns (BN254.G1Point[] memory) { return _getQuorumApks(quorums); } @@ -827,28 +914,34 @@ abstract contract IntegrationBase is IntegrationConfig { bytes32 operatorId = user.operatorId(); uint96[] memory stakes = new uint96[](quorums.length); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { stakes[i] = stakeRegistry.getCurrentStake(operatorId, uint8(quorums[i])); } return stakes; } - function _getPrevStakes(User user, bytes memory quorums) internal timewarp() returns (uint96[] memory) { + function _getPrevStakes( + User user, + bytes memory quorums + ) internal timewarp returns (uint96[] memory) { return _getStakes(user, quorums); } function _getWeights(User user, bytes memory quorums) internal view returns (uint96[] memory) { uint96[] memory weights = new uint96[](quorums.length); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { weights[i] = stakeRegistry.weightOfOperatorForQuorum(uint8(quorums[i]), address(user)); } return weights; } - function _getPrevWeights(User user, bytes memory quorums) internal timewarp() returns (uint96[] memory) { + function _getPrevWeights( + User user, + bytes memory quorums + ) internal timewarp returns (uint96[] memory) { return _getWeights(user, quorums); } @@ -860,7 +953,7 @@ abstract contract IntegrationBase is IntegrationConfig { uint96[] memory addedWeights = new uint96[](quorums.length); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { uint96 curWeight = curWeights[i]; uint96 prevWeight = prevWeights[i]; @@ -874,47 +967,60 @@ abstract contract IntegrationBase is IntegrationConfig { return addedWeights; } - function _getTotalStakes(bytes memory quorums) internal view returns (uint96[] memory) { + function _getTotalStakes( + bytes memory quorums + ) internal view returns (uint96[] memory) { uint96[] memory stakes = new uint96[](quorums.length); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { stakes[i] = stakeRegistry.getCurrentTotalStake(uint8(quorums[i])); } return stakes; } - function _getPrevTotalStakes(bytes memory quorums) internal timewarp() returns (uint96[] memory) { + function _getPrevTotalStakes( + bytes memory quorums + ) internal timewarp returns (uint96[] memory) { return _getTotalStakes(quorums); } /// IndexRegistry: - function _getOperatorCounts(bytes memory quorums) internal view returns (uint32[] memory) { + function _getOperatorCounts( + bytes memory quorums + ) internal view returns (uint32[] memory) { uint32[] memory operatorCounts = new uint32[](quorums.length); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { operatorCounts[i] = indexRegistry.totalOperatorsForQuorum(uint8(quorums[i])); } return operatorCounts; } - function _getPrevOperatorCounts(bytes memory quorums) internal timewarp() returns (uint32[] memory) { + function _getPrevOperatorCounts( + bytes memory quorums + ) internal timewarp returns (uint32[] memory) { return _getOperatorCounts(quorums); } - function _getOperatorLists(bytes memory quorums) internal view returns (bytes32[][] memory) { + function _getOperatorLists( + bytes memory quorums + ) internal view returns (bytes32[][] memory) { bytes32[][] memory operatorLists = new bytes32[][](quorums.length); - for (uint i = 0; i < quorums.length; i++) { - operatorLists[i] = indexRegistry.getOperatorListAtBlockNumber(uint8(quorums[i]), uint32(block.number)); + for (uint256 i = 0; i < quorums.length; i++) { + operatorLists[i] = + indexRegistry.getOperatorListAtBlockNumber(uint8(quorums[i]), uint32(block.number)); } return operatorLists; } - function _getPrevOperatorLists(bytes memory quorums) internal timewarp() returns (bytes32[][] memory) { + function _getPrevOperatorLists( + bytes memory quorums + ) internal timewarp returns (bytes32[][] memory) { return _getOperatorLists(quorums); } } diff --git a/test/integration/IntegrationChecks.t.sol b/test/integration/IntegrationChecks.t.sol index 0f2de79c..ba9c3d23 100644 --- a/test/integration/IntegrationChecks.t.sol +++ b/test/integration/IntegrationChecks.t.sol @@ -6,74 +6,75 @@ import "test/integration/User.t.sol"; /// @notice Contract that provides utility functions to reuse common test blocks & checks contract IntegrationChecks is IntegrationBase { - using BitmapUtils for *; - /******************************************************************************* - PRE-REGISTER CHECKS - *******************************************************************************/ - + /** + * + * PRE-REGISTER CHECKS + * + */ function check_Never_Registered( User operator ) internal { - _log("check_Never_Registered", operator); + _log("check_Never_Registered", operator); // RegistryCoordinator - assert_HasNoOperatorInfo(operator, - "operator should have empty id and NEVER_REGISTERED status"); - assert_EmptyQuorumBitmap(operator, - "operator already has bits in quorum bitmap"); + assert_HasNoOperatorInfo( + operator, "operator should have empty id and NEVER_REGISTERED status" + ); + assert_EmptyQuorumBitmap(operator, "operator already has bits in quorum bitmap"); // BLSApkRegistry - assert_NoRegisteredPubkey(operator, - "operator already has a registered pubkey"); + assert_NoRegisteredPubkey(operator, "operator already has a registered pubkey"); // DelegationManager - assert_NotRegisteredToAVS(operator, - "operator should not be registered to the AVS"); + assert_NotRegisteredToAVS(operator, "operator should not be registered to the AVS"); } - /******************************************************************************* - POST-REGISTER CHECKS - *******************************************************************************/ - - function check_Register_State( - User operator, - bytes memory quorums - ) internal { + /** + * + * POST-REGISTER CHECKS + * + */ + function check_Register_State(User operator, bytes memory quorums) internal { _log("check_Register_State", operator); // RegistryCoordinator - assert_HasOperatorInfoWithId(operator, - "operatorInfo should have operatorId"); - assert_HasRegisteredStatus(operator, - "operatorInfo status should be REGISTERED"); - assert_IsRegisteredForQuorums(operator, quorums, - "current operator bitmap should include quorums"); - assert_Snap_Registered_ForQuorums(operator, quorums, - "operator did not register for all quorums"); + assert_HasOperatorInfoWithId(operator, "operatorInfo should have operatorId"); + assert_HasRegisteredStatus(operator, "operatorInfo status should be REGISTERED"); + assert_IsRegisteredForQuorums( + operator, quorums, "current operator bitmap should include quorums" + ); + assert_Snap_Registered_ForQuorums( + operator, quorums, "operator did not register for all quorums" + ); // BLSApkRegistry - assert_HasRegisteredPubkey(operator, - "operator should have registered a pubkey"); - assert_Snap_Added_QuorumApk(operator, quorums, - "operator pubkey should have been added to each quorum apk"); + assert_HasRegisteredPubkey(operator, "operator should have registered a pubkey"); + assert_Snap_Added_QuorumApk( + operator, quorums, "operator pubkey should have been added to each quorum apk" + ); // StakeRegistry - assert_HasAtLeastMinimumStake(operator, quorums, - "operator should have at least the minimum stake in each quorum"); - assert_Snap_Added_OperatorWeight(operator, quorums, - "failed to add operator weight to operator and total stake in each quorum"); + assert_HasAtLeastMinimumStake( + operator, quorums, "operator should have at least the minimum stake in each quorum" + ); + assert_Snap_Added_OperatorWeight( + operator, + quorums, + "failed to add operator weight to operator and total stake in each quorum" + ); // IndexRegistry - assert_Snap_Added_OperatorCount(quorums, - "total operator count should have increased for each quorum"); - assert_Snap_Added_OperatorListEntry(operator, quorums, - "operator list should have one more entry"); + assert_Snap_Added_OperatorCount( + quorums, "total operator count should have increased for each quorum" + ); + assert_Snap_Added_OperatorListEntry( + operator, quorums, "operator list should have one more entry" + ); // AVSDirectory - assert_IsRegisteredToAVS(operator, - "operator should be registered to AVS"); + assert_IsRegisteredToAVS(operator, "operator should be registered to AVS"); } /// @dev Combines many checks of check_Register_State and check_Deregister_State @@ -86,80 +87,115 @@ contract IntegrationChecks is IntegrationBase { ) internal { _log("check_Churned_State", incomingOperator); - bytes memory combinedQuorums = - churnedQuorums - .orderedBytesArrayToBitmap() - .plus(standardQuorums.orderedBytesArrayToBitmap()) - .bitmapToBytesArray(); + bytes memory combinedQuorums = churnedQuorums.orderedBytesArrayToBitmap().plus( + standardQuorums.orderedBytesArrayToBitmap() + ).bitmapToBytesArray(); // RegistryCoordinator - assert_HasOperatorInfoWithId(incomingOperator, - "operatorInfo should have operatorId"); - assert_HasRegisteredStatus(incomingOperator, - "operatorInfo status should be REGISTERED"); - assert_IsRegisteredForQuorums(incomingOperator, combinedQuorums, - "current operator bitmap should include quorums"); - assert_Snap_Registered_ForQuorums(incomingOperator, combinedQuorums, - "operator did not register for all quorums"); + assert_HasOperatorInfoWithId(incomingOperator, "operatorInfo should have operatorId"); + assert_HasRegisteredStatus(incomingOperator, "operatorInfo status should be REGISTERED"); + assert_IsRegisteredForQuorums( + incomingOperator, combinedQuorums, "current operator bitmap should include quorums" + ); + assert_Snap_Registered_ForQuorums( + incomingOperator, combinedQuorums, "operator did not register for all quorums" + ); // BLSApkRegistry - assert_HasRegisteredPubkey(incomingOperator, - "operator should have registered a pubkey"); - assert_Snap_Added_QuorumApk(incomingOperator, standardQuorums, - "operator pubkey should have been added to standardQuorums apks"); - assert_Snap_Churned_QuorumApk(incomingOperator, churnedOperators, churnedQuorums, - "operator pubkey should have been added and churned operator pubkeys should have been removed from apks"); + assert_HasRegisteredPubkey(incomingOperator, "operator should have registered a pubkey"); + assert_Snap_Added_QuorumApk( + incomingOperator, + standardQuorums, + "operator pubkey should have been added to standardQuorums apks" + ); + assert_Snap_Churned_QuorumApk( + incomingOperator, + churnedOperators, + churnedQuorums, + "operator pubkey should have been added and churned operator pubkeys should have been removed from apks" + ); // StakeRegistry - assert_HasAtLeastMinimumStake(incomingOperator, combinedQuorums, - "operator should have at least the minimum stake in each quorum"); - assert_Snap_Added_OperatorWeight(incomingOperator, standardQuorums, - "failed to add operator weight to operator and total stake in standardQuorums"); - assert_Snap_Churned_OperatorWeight(incomingOperator, churnedOperators, churnedQuorums, - "failed to add operator weight and remove churned weight from each quorum"); + assert_HasAtLeastMinimumStake( + incomingOperator, + combinedQuorums, + "operator should have at least the minimum stake in each quorum" + ); + assert_Snap_Added_OperatorWeight( + incomingOperator, + standardQuorums, + "failed to add operator weight to operator and total stake in standardQuorums" + ); + assert_Snap_Churned_OperatorWeight( + incomingOperator, + churnedOperators, + churnedQuorums, + "failed to add operator weight and remove churned weight from each quorum" + ); // IndexRegistry - assert_Snap_Added_OperatorCount(standardQuorums, - "total operator count should have increased for standardQuorums"); - assert_Snap_Unchanged_OperatorCount(churnedQuorums, - "total operator count should be the same for churnedQuorums"); - assert_Snap_Added_OperatorListEntry(incomingOperator, standardQuorums, - "operator list should have one more entry in standardQuorums"); - assert_Snap_Replaced_OperatorListEntries(incomingOperator, churnedOperators, churnedQuorums, - "operator list should contain incoming operator and should not contain churned operators"); + assert_Snap_Added_OperatorCount( + standardQuorums, "total operator count should have increased for standardQuorums" + ); + assert_Snap_Unchanged_OperatorCount( + churnedQuorums, "total operator count should be the same for churnedQuorums" + ); + assert_Snap_Added_OperatorListEntry( + incomingOperator, + standardQuorums, + "operator list should have one more entry in standardQuorums" + ); + assert_Snap_Replaced_OperatorListEntries( + incomingOperator, + churnedOperators, + churnedQuorums, + "operator list should contain incoming operator and should not contain churned operators" + ); // AVSDirectory - assert_IsRegisteredToAVS(incomingOperator, - "operator should be registered to AVS"); + assert_IsRegisteredToAVS(incomingOperator, "operator should be registered to AVS"); // Check that churnedOperators are deregistered from churnedQuorums - for (uint i = 0; i < churnedOperators.length; i++) { + for (uint256 i = 0; i < churnedOperators.length; i++) { User churnedOperator = churnedOperators[i]; bytes memory churnedQuorum = new bytes(1); churnedQuorum[0] = churnedQuorums[i]; // RegistryCoordinator - assert_HasOperatorInfoWithId(churnedOperator, - "churned operatorInfo should still have operatorId"); - assert_NotRegisteredForQuorums(churnedOperator, churnedQuorum, - "churned operator bitmap should not include churned quorums"); - assert_Snap_Deregistered_FromQuorums(churnedOperator, churnedQuorum, - "churned operator did not deregister from churned quorum"); + assert_HasOperatorInfoWithId( + churnedOperator, "churned operatorInfo should still have operatorId" + ); + assert_NotRegisteredForQuorums( + churnedOperator, + churnedQuorum, + "churned operator bitmap should not include churned quorums" + ); + assert_Snap_Deregistered_FromQuorums( + churnedOperator, + churnedQuorum, + "churned operator did not deregister from churned quorum" + ); // BLSApkRegistry - assert_HasRegisteredPubkey(churnedOperator, - "churned operator should still have a registered pubkey"); + assert_HasRegisteredPubkey( + churnedOperator, "churned operator should still have a registered pubkey" + ); // StakeRegistry - assert_NoExistingStake(churnedOperator, churnedQuorum, - "operator should no longer have stake in any quorums"); + assert_NoExistingStake( + churnedOperator, + churnedQuorum, + "operator should no longer have stake in any quorums" + ); } } - /******************************************************************************* - BALANCE UPDATE CHECKS - *******************************************************************************/ + /** + * + * BALANCE UPDATE CHECKS + * + */ /// @dev Validate state directly after the operator deposits into Eigenlayer core /// We're mostly checking that nothing in the middleware contracts has changed, @@ -168,37 +204,34 @@ contract IntegrationChecks is IntegrationBase { User operator, bytes memory quorums, IStrategy[] memory strategies, - uint[] memory tokenBalances + uint256[] memory tokenBalances ) internal { _log("check_Deposit_State", operator); // RegistryCoordinator - assert_Snap_Unchanged_OperatorInfo(operator, - "operator info should not have changed"); - assert_Snap_Unchanged_QuorumBitmap(operator, - "operators quorum bitmap should not have changed"); + assert_Snap_Unchanged_OperatorInfo(operator, "operator info should not have changed"); + assert_Snap_Unchanged_QuorumBitmap( + operator, "operators quorum bitmap should not have changed" + ); // BLSApkRegistry - assert_Snap_Unchanged_QuorumApk(quorums, - "quorum apks should not have changed"); + assert_Snap_Unchanged_QuorumApk(quorums, "quorum apks should not have changed"); // StakeRegistry - assert_Snap_Increased_OperatorWeight(operator, quorums, - "operator weight should not have decreased after deposit"); - assert_Snap_Unchanged_OperatorStake(operator, quorums, - "operator stake should be unchanged"); - assert_Snap_Unchanged_TotalStake(quorums, - "total stake should be unchanged"); + assert_Snap_Increased_OperatorWeight( + operator, quorums, "operator weight should not have decreased after deposit" + ); + assert_Snap_Unchanged_OperatorStake(operator, quorums, "operator stake should be unchanged"); + assert_Snap_Unchanged_TotalStake(quorums, "total stake should be unchanged"); // IndexRegistry - assert_Snap_Unchanged_OperatorCount(quorums, - "operator counts should not have changed"); - assert_Snap_Unchanged_OperatorListEntry(quorums, - "operator list should not have changed"); + assert_Snap_Unchanged_OperatorCount(quorums, "operator counts should not have changed"); + assert_Snap_Unchanged_OperatorListEntry(quorums, "operator list should not have changed"); // Core - assert_Snap_Added_OperatorShares(operator, strategies, tokenBalances, - "operator should have additional stake"); + assert_Snap_Added_OperatorShares( + operator, strategies, tokenBalances, "operator should have additional stake" + ); } /// @dev Checks that an operator's stake was successfully increased @@ -212,32 +245,38 @@ contract IntegrationChecks is IntegrationBase { _log("check_DepositUpdate_State", operator); // RegistryCoordinator - assert_Snap_Unchanged_OperatorInfo(operator, - "operator info should not have changed"); - assert_Snap_Unchanged_QuorumBitmap(operator, - "operators quorum bitmap should not have changed"); + assert_Snap_Unchanged_OperatorInfo(operator, "operator info should not have changed"); + assert_Snap_Unchanged_QuorumBitmap( + operator, "operators quorum bitmap should not have changed" + ); // BLSApkRegistry - assert_Snap_Unchanged_QuorumApk(quorums, - "quorum apks should not have changed"); + assert_Snap_Unchanged_QuorumApk(quorums, "quorum apks should not have changed"); // StakeRegistry - assert_HasAtLeastMinimumStake(operator, quorums, - "operator should have at least the minimum stake in each quorum"); - assert_Snap_Unchanged_OperatorWeight(operator, quorums, - "updateOperators should not effect operator weight calculation"); - assert_Snap_AddedWeightToStakes(operator, quorums, addedWeights, - "weights should have been added to operator and total stakes"); + assert_HasAtLeastMinimumStake( + operator, quorums, "operator should have at least the minimum stake in each quorum" + ); + assert_Snap_Unchanged_OperatorWeight( + operator, quorums, "updateOperators should not effect operator weight calculation" + ); + assert_Snap_AddedWeightToStakes( + operator, + quorums, + addedWeights, + "weights should have been added to operator and total stakes" + ); // IndexRegistry - assert_Snap_Unchanged_OperatorCount(quorums, - "total operator count should be unchanged for each quorum"); - assert_Snap_Unchanged_OperatorListEntry(quorums, - "operator list should be unchanged for each quorum"); + assert_Snap_Unchanged_OperatorCount( + quorums, "total operator count should be unchanged for each quorum" + ); + assert_Snap_Unchanged_OperatorListEntry( + quorums, "operator list should be unchanged for each quorum" + ); // AVSDirectory - assert_IsRegisteredToAVS(operator, - "operator should be registered to AVS"); + assert_IsRegisteredToAVS(operator, "operator should be registered to AVS"); } /// @dev Validate state directly after the operator exits from Eigenlayer core (by queuing withdrawals) @@ -250,144 +289,140 @@ contract IntegrationChecks is IntegrationBase { _log("check_Withdraw_State", operator); // RegistryCoordinator - assert_Snap_Unchanged_OperatorInfo(operator, - "operator info should not have changed"); - assert_Snap_Unchanged_QuorumBitmap(operator, - "operators quorum bitmap should not have changed"); + assert_Snap_Unchanged_OperatorInfo(operator, "operator info should not have changed"); + assert_Snap_Unchanged_QuorumBitmap( + operator, "operators quorum bitmap should not have changed" + ); // BLSApkRegistry - assert_Snap_Unchanged_QuorumApk(quorums, - "quorum apks should not have changed"); + assert_Snap_Unchanged_QuorumApk(quorums, "quorum apks should not have changed"); // StakeRegistry - assert_Snap_Decreased_OperatorWeight(operator, quorums, - "operator weight should not have increased after deposit"); - assert_Snap_Unchanged_OperatorStake(operator, quorums, - "operator stake should be unchanged"); - assert_Snap_Unchanged_TotalStake(quorums, - "total stake should be unchanged"); + assert_Snap_Decreased_OperatorWeight( + operator, quorums, "operator weight should not have increased after deposit" + ); + assert_Snap_Unchanged_OperatorStake(operator, quorums, "operator stake should be unchanged"); + assert_Snap_Unchanged_TotalStake(quorums, "total stake should be unchanged"); // IndexRegistry - assert_Snap_Unchanged_OperatorCount(quorums, - "operator counts should not have changed"); - assert_Snap_Unchanged_OperatorListEntry(quorums, - "operator list should not have changed"); + assert_Snap_Unchanged_OperatorCount(quorums, "operator counts should not have changed"); + assert_Snap_Unchanged_OperatorListEntry(quorums, "operator list should not have changed"); // Core - assert_Snap_Removed_OperatorShares(operator, strategies, shares, - "operator should have reduced stake"); + assert_Snap_Removed_OperatorShares( + operator, strategies, shares, "operator should have reduced stake" + ); } /// @dev Validate state when, after exiting from the core contracts, updateOperators is called /// We expect that the operator is completely deregistered. /// NOTE: This is a combination of check_Deregister_State and check_CompleteDeregister_State - function check_WithdrawUpdate_State( - User operator, - bytes memory quorums - ) internal { + function check_WithdrawUpdate_State(User operator, bytes memory quorums) internal { _log("check_WithdrawUpdate_State", operator); // RegistryCoordinator - assert_HasOperatorInfoWithId(operator, - "operatorInfo should still have operatorId"); - assert_EmptyQuorumBitmap(operator, - "operator should not have any bits in bitmap"); - assert_HasDeregisteredStatus(operator, - "operatorInfo status should be DEREGISTERED"); - assert_Snap_Deregistered_FromQuorums(operator, quorums, - "operator did not deregister from all quorums"); + assert_HasOperatorInfoWithId(operator, "operatorInfo should still have operatorId"); + assert_EmptyQuorumBitmap(operator, "operator should not have any bits in bitmap"); + assert_HasDeregisteredStatus(operator, "operatorInfo status should be DEREGISTERED"); + assert_Snap_Deregistered_FromQuorums( + operator, quorums, "operator did not deregister from all quorums" + ); // BLSApkRegistry - assert_HasRegisteredPubkey(operator, - "operator should still have a registered pubkey"); - assert_Snap_Removed_QuorumApk(operator, quorums, - "operator pubkey should have been subtracted from each quorum apk"); + assert_HasRegisteredPubkey(operator, "operator should still have a registered pubkey"); + assert_Snap_Removed_QuorumApk( + operator, quorums, "operator pubkey should have been subtracted from each quorum apk" + ); // StakeRegistry - assert_NoExistingStake(operator, quorums, - "operator should no longer have stake in any quorums"); - assert_Snap_Removed_TotalStake(operator, quorums, - "failed to remove operator weight from total stake for each quorum"); + assert_NoExistingStake( + operator, quorums, "operator should no longer have stake in any quorums" + ); + assert_Snap_Removed_TotalStake( + operator, quorums, "failed to remove operator weight from total stake for each quorum" + ); // IndexRegistry - assert_Snap_Reduced_OperatorCount(quorums, - "total operator count should have decreased for each quorum"); - assert_Snap_Removed_OperatorListEntry(operator, quorums, - "operator list should have one fewer entry"); + assert_Snap_Reduced_OperatorCount( + quorums, "total operator count should have decreased for each quorum" + ); + assert_Snap_Removed_OperatorListEntry( + operator, quorums, "operator list should have one fewer entry" + ); // AVSDirectory - assert_NotRegisteredToAVS(operator, - "operator should not be registered to the AVS"); + assert_NotRegisteredToAVS(operator, "operator should not be registered to the AVS"); } /// @dev Used to validate a stake update after NO core balance changes occured - function check_NoUpdate_State( - User operator, - bytes memory quorums - ) internal { + function check_NoUpdate_State(User operator, bytes memory quorums) internal { _log("check_NoChangeUpdate_State", operator); // RegistryCoordinator - assert_Snap_Unchanged_OperatorInfo(operator, - "operator info should not have changed"); - assert_Snap_Unchanged_QuorumBitmap(operator, - "operators quorum bitmap should not have changed"); + assert_Snap_Unchanged_OperatorInfo(operator, "operator info should not have changed"); + assert_Snap_Unchanged_QuorumBitmap( + operator, "operators quorum bitmap should not have changed" + ); // BLSApkRegistry - assert_Snap_Unchanged_QuorumApk(quorums, - "quorum apks should not have changed"); + assert_Snap_Unchanged_QuorumApk(quorums, "quorum apks should not have changed"); // StakeRegistry - assert_Snap_Unchanged_OperatorWeight(operator, quorums, - "operator weight should be unchanged"); - assert_Snap_Unchanged_OperatorStake(operator, quorums, - "operator stake should be unchanged"); - assert_Snap_Unchanged_TotalStake(quorums, - "total stake should be unchanged"); + assert_Snap_Unchanged_OperatorWeight( + operator, quorums, "operator weight should be unchanged" + ); + assert_Snap_Unchanged_OperatorStake(operator, quorums, "operator stake should be unchanged"); + assert_Snap_Unchanged_TotalStake(quorums, "total stake should be unchanged"); // IndexRegistry - assert_Snap_Unchanged_OperatorCount(quorums, - "total operator count should be unchanged for each quorum"); - assert_Snap_Unchanged_OperatorListEntry(quorums, - "operator list should be unchanged for each quorum"); + assert_Snap_Unchanged_OperatorCount( + quorums, "total operator count should be unchanged for each quorum" + ); + assert_Snap_Unchanged_OperatorListEntry( + quorums, "operator list should be unchanged for each quorum" + ); } - /******************************************************************************* - POST-DEREGISTER CHECKS - *******************************************************************************/ + /** + * + * POST-DEREGISTER CHECKS + * + */ /// @dev Check that the operator correctly deregistered from some quorums - function check_Deregister_State( - User operator, - bytes memory quorums - ) internal { + function check_Deregister_State(User operator, bytes memory quorums) internal { _log("check_Deregister_State", operator); // RegistryCoordinator - assert_HasOperatorInfoWithId(operator, - "operatorInfo should still have operatorId"); - assert_NotRegisteredForQuorums(operator, quorums, - "current operator bitmap should not include quorums"); - assert_Snap_Deregistered_FromQuorums(operator, quorums, - "operator did not deregister from all quorums"); + assert_HasOperatorInfoWithId(operator, "operatorInfo should still have operatorId"); + assert_NotRegisteredForQuorums( + operator, quorums, "current operator bitmap should not include quorums" + ); + assert_Snap_Deregistered_FromQuorums( + operator, quorums, "operator did not deregister from all quorums" + ); // BLSApkRegistry - assert_HasRegisteredPubkey(operator, - "operator should still have a registered pubkey"); - assert_Snap_Removed_QuorumApk(operator, quorums, - "operator pubkey should have been subtracted from each quorum apk"); + assert_HasRegisteredPubkey(operator, "operator should still have a registered pubkey"); + assert_Snap_Removed_QuorumApk( + operator, quorums, "operator pubkey should have been subtracted from each quorum apk" + ); // StakeRegistry - assert_NoExistingStake(operator, quorums, - "operator should no longer have stake in any quorums"); - assert_Snap_Removed_TotalStake(operator, quorums, - "failed to remove operator weight from total stake for each quorum"); + assert_NoExistingStake( + operator, quorums, "operator should no longer have stake in any quorums" + ); + assert_Snap_Removed_TotalStake( + operator, quorums, "failed to remove operator weight from total stake for each quorum" + ); // IndexRegistry - assert_Snap_Reduced_OperatorCount(quorums, - "total operator count should have decreased for each quorum"); - assert_Snap_Removed_OperatorListEntry(operator, quorums, - "operator list should have one fewer entry"); + assert_Snap_Reduced_OperatorCount( + quorums, "total operator count should have decreased for each quorum" + ); + assert_Snap_Removed_OperatorListEntry( + operator, quorums, "operator list should have one fewer entry" + ); } /// @dev Check that the operator correctly deregistered from ALL their quorums @@ -397,21 +432,19 @@ contract IntegrationChecks is IntegrationBase { _log("check_CompleteDeregister_State", operator); // RegistryCoordinator - assert_EmptyQuorumBitmap(operator, - "operator should not have any bits in bitmap"); - assert_HasOperatorInfoWithId(operator, - "operatorInfo should still have operatorId"); - assert_HasDeregisteredStatus(operator, - "operatorInfo status should be DEREGISTERED"); + assert_EmptyQuorumBitmap(operator, "operator should not have any bits in bitmap"); + assert_HasOperatorInfoWithId(operator, "operatorInfo should still have operatorId"); + assert_HasDeregisteredStatus(operator, "operatorInfo status should be DEREGISTERED"); // AVSDirectory - assert_NotRegisteredToAVS(operator, - "operator should not be registered to the AVS"); + assert_NotRegisteredToAVS(operator, "operator should not be registered to the AVS"); } - /******************************************************************************* - UTIL METHODS - *******************************************************************************/ + /** + * + * UTIL METHODS + * + */ /// example output: /// - check_Register_State(Operator0) diff --git a/test/integration/IntegrationConfig.t.sol b/test/integration/IntegrationConfig.t.sol index f3231ac3..e04a7204 100644 --- a/test/integration/IntegrationConfig.t.sol +++ b/test/integration/IntegrationConfig.t.sol @@ -8,7 +8,6 @@ import "test/ffi/util/G2Operations.sol"; import "test/integration/utils/BitmapStrings.t.sol"; contract Constants { - /// Quorum Config: /// @dev Default OperatorSetParam values used to initialize quorums @@ -16,22 +15,21 @@ contract Constants { /// This is a low number because each operator receives its own BLS keypair, which /// is very slow to generate. uint32 constant MAX_OPERATOR_COUNT = 5; - uint16 constant KICK_BIPS_OPERATOR_STAKE = 15000; + uint16 constant KICK_BIPS_OPERATOR_STAKE = 15_000; uint16 constant KICK_BIPS_TOTAL_STAKE = 150; /// Other: /// @dev Number of BLS keypairs to pregenerate. This is a slow operation, /// so I've set this to a low number. - uint constant NUM_GENERATED_OPERATORS = MAX_OPERATOR_COUNT + 5; + uint256 constant NUM_GENERATED_OPERATORS = MAX_OPERATOR_COUNT + 5; - uint constant MAX_QUORUM_COUNT = 192; // From RegistryCoordinator.MAX_QUORUM_COUNT + uint256 constant MAX_QUORUM_COUNT = 192; // From RegistryCoordinator.MAX_QUORUM_COUNT - uint16 internal constant BIPS_DENOMINATOR = 10000; + uint16 internal constant BIPS_DENOMINATOR = 10_000; } contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { - using BitmapStrings for *; using Strings for *; using BN254 for *; @@ -48,42 +46,42 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { bytes minStakeFlags; bytes fillTypeFlags; - uint constant FLAG = 1; + uint256 constant FLAG = 1; /// @dev Flags for userTypes - uint constant DEFAULT = (FLAG << 0); - uint constant ALT_METHODS = (FLAG << 1); + uint256 constant DEFAULT = (FLAG << 0); + uint256 constant ALT_METHODS = (FLAG << 1); /// @dev Flags for numQuorums and numStrategies - uint constant ONE = (FLAG << 0); - uint constant TWO = (FLAG << 1); - uint constant MANY = (FLAG << 2); - uint constant FIFTEEN = (FLAG << 3); - uint constant TWENTY = (FLAG << 4); - uint constant TWENTYFIVE = (FLAG << 5); + uint256 constant ONE = (FLAG << 0); + uint256 constant TWO = (FLAG << 1); + uint256 constant MANY = (FLAG << 2); + uint256 constant FIFTEEN = (FLAG << 3); + uint256 constant TWENTY = (FLAG << 4); + uint256 constant TWENTYFIVE = (FLAG << 5); /// @dev Flags for minimumStake - uint constant NO_MINIMUM = (FLAG << 0); - uint constant HAS_MINIMUM = (FLAG << 1); + uint256 constant NO_MINIMUM = (FLAG << 0); + uint256 constant HAS_MINIMUM = (FLAG << 1); /// @dev Flags for fillTypes - uint constant EMPTY = (FLAG << 0); - uint constant SOME_FILL = (FLAG << 1); - uint constant FULL = (FLAG << 2); + uint256 constant EMPTY = (FLAG << 0); + uint256 constant SOME_FILL = (FLAG << 1); + uint256 constant FULL = (FLAG << 2); /// @dev Tracking variables for pregenerated BLS keypairs: /// (See _fetchKeypair) - uint fetchIdx = 0; - uint[] privKeys; + uint256 fetchIdx = 0; + uint256[] privKeys; IBLSApkRegistry.PubkeyRegistrationParams[] pubkeys; /// @dev Current initialized quorums are tracked here: - uint quorumCount; + uint256 quorumCount; uint192 quorumBitmap; bytes quorumArray; /// @dev Number of operators generated so far - uint numOperators = 0; + uint256 numOperators = 0; /// @dev current array of operatorIds registered so far per quorum. /// does not update and remove if an operator is deregistered however, used for testing updateOperatorsForQuorum mapping(uint8 => address[]) operatorsForQuorum; @@ -94,9 +92,9 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { * so this is the best way to speed things up when running multiple tests. */ constructor() { - for (uint i = 0; i < NUM_GENERATED_OPERATORS; i++) { + for (uint256 i = 0; i < NUM_GENERATED_OPERATORS; i++) { IBLSApkRegistry.PubkeyRegistrationParams memory pubkey; - uint privKey = uint(keccak256(abi.encodePacked(i + 1))); + uint256 privKey = uint256(keccak256(abi.encodePacked(i + 1))); pubkey.pubkeyG1 = BN254.generatorG1().scalar_mul(privKey); pubkey.pubkeyG2 = G2Operations.mul(privKey); @@ -112,15 +110,15 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { */ struct QuorumConfig { /// @dev The number of quorums created during setup - uint numQuorums; // ONE | TWO | MANY + uint256 numQuorums; // ONE | TWO | MANY /// @dev The number of strategies a quorum will consider - uint numStrategies; // ONE | TWO | MANY + uint256 numStrategies; // ONE | TWO | MANY /// @dev Whether each quorum has a minimum stake /// NOTE: Minimum stake is currently MIN_BALANCE by default - uint minimumStake; // NO_MINIMUM | HAS_MINIMUM + uint256 minimumStake; // NO_MINIMUM | HAS_MINIMUM /// @dev Whether each quorum created is pre-populated with operators /// NOTE: Default - uint fillTypes; // EMPTY | SOME_FILL | FULL + uint256 fillTypes; // EMPTY | SOME_FILL | FULL } /** @@ -131,7 +129,7 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { */ function _configRand( uint24 _randomSeed, - uint _userTypes, + uint256 _userTypes, QuorumConfig memory _quorumConfig ) internal { emit log_named_uint("_configRand: set random seed to", _randomSeed); @@ -147,7 +145,9 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { // Sanity check config assertTrue(userFlags.length != 0, "_configRand: invalid _userTypes, no flags passed"); assertTrue(numQuorumFlags.length != 0, "_configRand: invalid numQuorums, no flags passed"); - assertTrue(numStrategyFlags.length != 0, "_configRand: invalid numStrategies, no flags passed"); + assertTrue( + numStrategyFlags.length != 0, "_configRand: invalid numStrategies, no flags passed" + ); assertTrue(minStakeFlags.length != 0, "_configRand: invalid minimumStake, no flags passed"); assertTrue(fillTypeFlags.length != 0, "_configRand: invalid fillTypes, no flags passed"); @@ -158,14 +158,15 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { emit log_named_uint("_configRand: number of quorums being initialized", quorumCount); // Default OperatorSetParams for all quorums - IRegistryCoordinator.OperatorSetParam memory operatorSet = IRegistryCoordinator.OperatorSetParam({ + IRegistryCoordinator.OperatorSetParam memory operatorSet = IRegistryCoordinator + .OperatorSetParam({ maxOperatorCount: MAX_OPERATOR_COUNT, kickBIPsOfOperatorStake: KICK_BIPS_OPERATOR_STAKE, kickBIPsOfTotalStake: KICK_BIPS_TOTAL_STAKE }); // Initialize each quorum - for (uint i = 0; i < quorumCount; i++) { + for (uint256 i = 0; i < quorumCount; i++) { IStakeRegistry.StrategyParams[] memory strategyParams = _randStrategyParams(); uint96 minimumStake = _randMinStake(); @@ -183,15 +184,19 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { } // Decide how many operators to register for each quorum initially - uint initialOperators = _randInitialOperators(operatorSet); - emit log(string.concat("Registering ", initialOperators.toString(), " initial operators in each quorum")); + uint256 initialOperators = _randInitialOperators(operatorSet); + emit log( + string.concat( + "Registering ", initialOperators.toString(), " initial operators in each quorum" + ) + ); // For each initial operator, register for all quorums - for (uint j = 0; j < initialOperators; j++) { + for (uint256 j = 0; j < initialOperators; j++) { User operator = _newRandomOperator(); operator.registerOperator(quorumArray); - for (uint k = 0; k < quorumArray.length; k++) { + for (uint256 k = 0; k < quorumArray.length; k++) { uint8 quorum = uint8(quorumArray[k]); operatorsForQuorum[quorum].push(address(operator)); } @@ -205,29 +210,34 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { /** * Gen/Init methods: */ - function _newRandomOperator() internal returns (User) { string memory operatorName = string.concat("Operator", numOperators.toString()); numOperators++; - (User operator, IStrategy[] memory strategies, uint[] memory tokenBalances) = _randUser(operatorName); + (User operator, IStrategy[] memory strategies, uint256[] memory tokenBalances) = + _randUser(operatorName); operator.registerAsOperator(); operator.depositIntoEigenlayer(strategies, tokenBalances); - assertTrue(delegationManager.isOperator(address(operator)), "_newRandomOperator: operator should be registered"); + assertTrue( + delegationManager.isOperator(address(operator)), + "_newRandomOperator: operator should be registered" + ); return operator; } /// @dev Create a new user with token balances in ALL core-whitelisted strategies - function _randUser(string memory name) internal returns (User, IStrategy[] memory, uint[] memory) { + function _randUser( + string memory name + ) internal returns (User, IStrategy[] memory, uint256[] memory) { // Create User contract and give it a unique BLS keypair - (uint privKey, IBLSApkRegistry.PubkeyRegistrationParams memory pubkey) = _fetchKeypair(); + (uint256 privKey, IBLSApkRegistry.PubkeyRegistrationParams memory pubkey) = _fetchKeypair(); // Use userFlags to pick the kind of user to generate User user; - uint userType = _randValue(userFlags); + uint256 userType = _randValue(userFlags); if (userType == DEFAULT) { user = new User(name, privKey, pubkey); @@ -238,21 +248,23 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { emit log_named_string("_randUser: Created user", user.NAME()); - (IStrategy[] memory strategies, uint[] memory balances) = _dealRandTokens(user); + (IStrategy[] memory strategies, uint256[] memory balances) = _dealRandTokens(user); return (user, strategies, balances); } - function _dealRandTokens(User user) internal returns (IStrategy[] memory, uint[] memory) { + function _dealRandTokens( + User user + ) internal returns (IStrategy[] memory, uint256[] memory) { IStrategy[] memory strategies = new IStrategy[](allStrats.length); - uint[] memory balances = new uint[](allStrats.length); + uint256[] memory balances = new uint256[](allStrats.length); emit log_named_string("_dealRandTokens: dealing assets to", user.NAME()); // Deal the user a random balance between [MIN_BALANCE, MAX_BALANCE] for each existing strategy - for (uint i = 0; i < allStrats.length; i++) { + for (uint256 i = 0; i < allStrats.length; i++) { IStrategy strat = allStrats[i]; IERC20 underlyingToken = strat.underlyingToken(); - uint balance = _randUint({ min: MIN_BALANCE, max: MAX_BALANCE }); + uint256 balance = _randUint({min: MIN_BALANCE, max: MAX_BALANCE}); StdCheats.deal(address(underlyingToken), address(user), balance); strategies[i] = strat; @@ -262,17 +274,19 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { return (strategies, balances); } - function _dealMaxTokens(User user) internal returns (IStrategy[] memory, uint[] memory) { + function _dealMaxTokens( + User user + ) internal returns (IStrategy[] memory, uint256[] memory) { IStrategy[] memory strategies = new IStrategy[](allStrats.length); - uint[] memory balances = new uint[](allStrats.length); + uint256[] memory balances = new uint256[](allStrats.length); emit log_named_string("_dealMaxTokens: dealing assets to", user.NAME()); // Deal the user the 100 * MAX_BALANCE for each existing strategy - for (uint i = 0; i < allStrats.length; i++) { + for (uint256 i = 0; i < allStrats.length; i++) { IStrategy strat = allStrats[i]; IERC20 underlyingToken = strat.underlyingToken(); - uint balance = 100 * MAX_BALANCE; + uint256 balance = 100 * MAX_BALANCE; StdCheats.deal(address(underlyingToken), address(user), balance); strategies[i] = strat; @@ -301,32 +315,45 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { // For each churn quorum, select operators as churn targets User[] memory churnTargets = new User[](churnQuorums.length); - for (uint i = 0; i < churnQuorums.length; i++) { + for (uint256 i = 0; i < churnQuorums.length; i++) { uint8 quorum = uint8(churnQuorums[i]); - IRegistryCoordinator.OperatorSetParam memory params - = registryCoordinator.getOperatorSetParams(quorum); + IRegistryCoordinator.OperatorSetParam memory params = + registryCoordinator.getOperatorSetParams(quorum); // Sanity check - make sure we're at the operator cap uint32 curNumOperators = indexRegistry.totalOperatorsForQuorum(quorum); - assertTrue(curNumOperators >= params.maxOperatorCount, "_getChurnTargets: non-full quorum cannot be churned"); + assertTrue( + curNumOperators >= params.maxOperatorCount, + "_getChurnTargets: non-full quorum cannot be churned" + ); // Get a random registered operator churnTargets[i] = _selectRandRegisteredOperator(quorum); emit log_named_string( - string.concat("_getChurnTargets: selected churn target for quorum ", uint(quorum).toString()), - churnTargets[i].NAME()); + string.concat( + "_getChurnTargets: selected churn target for quorum ", + uint256(quorum).toString() + ), + churnTargets[i].NAME() + ); uint96 currentTotalStake = stakeRegistry.getCurrentTotalStake(quorum); - uint96 operatorToChurnStake = stakeRegistry.getCurrentStake(churnTargets[i].operatorId(), quorum); + uint96 operatorToChurnStake = + stakeRegistry.getCurrentStake(churnTargets[i].operatorId(), quorum); // Ensure the incoming operator exceeds the individual stake threshold -- // more stake than the outgoing operator by kickBIPsOfOperatorStake while ( - _getWeight(quorum, incomingOperator) <= _individualKickThreshold(operatorToChurnStake, params) || - operatorToChurnStake >= _totalKickThreshold(currentTotalStake + _getWeight(quorum, incomingOperator), params) + _getWeight(quorum, incomingOperator) + <= _individualKickThreshold(operatorToChurnStake, params) + || operatorToChurnStake + >= _totalKickThreshold( + currentTotalStake + _getWeight(quorum, incomingOperator), params + ) ) { - (IStrategy[] memory strategies, uint[] memory balances) = _dealMaxTokens(incomingOperator); + (IStrategy[] memory strategies, uint256[] memory balances) = + _dealMaxTokens(incomingOperator); incomingOperator.depositIntoEigenlayer(strategies, balances); } } @@ -351,19 +378,21 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { return totalStake * setParams.kickBIPsOfTotalStake / BIPS_DENOMINATOR; } - function _getWeight( - uint8 quorum, - User operator - ) internal view returns (uint96) { + function _getWeight(uint8 quorum, User operator) internal view returns (uint96) { return stakeRegistry.weightOfOperatorForQuorum(quorum, address(operator)); } - function _makeRoom(bytes memory quorums) private { - emit log_named_string("_getChurnTargets: making room by removing operators from quorums", quorums.toString()); + function _makeRoom( + bytes memory quorums + ) private { + emit log_named_string( + "_getChurnTargets: making room by removing operators from quorums", quorums.toString() + ); - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { uint8 quorum = uint8(quorums[i]); - uint32 maxOperatorCount = registryCoordinator.getOperatorSetParams(quorum).maxOperatorCount; + uint32 maxOperatorCount = + registryCoordinator.getOperatorSetParams(quorum).maxOperatorCount; // Continue deregistering until we're under the cap // This uses while in case we tested a config change that lowered the max count @@ -378,24 +407,31 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { } } - function _selectRandRegisteredOperator(uint8 quorum) internal returns (User) { + function _selectRandRegisteredOperator( + uint8 quorum + ) internal returns (User) { uint32 curNumOperators = indexRegistry.totalOperatorsForQuorum(quorum); bytes32 randId = indexRegistry.getLatestOperatorUpdate({ quorumNumber: quorum, - operatorIndex: uint32(_randUint({ min: 0, max: curNumOperators - 1 })) + operatorIndex: uint32(_randUint({min: 0, max: curNumOperators - 1})) }).operatorId; return User(blsApkRegistry.getOperatorFromPubkeyHash(randId)); } - function _fetchKeypair() internal returns (uint, IBLSApkRegistry.PubkeyRegistrationParams memory) { + function _fetchKeypair() + internal + returns (uint256, IBLSApkRegistry.PubkeyRegistrationParams memory) + { // should probably just generate another keypair at this point if (fetchIdx == privKeys.length) { - revert("_fetchKeypair: not enough generated keys. Check IntegrationDeployer.constructor"); + revert( + "_fetchKeypair: not enough generated keys. Check IntegrationDeployer.constructor" + ); } - uint privKey = privKeys[fetchIdx]; + uint256 privKey = privKeys[fetchIdx]; IBLSApkRegistry.PubkeyRegistrationParams memory pubkey = pubkeys[fetchIdx]; fetchIdx++; @@ -404,12 +440,12 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { /// @dev Uses `random` to return a random uint, with a range given by `min` and `max` (inclusive) /// @return `min` <= result <= `max` - function _randUint(uint min, uint max) internal returns (uint) { - uint range = max - min + 1; + function _randUint(uint256 min, uint256 max) internal returns (uint256) { + uint256 range = max - min + 1; // calculate the number of bits needed for the range - uint bitsNeeded = 0; - uint tempRange = range; + uint256 bitsNeeded = 0; + uint256 tempRange = range; while (tempRange > 0) { bitsNeeded++; tempRange >>= 1; @@ -417,8 +453,8 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { // create a mask for the required number of bits // and extract the value from the hash - uint mask = (1 << bitsNeeded) - 1; - uint value = uint(random) & mask; + uint256 mask = (1 << bitsNeeded) - 1; + uint256 value = uint256(random) & mask; // in case value is out of range, wrap around or retry while (value >= range) { @@ -431,14 +467,16 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { } function _randBool() internal returns (bool) { - return _randUint({ min: 0, max: 1 }) == 0; + return _randUint({min: 0, max: 1}) == 0; } - function _selectRand(bytes memory quorums) internal returns (bytes memory) { + function _selectRand( + bytes memory quorums + ) internal returns (bytes memory) { assertTrue(quorums.length != 0, "_selectRand: tried to select from empty quorum list"); uint192 result; - for (uint i = 0; i < quorums.length; i++) { + for (uint256 i = 0; i < quorums.length; i++) { if (_randBool()) { result = uint192(result.setBit(uint8(quorums[i]))); } @@ -457,19 +495,21 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { } /// @dev Select a random value from `arr` and return it. Reverts if arr is empty - function _randValue(bytes memory arr) internal returns (uint) { + function _randValue( + bytes memory arr + ) internal returns (uint256) { assertTrue(arr.length > 0, "_randValue: tried to select value from empty array"); - uint idx = _randUint({ min: 0, max: arr.length - 1 }); - return uint(uint8(arr[idx])); + uint256 idx = _randUint({min: 0, max: arr.length - 1}); + return uint256(uint8(arr[idx])); } /// Private _randX methods used by _configRand: /// @dev Select a random number of quorums to initialize /// NOTE: This should only be used when initializing quorums for the first time (in _configRand) - function _randQuorumCount() private returns (uint) { - uint quorumFlag = _randValue(numQuorumFlags); + function _randQuorumCount() private returns (uint256) { + uint256 quorumFlag = _randValue(numQuorumFlags); if (quorumFlag == ONE) { return 1; @@ -478,7 +518,7 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { } else if (quorumFlag == MANY) { // Ideally this would be MAX_QUORUM_COUNT, but that really slows tests // that have users register for all quorums - return _randUint({ min: 3, max: 10 }); + return _randUint({min: 3, max: 10}); } else { revert("_randQuorumCount: flag not recognized"); } @@ -489,15 +529,15 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { /// selecting strategies to add after the quorum has been initialized, this is likely to /// return duplicates. function _randStrategyParams() private returns (IStakeRegistry.StrategyParams[] memory) { - uint strategyFlag = _randValue(numStrategyFlags); - uint strategyCount; + uint256 strategyFlag = _randValue(numStrategyFlags); + uint256 strategyCount; if (strategyFlag == ONE) { strategyCount = 1; } else if (strategyFlag == TWO) { strategyCount = 2; } else if (strategyFlag == MANY) { - strategyCount = _randUint({ min: 3, max: allStrats.length - 1 }); + strategyCount = _randUint({min: 3, max: allStrats.length - 1}); } else if (strategyFlag == FIFTEEN) { strategyCount = 15; } else if (strategyFlag == TWENTY) { @@ -508,9 +548,10 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { revert("_randStrategyCount: flag not recognized"); } - IStakeRegistry.StrategyParams[] memory params = new IStakeRegistry.StrategyParams[](strategyCount); + IStakeRegistry.StrategyParams[] memory params = + new IStakeRegistry.StrategyParams[](strategyCount); - for (uint i = 0; i < params.length; i++) { + for (uint256 i = 0; i < params.length; i++) { params[i] = IStakeRegistry.StrategyParams({ strategy: allStrats[i], multiplier: DEFAULT_STRATEGY_MULTIPLIER @@ -524,13 +565,15 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { * @dev Uses _randFillType to determine how many operators to register for a quorum initially * @return The number of operators to register */ - function _randInitialOperators(IRegistryCoordinator.OperatorSetParam memory operatorSet) private returns (uint) { - uint fillTypeFlag = _randValue(fillTypeFlags); + function _randInitialOperators( + IRegistryCoordinator.OperatorSetParam memory operatorSet + ) private returns (uint256) { + uint256 fillTypeFlag = _randValue(fillTypeFlags); if (fillTypeFlag == EMPTY) { return 0; } else if (fillTypeFlag == SOME_FILL) { - return _randUint({ min: 1, max: operatorSet.maxOperatorCount - 1 }); + return _randUint({min: 1, max: operatorSet.maxOperatorCount - 1}); } else if (fillTypeFlag == FULL) { return operatorSet.maxOperatorCount; } else { @@ -540,7 +583,7 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { /// @dev Select a random number of quorums to initialize function _randMinStake() private returns (uint96) { - uint minStakeFlag = _randValue(minStakeFlags); + uint256 minStakeFlag = _randValue(minStakeFlags); if (minStakeFlag == NO_MINIMUM) { return 0; @@ -555,10 +598,12 @@ contract IntegrationConfig is IntegrationDeployer, G2Operations, Constants { * @dev Converts a bitmap into an array of bytes * @dev Each byte in the input is processed as indicating a single bit to flip in the bitmap */ - function _bitmapToBytes(uint bitmap) internal pure returns (bytes memory bytesArray) { - for (uint i = 0; i < 256; ++i) { + function _bitmapToBytes( + uint256 bitmap + ) internal pure returns (bytes memory bytesArray) { + for (uint256 i = 0; i < 256; ++i) { // Mask for i-th bit - uint mask = uint(1 << i); + uint256 mask = uint256(1 << i); // emit log_named_uint("mask: ", mask); diff --git a/test/integration/IntegrationDeployer.t.sol b/test/integration/IntegrationDeployer.t.sol index acb89afd..5d5ffadd 100644 --- a/test/integration/IntegrationDeployer.t.sol +++ b/test/integration/IntegrationDeployer.t.sol @@ -107,7 +107,7 @@ abstract contract IntegrationDeployer is Test, IUserDeployer { /// @notice Upper bound start range is ~1 month into the future, multiple of CALCULATION_INTERVAL_SECONDS uint32 MAX_FUTURE_LENGTH = 28 days; /// @notice absolute min timestamp that a rewards can start at - uint32 GENESIS_REWARDS_TIMESTAMP = 1712188800; + uint32 GENESIS_REWARDS_TIMESTAMP = 1_712_188_800; /// @notice Equivalent to 100%, but in basis points. uint16 internal constant ONE_HUNDRED_IN_BIPS = 10_000; @@ -163,33 +163,41 @@ abstract contract IntegrationDeployer is Test, IUserDeployer { ) ); - permissionController = PermissionController(address(new TransparentUpgradeableProxy(address(emptyContract), address(proxyAdmin), ""))); + permissionController = PermissionController( + address( + new TransparentUpgradeableProxy(address(emptyContract), address(proxyAdmin), "") + ) + ); rewardsCoordinator = RewardsCoordinator( - address(new TransparentUpgradeableProxy(address(emptyContract), address(proxyAdmin), "")) + address( + new TransparentUpgradeableProxy(address(emptyContract), address(proxyAdmin), "") + ) ); // Deploy EigenPod Contracts - pod = new EigenPod( - ethPOSDeposit, - eigenPodManager, - GENESIS_TIME_LOCAL - ); + pod = new EigenPod(ethPOSDeposit, eigenPodManager, GENESIS_TIME_LOCAL); eigenPodBeacon = new UpgradeableBeacon(address(pod)); PermissionController permissionControllerImplementation = new PermissionController(); // Second, deploy the *implementation* contracts, using the *proxy contracts* as inputs - DelegationManager delegationImplementation = - new DelegationManager(strategyManager, eigenPodManager, allocationManager, pauserRegistry, permissionController, 0); + DelegationManager delegationImplementation = new DelegationManager( + strategyManager, + eigenPodManager, + allocationManager, + pauserRegistry, + permissionController, + 0 + ); StrategyManager strategyManagerImplementation = new StrategyManager(delegationManager, pauserRegistry); - EigenPodManager eigenPodManagerImplementation = new EigenPodManager( - ethPOSDeposit, eigenPodBeacon, delegationManager, pauserRegistry - ); + EigenPodManager eigenPodManagerImplementation = + new EigenPodManager(ethPOSDeposit, eigenPodBeacon, delegationManager, pauserRegistry); console.log("HERE Impl"); - AVSDirectory avsDirectoryImplementation = new AVSDirectory(delegationManager, pauserRegistry); + AVSDirectory avsDirectoryImplementation = + new AVSDirectory(delegationManager, pauserRegistry); RewardsCoordinator rewardsCoordinatorImplementation = new RewardsCoordinator( delegationManager, @@ -209,7 +217,7 @@ abstract contract IntegrationDeployer is Test, IUserDeployer { pauserRegistry, permissionController, uint32(7 days), // DEALLOCATION_DELAY - uint32(1 days) // ALLOCATION_CONFIGURATION_DELAY + uint32(1 days) // ALLOCATION_CONFIGURATION_DELAY ); // Third, upgrade the proxy contracts to point to the implementations @@ -332,7 +340,11 @@ abstract contract IntegrationDeployer is Test, IUserDeployer { cheats.stopPrank(); StakeRegistry stakeRegistryImplementation = new StakeRegistry( - IRegistryCoordinator(registryCoordinator), IDelegationManager(delegationManager), IAVSDirectory(avsDirectory), allocationManager, IServiceManager(serviceManager) + IRegistryCoordinator(registryCoordinator), + IDelegationManager(delegationManager), + IAVSDirectory(avsDirectory), + allocationManager, + IServiceManager(serviceManager) ); BLSApkRegistry blsApkRegistryImplementation = new BLSApkRegistry(IRegistryCoordinator(registryCoordinator)); @@ -374,8 +386,14 @@ abstract contract IntegrationDeployer is Test, IUserDeployer { StakeType[] memory quorumStakeTypes = new StakeType[](0); uint32[] memory slashableStakeQuorumLookAheadPeriods = new uint32[](0); - RegistryCoordinator registryCoordinatorImplementation = - new RegistryCoordinator(serviceManager, stakeRegistry, blsApkRegistry, indexRegistry, allocationManager, pauserRegistry); + RegistryCoordinator registryCoordinatorImplementation = new RegistryCoordinator( + serviceManager, + stakeRegistry, + blsApkRegistry, + indexRegistry, + allocationManager, + pauserRegistry + ); proxyAdmin.upgradeAndCall( TransparentUpgradeableProxy(payable(address(registryCoordinator))), address(registryCoordinatorImplementation), @@ -423,9 +441,7 @@ abstract contract IntegrationDeployer is Test, IUserDeployer { bool[] memory thirdPartyTransfersForbiddenValues = new bool[](1); strategies[0] = strategy; cheats.prank(strategyManager.strategyWhitelister()); - strategyManager.addStrategiesToDepositWhitelist( - strategies - ); + strategyManager.addStrategiesToDepositWhitelist(strategies); // Add to allStrats allStrats.push(strategy); diff --git a/test/integration/TimeMachine.t.sol b/test/integration/TimeMachine.t.sol index b1cffa68..d16e1ac4 100644 --- a/test/integration/TimeMachine.t.sol +++ b/test/integration/TimeMachine.t.sol @@ -4,20 +4,19 @@ pragma solidity ^0.8.27; import "forge-std/Test.sol"; contract TimeMachine is Test { - Vm cheats = Vm(VM_ADDRESS); bool pastExists = false; - uint lastSnapshot; + uint256 lastSnapshot; - function createSnapshot() public returns (uint) { - uint snapshot = cheats.snapshot(); + function createSnapshot() public returns (uint256) { + uint256 snapshot = cheats.snapshot(); lastSnapshot = snapshot; pastExists = true; return snapshot; } - function warpToLast() public returns (uint curState) { + function warpToLast() public returns (uint256 curState) { // Safety check to make sure createSnapshot is called before attempting to warp // so we don't accidentally prevent our own births assertTrue(pastExists, "TimeMachine.warpToLast: invalid usage, past does not exist"); @@ -27,7 +26,9 @@ contract TimeMachine is Test { return curState; } - function warpToPresent(uint curState) public { + function warpToPresent( + uint256 curState + ) public { cheats.revertTo(curState); } } diff --git a/test/integration/User.t.sol b/test/integration/User.t.sol index 23e9ffcc..fbc491f5 100644 --- a/test/integration/User.t.sol +++ b/test/integration/User.t.sol @@ -28,17 +28,15 @@ import "test/integration/TimeMachine.t.sol"; import "test/integration/utils/Sort.t.sol"; import "test/integration/utils/BitmapStrings.t.sol"; - interface IUserDeployer { function registryCoordinator() external view returns (RegistryCoordinator); function avsDirectory() external view returns (AVSDirectory); function timeMachine() external view returns (TimeMachine); - function churnApproverPrivateKey() external view returns (uint); + function churnApproverPrivateKey() external view returns (uint256); function churnApprover() external view returns (address); } contract User is Test { - using BN254 for *; using Strings for *; using BitmapStrings for *; @@ -60,21 +58,25 @@ contract User is Test { TimeMachine timeMachine; - uint churnApproverPrivateKey; + uint256 churnApproverPrivateKey; address churnApprover; string public NAME; bytes32 public operatorId; // BLS keypair: - uint privKey; + uint256 privKey; IBLSApkRegistry.PubkeyRegistrationParams pubkeyParams; // EIP1271 sigs: mapping(bytes32 => bool) digests; - uint salt = 0; + uint256 salt = 0; - constructor(string memory name, uint _privKey, IBLSApkRegistry.PubkeyRegistrationParams memory _pubkeyParams) { + constructor( + string memory name, + uint256 _privKey, + IBLSApkRegistry.PubkeyRegistrationParams memory _pubkeyParams + ) { IUserDeployer deployer = IUserDeployer(msg.sender); registryCoordinator = deployer.registryCoordinator(); @@ -100,7 +102,8 @@ contract User is Test { privKey = _privKey; pubkeyParams = _pubkeyParams; - BN254.G1Point memory registrationMessageHash = registryCoordinator.pubkeyRegistrationMessageHash(address(this)); + BN254.G1Point memory registrationMessageHash = + registryCoordinator.pubkeyRegistrationMessageHash(address(this)); pubkeyParams.pubkeyRegistrationSignature = registrationMessageHash.scalar_mul(privKey); operatorId = pubkeyParams.pubkeyG1.hashG1Point(); @@ -114,8 +117,9 @@ contract User is Test { /** * Middleware contracts: */ - - function registerOperator(bytes calldata quorums) public createSnapshot virtual returns (bytes32) { + function registerOperator( + bytes calldata quorums + ) public virtual createSnapshot returns (bytes32) { _log("registerOperator", quorums); vm.warp(block.timestamp + 1); @@ -136,7 +140,7 @@ contract User is Test { bytes calldata churnQuorums, User[] calldata churnTargets, bytes calldata standardQuorums - ) public createSnapshot virtual { + ) public virtual createSnapshot { _logChurn("registerOperatorWithChurn", churnQuorums, churnTargets, standardQuorums); // Sanity check input: @@ -144,39 +148,41 @@ contract User is Test { // - churnQuorums and standardQuorums should not have any bits in common uint192 churnBitmap = uint192(churnQuorums.orderedBytesArrayToBitmap()); uint192 standardBitmap = uint192(standardQuorums.orderedBytesArrayToBitmap()); - assertEq(churnQuorums.length, churnTargets.length, "User.registerOperatorWithChurn: input length mismatch"); - assertTrue(churnBitmap.noBitsInCommon(standardBitmap), "User.registerOperatorWithChurn: input quorums have common bits"); + assertEq( + churnQuorums.length, + churnTargets.length, + "User.registerOperatorWithChurn: input length mismatch" + ); + assertTrue( + churnBitmap.noBitsInCommon(standardBitmap), + "User.registerOperatorWithChurn: input quorums have common bits" + ); - bytes memory allQuorums = - churnBitmap - .plus(standardBitmap) - .bitmapToBytesArray(); + bytes memory allQuorums = churnBitmap.plus(standardBitmap).bitmapToBytesArray(); - IRegistryCoordinator.OperatorKickParam[] memory kickParams - = new IRegistryCoordinator.OperatorKickParam[](allQuorums.length); + IRegistryCoordinator.OperatorKickParam[] memory kickParams = + new IRegistryCoordinator.OperatorKickParam[](allQuorums.length); // this constructs OperatorKickParam[] in ascending quorum order // (yikes) - uint churnIdx; - uint stdIdx; + uint256 churnIdx; + uint256 stdIdx; while (churnIdx + stdIdx < allQuorums.length) { if (churnIdx == churnQuorums.length) { - kickParams[churnIdx + stdIdx] = IRegistryCoordinator.OperatorKickParam({ - quorumNumber: 0, - operator: address(0) - }); + kickParams[churnIdx + stdIdx] = + IRegistryCoordinator.OperatorKickParam({quorumNumber: 0, operator: address(0)}); stdIdx++; - } else if (stdIdx == standardQuorums.length || churnQuorums[churnIdx] < standardQuorums[stdIdx]) { + } else if ( + stdIdx == standardQuorums.length || churnQuorums[churnIdx] < standardQuorums[stdIdx] + ) { kickParams[churnIdx + stdIdx] = IRegistryCoordinator.OperatorKickParam({ quorumNumber: uint8(churnQuorums[churnIdx]), operator: address(churnTargets[churnIdx]) }); churnIdx++; } else if (standardQuorums[stdIdx] < churnQuorums[churnIdx]) { - kickParams[churnIdx + stdIdx] = IRegistryCoordinator.OperatorKickParam({ - quorumNumber: 0, - operator: address(0) - }); + kickParams[churnIdx + stdIdx] = + IRegistryCoordinator.OperatorKickParam({quorumNumber: 0, operator: address(0)}); stdIdx++; } else { revert("User.registerOperatorWithChurn: malformed input"); @@ -185,7 +191,7 @@ contract User is Test { // Generate churn approver signature bytes32 _salt = keccak256(abi.encodePacked(++salt, address(this))); - uint expiry = type(uint).max; + uint256 expiry = type(uint256).max; bytes32 digest = registryCoordinator.calculateOperatorChurnApprovalDigestHash({ registeringOperator: address(this), registeringOperatorId: operatorId, @@ -203,12 +209,8 @@ contract User is Test { } signature[signature.length - 1] = bytes1(v); - ISignatureUtils.SignatureWithSaltAndExpiry memory churnApproverSignature - = ISignatureUtils.SignatureWithSaltAndExpiry({ - signature: signature, - salt: _salt, - expiry: expiry - }); + ISignatureUtils.SignatureWithSaltAndExpiry memory churnApproverSignature = ISignatureUtils + .SignatureWithSaltAndExpiry({signature: signature, salt: _salt, expiry: expiry}); vm.warp(block.timestamp + 1); registryCoordinator.registerOperatorWithChurn({ @@ -221,14 +223,16 @@ contract User is Test { }); } - function deregisterOperator(bytes calldata quorums) public createSnapshot virtual { + function deregisterOperator( + bytes calldata quorums + ) public virtual createSnapshot { _log("deregisterOperator", quorums); registryCoordinator.deregisterOperator(quorums); } /// @dev Uses updateOperators to update this user's stake - function updateStakes() public createSnapshot virtual { + function updateStakes() public virtual createSnapshot { _log("updateStakes (updateOperators)"); address[] memory addrs = new address[](1); @@ -240,21 +244,23 @@ contract User is Test { /** * Core contracts: */ - - function registerAsOperator() public createSnapshot virtual { + function registerAsOperator() public virtual createSnapshot { _log("registerAsOperator (core)"); /// TODO: check - delegationManager.registerAsOperator(msg.sender,0, NAME); + delegationManager.registerAsOperator(msg.sender, 0, NAME); } // Deposit LSTs into the StrategyManager. This setup does not use the EPMgr or native ETH. - function depositIntoEigenlayer(IStrategy[] memory strategies, uint[] memory tokenBalances) public createSnapshot virtual { + function depositIntoEigenlayer( + IStrategy[] memory strategies, + uint256[] memory tokenBalances + ) public virtual createSnapshot { _log("depositIntoEigenLayer (core)"); - for (uint i = 0; i < strategies.length; i++) { + for (uint256 i = 0; i < strategies.length; i++) { IStrategy strat = strategies[i]; - uint tokenBalance = tokenBalances[i]; + uint256 tokenBalance = tokenBalances[i]; IERC20 underlyingToken = strat.underlyingToken(); underlyingToken.approve(address(strategyManager), tokenBalance); @@ -262,12 +268,19 @@ contract User is Test { } } - function exitEigenlayer() public createSnapshot virtual returns (IStrategy[] memory, uint256[] memory) { + function exitEigenlayer() + public + virtual + createSnapshot + returns (IStrategy[] memory, uint256[] memory) + { _log("exitEigenlayer (core)"); - (IStrategy[] memory strategies, uint256[] memory shares) = delegationManager.getDepositedShares(address(this)); + (IStrategy[] memory strategies, uint256[] memory shares) = + delegationManager.getDepositedShares(address(this)); - IDelegationManagerTypes.QueuedWithdrawalParams[] memory params = new IDelegationManager.QueuedWithdrawalParams[](1); + IDelegationManagerTypes.QueuedWithdrawalParams[] memory params = + new IDelegationManager.QueuedWithdrawalParams[](1); params[0] = IDelegationManagerTypes.QueuedWithdrawalParams({ strategies: strategies, depositShares: shares, @@ -296,8 +309,12 @@ contract User is Test { return pubkeyParams.pubkeyG1; } - function _genAVSRegistrationSig() internal returns (ISignatureUtils.SignatureWithSaltAndExpiry memory) { - ISignatureUtils.SignatureWithSaltAndExpiry memory signature = ISignatureUtils.SignatureWithSaltAndExpiry({ + function _genAVSRegistrationSig() + internal + returns (ISignatureUtils.SignatureWithSaltAndExpiry memory) + { + ISignatureUtils.SignatureWithSaltAndExpiry memory signature = ISignatureUtils + .SignatureWithSaltAndExpiry({ signature: new bytes(0), salt: bytes32(salt++), expiry: type(uint256).max @@ -315,7 +332,9 @@ contract User is Test { } // Operator0.registerOperator - function _log(string memory s) internal virtual { + function _log( + string memory s + ) internal virtual { emit log(string.concat(NAME, ".", s)); } @@ -340,7 +359,7 @@ contract User is Test { emit log_named_string("- churnQuorums", churnQuorums.toString()); string memory targetString = "["; - for (uint i = 0; i < churnTargets.length; i++) { + for (uint256 i = 0; i < churnTargets.length; i++) { if (i == churnTargets.length - 1) { targetString = string.concat(targetString, churnTargets[i].NAME()); } else { @@ -354,7 +373,6 @@ contract User is Test { } contract User_AltMethods is User { - using BitmapUtils for *; modifier createSnapshot() virtual override { @@ -363,12 +381,17 @@ contract User_AltMethods is User { _; } - constructor(string memory name, uint _privKey, IBLSApkRegistry.PubkeyRegistrationParams memory _pubkeyParams) - User(name, _privKey, _pubkeyParams) {} + constructor( + string memory name, + uint256 _privKey, + IBLSApkRegistry.PubkeyRegistrationParams memory _pubkeyParams + ) User(name, _privKey, _pubkeyParams) {} /// @dev Rather than calling deregisterOperator, this pranks the ejector and calls /// ejectOperator - function deregisterOperator(bytes calldata quorums) public createSnapshot virtual override { + function deregisterOperator( + bytes calldata quorums + ) public virtual override createSnapshot { _log("deregisterOperator (eject)", quorums); address ejector = registryCoordinator.ejector(); @@ -378,19 +401,21 @@ contract User_AltMethods is User { } /// @dev Uses updateOperatorsForQuorum to update stakes of all operators in all quorums - function updateStakes() public createSnapshot virtual override { + function updateStakes() public virtual override createSnapshot { _log("updateStakes (updateOperatorsForQuorum)"); - bytes memory allQuorums = ((1 << registryCoordinator.quorumCount()) - 1).bitmapToBytesArray(); + bytes memory allQuorums = + ((1 << registryCoordinator.quorumCount()) - 1).bitmapToBytesArray(); address[][] memory operatorsPerQuorum = new address[][](allQuorums.length); - for (uint i = 0; i < allQuorums.length; i++) { + for (uint256 i = 0; i < allQuorums.length; i++) { uint8 quorum = uint8(allQuorums[i]); - bytes32[] memory operatorIds = indexRegistry.getOperatorListAtBlockNumber(quorum, uint32(block.number)); + bytes32[] memory operatorIds = + indexRegistry.getOperatorListAtBlockNumber(quorum, uint32(block.number)); operatorsPerQuorum[i] = new address[](operatorIds.length); - for (uint j = 0; j < operatorIds.length; j++) { + for (uint256 j = 0; j < operatorIds.length; j++) { operatorsPerQuorum[i][j] = blsApkRegistry.getOperatorFromPubkeyHash(operatorIds[j]); } diff --git a/test/integration/mocks/BeaconChainOracleMock.t.sol b/test/integration/mocks/BeaconChainOracleMock.t.sol index 5c2e4b77..766bb8e7 100644 --- a/test/integration/mocks/BeaconChainOracleMock.t.sol +++ b/test/integration/mocks/BeaconChainOracleMock.t.sol @@ -11,7 +11,9 @@ contract BeaconChainOracleMock { mapping(uint64 => bytes32) blockRoots; - function timestampToBlockRoot(uint256 timestamp) public view returns (bytes32) { + function timestampToBlockRoot( + uint256 timestamp + ) public view returns (bytes32) { return blockRoots[uint64(timestamp)]; } @@ -19,4 +21,3 @@ contract BeaconChainOracleMock { blockRoots[timestamp] = blockRoot; } } - diff --git a/test/integration/tests/Full_Register_Deregister.t.sol b/test/integration/tests/Full_Register_Deregister.t.sol index 2561aa2c..be7f672b 100644 --- a/test/integration/tests/Full_Register_Deregister.t.sol +++ b/test/integration/tests/Full_Register_Deregister.t.sol @@ -6,13 +6,14 @@ import "test/integration/User.t.sol"; import "test/integration/IntegrationChecks.t.sol"; contract Integration_Full_Register_Deregister is IntegrationChecks { - using BitmapUtils for *; // 1. Register for all quorums by churning old operators // 2. Deregister from all quorums // 3. Re-register for all quorums without needing churn - function testFuzz_churnAll_deregisterAll_reregisterAll(uint24 _random) public { + function testFuzz_churnAll_deregisterAll_reregisterAll( + uint24 _random + ) public { _configRand({ _randomSeed: _random, _userTypes: DEFAULT | ALT_METHODS, @@ -60,7 +61,9 @@ contract Integration_Full_Register_Deregister is IntegrationChecks { // 2. Deregister from all quorums // 3. Old operators re-register for quorums // 4. Original operator re-registers for all quorums by churning old operators again - function testFuzz_churnAll_deregisterAll_oldReregisterAll(uint24 _random) public { + function testFuzz_churnAll_deregisterAll_oldReregisterAll( + uint24 _random + ) public { _configRand({ _randomSeed: _random, _userTypes: DEFAULT | ALT_METHODS, @@ -101,7 +104,7 @@ contract Integration_Full_Register_Deregister is IntegrationChecks { // 3. Old operators re-register for quorums // Note: churnTargets.length == quorums.length, so we do these one at a time - for (uint i = 0; i < churnTargets.length; i++) { + for (uint256 i = 0; i < churnTargets.length; i++) { User churnTarget = churnTargets[i]; bytes memory quorum = new bytes(1); quorum[0] = quorums[i]; @@ -123,7 +126,9 @@ contract Integration_Full_Register_Deregister is IntegrationChecks { // 1. Register for *some* quorums with churn, and the rest without churn // 2. Deregister from all quorums // 3. Re-register for all quorums without needing churn - function testFuzz_churnSome_deregisterSome_deregisterRemaining(uint24 _random) public { + function testFuzz_churnSome_deregisterSome_deregisterRemaining( + uint24 _random + ) public { _configRand({ _randomSeed: _random, _userTypes: DEFAULT | ALT_METHODS, @@ -140,11 +145,9 @@ contract Integration_Full_Register_Deregister is IntegrationChecks { // Select some quorums to register using churn, and the rest without churn bytes memory churnQuorums = _selectRand(quorums); - bytes memory standardQuorums = - quorums - .orderedBytesArrayToBitmap() - .minus(churnQuorums.orderedBytesArrayToBitmap()) - .bitmapToBytesArray(); + bytes memory standardQuorums = quorums.orderedBytesArrayToBitmap().minus( + churnQuorums.orderedBytesArrayToBitmap() + ).bitmapToBytesArray(); // Select churnable operators in each quorum. If needed, deals/deposits assets // for the operator, and deregisters operators from standardQuorums to make room diff --git a/test/integration/tests/NonFull_Register_CoreBalanceChange_Update.t.sol b/test/integration/tests/NonFull_Register_CoreBalanceChange_Update.t.sol index d9b74e8d..679ea1b5 100644 --- a/test/integration/tests/NonFull_Register_CoreBalanceChange_Update.t.sol +++ b/test/integration/tests/NonFull_Register_CoreBalanceChange_Update.t.sol @@ -6,12 +6,13 @@ import "test/integration/User.t.sol"; import "test/integration/IntegrationChecks.t.sol"; contract Integration_NonFull_Register_CoreBalanceChange_Update is IntegrationChecks { - // 1. Register for all quorums // 2. (core) Deposit additional tokens // 3. Update stakes // 4. Deregister from all quorums - function testFuzz_registerAll_increaseCoreBalance_update_deregisterAll(uint24 _random) public { + function testFuzz_registerAll_increaseCoreBalance_update_deregisterAll( + uint24 _random + ) public { _configRand({ _randomSeed: _random, _userTypes: DEFAULT | ALT_METHODS, @@ -33,10 +34,7 @@ contract Integration_NonFull_Register_CoreBalanceChange_Update is IntegrationChe check_Register_State(operator, quorums); // Award operator tokens to deposit into core - ( - IStrategy[] memory strategies, - uint[] memory tokenBalances - ) = _dealRandTokens(operator); + (IStrategy[] memory strategies, uint256[] memory tokenBalances) = _dealRandTokens(operator); // 2. (core) Deposit tokens and return the weight added in each initialized quorum operator.depositIntoEigenlayer(strategies, tokenBalances); @@ -56,7 +54,9 @@ contract Integration_NonFull_Register_CoreBalanceChange_Update is IntegrationChe // 1. Register for all quorums // 2. (core) Deposit additional tokens // 3. Deregister from all quorums - function testFuzz_registerAll_increaseCoreBalance_deregisterAll(uint24 _random) public { + function testFuzz_registerAll_increaseCoreBalance_deregisterAll( + uint24 _random + ) public { _configRand({ _randomSeed: _random, _userTypes: DEFAULT | ALT_METHODS, @@ -78,10 +78,7 @@ contract Integration_NonFull_Register_CoreBalanceChange_Update is IntegrationChe check_Register_State(operator, quorums); // Award operator tokens to deposit into core - ( - IStrategy[] memory strategies, - uint[] memory tokenBalances - ) = _dealRandTokens(operator); + (IStrategy[] memory strategies, uint256[] memory tokenBalances) = _dealRandTokens(operator); // 2. (core) Deposit tokens operator.depositIntoEigenlayer(strategies, tokenBalances); @@ -96,7 +93,9 @@ contract Integration_NonFull_Register_CoreBalanceChange_Update is IntegrationChe // 1. Register for all quorums // 2. (core) Queue full withdrawal // 3. updateOperators/updateOperatorsForQuorum - function testFuzz_registerAll_decreaseCoreBalance_update(uint24 _random) public { + function testFuzz_registerAll_decreaseCoreBalance_update( + uint24 _random + ) public { _configRand({ _randomSeed: _random, _userTypes: DEFAULT | ALT_METHODS, @@ -129,7 +128,9 @@ contract Integration_NonFull_Register_CoreBalanceChange_Update is IntegrationChe // 1. Register for all quorums // 2. (core) Queue full withdrawal // 3. Deregister from all quorums - function testFuzz_registerAll_decreaseCoreBalance_deregisterAll(uint24 _random) public { + function testFuzz_registerAll_decreaseCoreBalance_deregisterAll( + uint24 _random + ) public { _configRand({ _randomSeed: _random, _userTypes: DEFAULT | ALT_METHODS, @@ -163,7 +164,9 @@ contract Integration_NonFull_Register_CoreBalanceChange_Update is IntegrationChe // 1. Register for all quorums // 2. updateOperators/updateOperatorsForQuorum // 3. Deregister from all quorums - function testFuzz_registerAll_update_deregisterAll(uint24 _random) public { + function testFuzz_registerAll_update_deregisterAll( + uint24 _random + ) public { _configRand({ _randomSeed: _random, _userTypes: DEFAULT | ALT_METHODS, diff --git a/test/integration/tests/NonFull_Register_Deregister.t.sol b/test/integration/tests/NonFull_Register_Deregister.t.sol index 6acf85cb..5eea66e4 100644 --- a/test/integration/tests/NonFull_Register_Deregister.t.sol +++ b/test/integration/tests/NonFull_Register_Deregister.t.sol @@ -6,12 +6,13 @@ import "test/integration/User.t.sol"; import "test/integration/IntegrationChecks.t.sol"; contract Integration_NonFull_Register_Deregister is IntegrationChecks { - using BitmapUtils for *; // 1. Register for all quorums // 2. Deregister from all quorums - function testFuzz_registerAll_deregisterAll(uint24 _random) public { + function testFuzz_registerAll_deregisterAll( + uint24 _random + ) public { _configRand({ _randomSeed: _random, _userTypes: DEFAULT | ALT_METHODS, @@ -41,7 +42,9 @@ contract Integration_NonFull_Register_Deregister is IntegrationChecks { // 1. Register for some quorums // 2. Deregister from some quorums // 3. Deregister from any remaining quorums - function testFuzz_registerSome_deregisterSome_deregisterRemaining(uint24 _random) public { + function testFuzz_registerSome_deregisterSome_deregisterRemaining( + uint24 _random + ) public { _configRand({ _randomSeed: _random, _userTypes: DEFAULT | ALT_METHODS, @@ -69,7 +72,7 @@ contract Integration_NonFull_Register_Deregister is IntegrationChecks { check_Deregister_State(operator, quorumsToRemove); // 3. Deregister from any remaining quorums - bytes memory quorumsRemaining = _calcRemaining({ start: quorums, removed: quorumsToRemove }); + bytes memory quorumsRemaining = _calcRemaining({start: quorums, removed: quorumsToRemove}); if (quorumsRemaining.length != 0) { operator.deregisterOperator(quorumsRemaining); check_Deregister_State(operator, quorumsRemaining); @@ -80,7 +83,9 @@ contract Integration_NonFull_Register_Deregister is IntegrationChecks { // 1. Register for some quorums // 2. Deregister from some quorums // 3. Reregister for some quorums - function testFuzz_registerSome_deregisterSome_reregisterSome(uint24 _random) public { + function testFuzz_registerSome_deregisterSome_reregisterSome( + uint24 _random + ) public { _configRand({ _randomSeed: _random, _userTypes: DEFAULT | ALT_METHODS, diff --git a/test/integration/utils/BitmapStrings.t.sol b/test/integration/utils/BitmapStrings.t.sol index 2bcec384..7235dab5 100644 --- a/test/integration/utils/BitmapStrings.t.sol +++ b/test/integration/utils/BitmapStrings.t.sol @@ -4,27 +4,21 @@ pragma solidity ^0.8.27; import "@openzeppelin/contracts/utils/Strings.sol"; library BitmapStrings { - using Strings for *; /// @dev Given an input quorum array, returns a nice, readable string: /// e.g. [0, 1, 2, ...] /// (This is way more readable than logging with log_named_bytes) - function toString(bytes memory bitmapArr) internal pure returns (string memory) { + function toString( + bytes memory bitmapArr + ) internal pure returns (string memory) { string memory result = "["; - for (uint i = 0; i < bitmapArr.length; i++) { + for (uint256 i = 0; i < bitmapArr.length; i++) { if (i == bitmapArr.length - 1) { - result = string.concat( - result, - uint(uint8(bitmapArr[i])).toString() - ); + result = string.concat(result, uint256(uint8(bitmapArr[i])).toString()); } else { - result = string.concat( - result, - uint(uint8(bitmapArr[i])).toString(), - ", " - ); + result = string.concat(result, uint256(uint8(bitmapArr[i])).toString(), ", "); } } diff --git a/test/integration/utils/Sort.t.sol b/test/integration/utils/Sort.t.sol index 968400c6..884a02f5 100644 --- a/test/integration/utils/Sort.t.sol +++ b/test/integration/utils/Sort.t.sol @@ -8,7 +8,9 @@ library Sort { * @param addresses The array of addresses to be sorted. * @return sortedAddresses The array of addresses sorted in ascending order. */ - function sortAddresses(address[] memory addresses) internal pure returns (address[] memory) { + function sortAddresses( + address[] memory addresses + ) internal pure returns (address[] memory) { uint256 n = addresses.length; for (uint256 i = 0; i < n; i++) { for (uint256 j = 0; j < n - 1; j++) { diff --git a/test/mocks/AVSDirectoryMock.sol b/test/mocks/AVSDirectoryMock.sol index ca3613ef..0271add0 100644 --- a/test/mocks/AVSDirectoryMock.sol +++ b/test/mocks/AVSDirectoryMock.sol @@ -1,174 +1,154 @@ // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.27; -import {IAVSDirectory } from "eigenlayer-contracts/src/contracts/interfaces/IAVSDirectory.sol"; +import {IAVSDirectory} from "eigenlayer-contracts/src/contracts/interfaces/IAVSDirectory.sol"; import {OperatorSet} from "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; import {ISignatureUtils} from "eigenlayer-contracts/src/contracts/interfaces/ISignatureUtils.sol"; import {IStrategy} from "eigenlayer-contracts/src/contracts/interfaces/IStrategy.sol"; import {IPauserRegistry} from "eigenlayer-contracts/src/contracts/interfaces/IPauserRegistry.sol"; contract AVSDirectoryMock is IAVSDirectory { - function initialize( - address initialOwner, - uint256 initialPausedStatus - ) external {} - - function createOperatorSets( - uint32[] calldata operatorSetIds - ) external {} - - function becomeOperatorSetAVS() external {} - - function migrateOperatorsToOperatorSets( - address[] calldata operators, - uint32[][] calldata operatorSetIds - ) external {} - - function registerOperatorToOperatorSets( - address operator, - uint32[] calldata operatorSetIds, - ISignatureUtils.SignatureWithSaltAndExpiry memory operatorSignature - ) external {} - - function forceDeregisterFromOperatorSets( - address operator, - address avs, - uint32[] calldata operatorSetIds, - ISignatureUtils.SignatureWithSaltAndExpiry memory operatorSignature - ) external {} - - function deregisterOperatorFromOperatorSets( - address operator, - uint32[] calldata operatorSetIds - ) external {} - - function addStrategiesToOperatorSet( - uint32 operatorSetId, - IStrategy[] calldata strategies - ) external {} - - function removeStrategiesFromOperatorSet( - uint32 operatorSetId, - IStrategy[] calldata strategies - ) external {} - - function updateAVSMetadataURI( - string calldata metadataURI - ) external {} - - function cancelSalt(bytes32 salt) external {} - - function registerOperatorToAVS( - address operator, - ISignatureUtils.SignatureWithSaltAndExpiry memory operatorSignature - ) external {} - - function deregisterOperatorFromAVS(address operator) external {} - - function operatorSaltIsSpent( - address operator, - bytes32 salt - ) external view returns (bool) {} - - function isOperatorSetAVS( - address avs - ) external view returns (bool) {} - - function isOperatorSet( - address avs, - uint32 operatorSetId - ) external view returns (bool) {} - - function getNumOperatorSetsOfOperator( - address operator - ) external view returns (uint256) {} - - function inTotalOperatorSets( - address operator - ) external view returns (uint256) {} - - function calculateOperatorAVSRegistrationDigestHash( - address operator, - address avs, - bytes32 salt, - uint256 expiry - ) external view returns (bytes32) {} - - function calculateOperatorSetRegistrationDigestHash( - address avs, - uint32[] calldata operatorSetIds, - bytes32 salt, - uint256 expiry - ) external view returns (bytes32) {} - - function calculateOperatorSetForceDeregistrationTypehash( - address avs, - uint32[] calldata operatorSetIds, - bytes32 salt, - uint256 expiry - ) external view returns (bytes32) {} - - function OPERATOR_AVS_REGISTRATION_TYPEHASH() - external - view - - returns (bytes32) - {} - - function OPERATOR_SET_REGISTRATION_TYPEHASH() - external - view - - returns (bytes32) - {} - - function operatorSetStatus( - address avs, - address operator, - uint32 operatorSetId - ) - external - view - - returns (bool registered, uint32 lastDeregisteredTimestamp) - {} - - function initialize( - address initialOwner, - IPauserRegistry _pauserRegistry, - uint256 initialPausedStatus - ) external {} - - function operatorSetMemberAtIndex( - OperatorSet memory operatorSet, - uint256 index - ) external view returns (address) {} - - function getOperatorsInOperatorSet( - OperatorSet memory operatorSet, - uint256 start, - uint256 length - ) external view returns (address[] memory operators) {} - - function getStrategiesInOperatorSet( - OperatorSet memory operatorSet - ) external view returns (IStrategy[] memory strategies) {} - - function getNumOperatorsInOperatorSet( - OperatorSet memory operatorSet - ) external view returns (uint256) {} - - function isMember( - address operator, - OperatorSet memory operatorSet - ) external view returns (bool) {} - - function isOperatorSlashable( - address operator, - OperatorSet memory operatorSet - ) external view returns (bool) {} - - function isOperatorSetBatch( - OperatorSet[] calldata operatorSets - ) external view returns (bool) {} -} \ No newline at end of file + function initialize(address initialOwner, uint256 initialPausedStatus) external {} + + function createOperatorSets( + uint32[] calldata operatorSetIds + ) external {} + + function becomeOperatorSetAVS() external {} + + function migrateOperatorsToOperatorSets( + address[] calldata operators, + uint32[][] calldata operatorSetIds + ) external {} + + function registerOperatorToOperatorSets( + address operator, + uint32[] calldata operatorSetIds, + ISignatureUtils.SignatureWithSaltAndExpiry memory operatorSignature + ) external {} + + function forceDeregisterFromOperatorSets( + address operator, + address avs, + uint32[] calldata operatorSetIds, + ISignatureUtils.SignatureWithSaltAndExpiry memory operatorSignature + ) external {} + + function deregisterOperatorFromOperatorSets( + address operator, + uint32[] calldata operatorSetIds + ) external {} + + function addStrategiesToOperatorSet( + uint32 operatorSetId, + IStrategy[] calldata strategies + ) external {} + + function removeStrategiesFromOperatorSet( + uint32 operatorSetId, + IStrategy[] calldata strategies + ) external {} + + function updateAVSMetadataURI( + string calldata metadataURI + ) external {} + + function cancelSalt( + bytes32 salt + ) external {} + + function registerOperatorToAVS( + address operator, + ISignatureUtils.SignatureWithSaltAndExpiry memory operatorSignature + ) external {} + + function deregisterOperatorFromAVS( + address operator + ) external {} + + function operatorSaltIsSpent(address operator, bytes32 salt) external view returns (bool) {} + + function isOperatorSetAVS( + address avs + ) external view returns (bool) {} + + function isOperatorSet(address avs, uint32 operatorSetId) external view returns (bool) {} + + function getNumOperatorSetsOfOperator( + address operator + ) external view returns (uint256) {} + + function inTotalOperatorSets( + address operator + ) external view returns (uint256) {} + + function calculateOperatorAVSRegistrationDigestHash( + address operator, + address avs, + bytes32 salt, + uint256 expiry + ) external view returns (bytes32) {} + + function calculateOperatorSetRegistrationDigestHash( + address avs, + uint32[] calldata operatorSetIds, + bytes32 salt, + uint256 expiry + ) external view returns (bytes32) {} + + function calculateOperatorSetForceDeregistrationTypehash( + address avs, + uint32[] calldata operatorSetIds, + bytes32 salt, + uint256 expiry + ) external view returns (bytes32) {} + + function OPERATOR_AVS_REGISTRATION_TYPEHASH() external view returns (bytes32) {} + + function OPERATOR_SET_REGISTRATION_TYPEHASH() external view returns (bytes32) {} + + function operatorSetStatus( + address avs, + address operator, + uint32 operatorSetId + ) external view returns (bool registered, uint32 lastDeregisteredTimestamp) {} + + function initialize( + address initialOwner, + IPauserRegistry _pauserRegistry, + uint256 initialPausedStatus + ) external {} + + function operatorSetMemberAtIndex( + OperatorSet memory operatorSet, + uint256 index + ) external view returns (address) {} + + function getOperatorsInOperatorSet( + OperatorSet memory operatorSet, + uint256 start, + uint256 length + ) external view returns (address[] memory operators) {} + + function getStrategiesInOperatorSet( + OperatorSet memory operatorSet + ) external view returns (IStrategy[] memory strategies) {} + + function getNumOperatorsInOperatorSet( + OperatorSet memory operatorSet + ) external view returns (uint256) {} + + function isMember( + address operator, + OperatorSet memory operatorSet + ) external view returns (bool) {} + + function isOperatorSlashable( + address operator, + OperatorSet memory operatorSet + ) external view returns (bool) {} + + function isOperatorSetBatch( + OperatorSet[] calldata operatorSets + ) external view returns (bool) {} +} diff --git a/test/mocks/AllocationManagerMock.sol b/test/mocks/AllocationManagerMock.sol index b355af95..22b92b74 100644 --- a/test/mocks/AllocationManagerMock.sol +++ b/test/mocks/AllocationManagerMock.sol @@ -1,175 +1,154 @@ // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.27; -import {IAllocationManager, OperatorSet} from "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; -import {IAVSRegistrar } from "eigenlayer-contracts/src/contracts/interfaces/IAVSRegistrar.sol"; +import { + IAllocationManager, + OperatorSet +} from "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; +import {IAVSRegistrar} from "eigenlayer-contracts/src/contracts/interfaces/IAVSRegistrar.sol"; import {IStrategy} from "eigenlayer-contracts/src/contracts/interfaces/IStrategy.sol"; import {IPauserRegistry} from "eigenlayer-contracts/src/contracts/interfaces/IPauserRegistry.sol"; + contract AllocationManagerIntermediate is IAllocationManager { - function initialize( - address initialOwner, - uint256 initialPausedStatus - ) external virtual {} - - function slashOperator( - address avs, - SlashingParams calldata params - ) external virtual {} - - function modifyAllocations( - address operator, - AllocateParams[] calldata params - ) external virtual {} - - function clearDeallocationQueue( - address operator, - IStrategy[] calldata strategies, - uint16[] calldata numToClear - ) external virtual {} - - function registerForOperatorSets( - address operator, - RegisterParams calldata params - ) external virtual {} - - function deregisterFromOperatorSets( - DeregisterParams calldata params - ) external virtual {} - - function setAllocationDelay( - address operator, - uint32 delay - ) external virtual {} - - function setAVSRegistrar( - address avs, - IAVSRegistrar registrar - ) external virtual {} - - function updateAVSMetadataURI( - address avs, - string calldata metadataURI - ) external virtual {} - - function createOperatorSets( - address avs, - CreateSetParams[] calldata params - ) external virtual {} - - function addStrategiesToOperatorSet( - address avs, - uint32 operatorSetId, - IStrategy[] calldata strategies - ) external virtual {} - - function removeStrategiesFromOperatorSet( - address avs, - uint32 operatorSetId, - IStrategy[] calldata strategies - ) external virtual {} - - function getOperatorSetCount( - address avs - ) external view virtual returns (uint256) {} - - function getAllocatedSets( - address operator - ) external view virtual returns (OperatorSet[] memory) {} - - function getAllocatedStrategies( - address operator, - OperatorSet memory operatorSet - ) external view virtual returns (IStrategy[] memory) {} - - function getAllocation( - address operator, - OperatorSet memory operatorSet, - IStrategy strategy - ) external view virtual returns (Allocation memory) {} - - function getAllocations( - address[] memory operators, - OperatorSet memory operatorSet, - IStrategy strategy - ) external view virtual returns (Allocation[] memory) {} - - function getStrategyAllocations( - address operator, - IStrategy strategy - ) - external - view - virtual - returns (OperatorSet[] memory, Allocation[] memory) - {} - - function getAllocatableMagnitude( - address operator, - IStrategy strategy - ) external view virtual returns (uint64) {} - - function getMaxMagnitude( - address operator, - IStrategy strategy - ) external view virtual returns (uint64) {} - - function getMaxMagnitudes( - address operator, - IStrategy[] calldata strategies - ) external view virtual returns (uint64[] memory) {} - - function getMaxMagnitudes( - address[] calldata operators, - IStrategy strategy - ) external view virtual returns (uint64[] memory) {} - - function getMaxMagnitudesAtBlock( - address operator, - IStrategy[] calldata strategies, - uint32 blockNumber - ) external view virtual returns (uint64[] memory) {} - - function getAllocationDelay( - address operator - ) external view virtual returns (bool isSet, uint32 delay) {} - - function getRegisteredSets( - address operator - ) external view virtual returns (OperatorSet[] memory operatorSets) {} - - function isOperatorSet( - OperatorSet memory operatorSet - ) external view virtual returns (bool) {} - - function getMembers( - OperatorSet memory operatorSet - ) external view virtual returns (address[] memory operators) {} - - function getMemberCount( - OperatorSet memory operatorSet - ) external view virtual returns (uint256) {} - - function getAVSRegistrar( - address avs - ) external view virtual returns (IAVSRegistrar) {} - - function getStrategiesInOperatorSet( - OperatorSet memory operatorSet - ) external view virtual returns (IStrategy[] memory strategies) {} - - function getMinimumSlashableStake( - OperatorSet memory operatorSet, - address[] memory operators, - IStrategy[] memory strategies, - uint32 futureBlock - ) external view virtual returns (uint256[][] memory slashableStake) {} - - function isMemberOfOperatorSet( - address operator, - OperatorSet memory operatorSet - ) external view virtual returns (bool) {} + function initialize(address initialOwner, uint256 initialPausedStatus) external virtual {} + + function slashOperator(address avs, SlashingParams calldata params) external virtual {} + + function modifyAllocations( + address operator, + AllocateParams[] calldata params + ) external virtual {} + + function clearDeallocationQueue( + address operator, + IStrategy[] calldata strategies, + uint16[] calldata numToClear + ) external virtual {} + + function registerForOperatorSets( + address operator, + RegisterParams calldata params + ) external virtual {} + + function deregisterFromOperatorSets( + DeregisterParams calldata params + ) external virtual {} + + function setAllocationDelay(address operator, uint32 delay) external virtual {} + + function setAVSRegistrar(address avs, IAVSRegistrar registrar) external virtual {} + + function updateAVSMetadataURI(address avs, string calldata metadataURI) external virtual {} + + function createOperatorSets(address avs, CreateSetParams[] calldata params) external virtual {} + + function addStrategiesToOperatorSet( + address avs, + uint32 operatorSetId, + IStrategy[] calldata strategies + ) external virtual {} + + function removeStrategiesFromOperatorSet( + address avs, + uint32 operatorSetId, + IStrategy[] calldata strategies + ) external virtual {} + + function getOperatorSetCount( + address avs + ) external view virtual returns (uint256) {} + + function getAllocatedSets( + address operator + ) external view virtual returns (OperatorSet[] memory) {} + + function getAllocatedStrategies( + address operator, + OperatorSet memory operatorSet + ) external view virtual returns (IStrategy[] memory) {} + + function getAllocation( + address operator, + OperatorSet memory operatorSet, + IStrategy strategy + ) external view virtual returns (Allocation memory) {} + + function getAllocations( + address[] memory operators, + OperatorSet memory operatorSet, + IStrategy strategy + ) external view virtual returns (Allocation[] memory) {} + + function getStrategyAllocations( + address operator, + IStrategy strategy + ) external view virtual returns (OperatorSet[] memory, Allocation[] memory) {} + + function getAllocatableMagnitude( + address operator, + IStrategy strategy + ) external view virtual returns (uint64) {} + + function getMaxMagnitude( + address operator, + IStrategy strategy + ) external view virtual returns (uint64) {} + + function getMaxMagnitudes( + address operator, + IStrategy[] calldata strategies + ) external view virtual returns (uint64[] memory) {} + + function getMaxMagnitudes( + address[] calldata operators, + IStrategy strategy + ) external view virtual returns (uint64[] memory) {} + + function getMaxMagnitudesAtBlock( + address operator, + IStrategy[] calldata strategies, + uint32 blockNumber + ) external view virtual returns (uint64[] memory) {} + + function getAllocationDelay( + address operator + ) external view virtual returns (bool isSet, uint32 delay) {} + + function getRegisteredSets( + address operator + ) external view virtual returns (OperatorSet[] memory operatorSets) {} + + function isOperatorSet( + OperatorSet memory operatorSet + ) external view virtual returns (bool) {} + + function getMembers( + OperatorSet memory operatorSet + ) external view virtual returns (address[] memory operators) {} + + function getMemberCount( + OperatorSet memory operatorSet + ) external view virtual returns (uint256) {} + + function getAVSRegistrar( + address avs + ) external view virtual returns (IAVSRegistrar) {} + + function getStrategiesInOperatorSet( + OperatorSet memory operatorSet + ) external view virtual returns (IStrategy[] memory strategies) {} + + function getMinimumSlashableStake( + OperatorSet memory operatorSet, + address[] memory operators, + IStrategy[] memory strategies, + uint32 futureBlock + ) external view virtual returns (uint256[][] memory slashableStake) {} + + function isMemberOfOperatorSet( + address operator, + OperatorSet memory operatorSet + ) external view virtual returns (bool) {} } -contract AllocationManagerMock is AllocationManagerIntermediate { - -} \ No newline at end of file +contract AllocationManagerMock is AllocationManagerIntermediate {} diff --git a/test/mocks/DelegationMock.sol b/test/mocks/DelegationMock.sol index 36f973da..ff04b970 100644 --- a/test/mocks/DelegationMock.sol +++ b/test/mocks/DelegationMock.sol @@ -4,7 +4,8 @@ pragma solidity ^0.8.27; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {console2 as console} from "forge-std/Test.sol"; -import {IDelegationManager} from "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; +import {IDelegationManager} from + "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; import {IStrategyManager} from "eigenlayer-contracts/src/contracts/interfaces/IStrategyManager.sol"; import {StrategyManager} from "eigenlayer-contracts/src/contracts/core/StrategyManager.sol"; import {IStrategy} from "eigenlayer-contracts/src/contracts/interfaces/IStrategy.sol"; @@ -13,265 +14,250 @@ import {ISignatureUtils} from "eigenlayer-contracts/src/contracts/interfaces/ISi import {SlashingLib} from "eigenlayer-contracts/src/contracts/libraries/SlashingLib.sol"; contract DelegationIntermediate is IDelegationManager { - function initialize( - address initialOwner, - uint256 initialPausedStatus - ) external virtual {} - - function registerAsOperator( - OperatorDetails calldata registeringOperatorDetails, - uint32 allocationDelay, - string calldata metadataURI - ) external virtual {} - - function modifyOperatorDetails( - OperatorDetails calldata newOperatorDetails - ) external virtual {} - - function updateOperatorMetadataURI( - string calldata metadataURI - ) external virtual {} - - function delegateTo( - address operator, - SignatureWithExpiry memory approverSignatureAndExpiry, - bytes32 approverSalt - ) external virtual {} - - function undelegate( - address staker - ) external virtual returns (bytes32[] memory withdrawalRoots) {} - - function queueWithdrawals( - QueuedWithdrawalParams[] calldata params - ) external virtual returns (bytes32[] memory) {} - - function completeQueuedWithdrawals( - IERC20[][] calldata tokens, - bool[] calldata receiveAsTokens, - uint256 numToComplete - ) external virtual {} - - function completeQueuedWithdrawal( - Withdrawal calldata withdrawal, - IERC20[] calldata tokens, - bool receiveAsTokens - ) external virtual {} - - function completeQueuedWithdrawals( - Withdrawal[] calldata withdrawals, - IERC20[][] calldata tokens, - bool[] calldata receiveAsTokens - ) external virtual {} - - function increaseDelegatedShares( - address staker, - IStrategy strategy, - uint256 existingDepositShares, - uint256 addedShares - ) external virtual {} - - function decreaseBeaconChainScalingFactor( - address staker, - uint256 existingShares, - uint64 proportionOfOldBalance - ) external virtual {} - - function burnOperatorShares( - address operator, - IStrategy strategy, - uint64 prevMaxMagnitude, - uint64 newMaxMagnitude - ) external virtual {} - - function completeQueuedWithdrawal( - Withdrawal calldata withdrawal, - IERC20[] calldata tokens, - uint256 middlewareTimesIndex, - bool receiveAsTokens - ) external virtual {} - - function completeQueuedWithdrawals( - Withdrawal[] calldata withdrawals, - IERC20[][] calldata tokens, - uint256[] calldata middlewareTimesIndexes, - bool[] calldata receiveAsTokens - ) external virtual {} - - function delegatedTo( - address staker - ) external view virtual returns (address) {} - - function delegationApproverSaltIsSpent( - address _delegationApprover, - bytes32 salt - ) external view virtual returns (bool) {} - - function cumulativeWithdrawalsQueued( - address staker - ) external view virtual returns (uint256) {} - - function isDelegated(address staker) external view virtual returns (bool) {} - - function isOperator(address operator) external view virtual returns (bool) {} - - function operatorDetails( - address operator - ) external view virtual returns (OperatorDetails memory) {} - - function delegationApprover( - address operator - ) external view virtual returns (address) {} - - function getOperatorShares( - address operator, - IStrategy[] memory strategies - ) external view virtual returns (uint256[] memory) {} - - function getOperatorsShares( - address[] memory operators, - IStrategy[] memory strategies - ) external view virtual returns (uint256[][] memory) {} - - function getSlashableSharesInQueue( - address operator, - IStrategy strategy - ) external view virtual returns (uint256) {} - - function getWithdrawableShares( - address staker, - IStrategy[] memory strategies - ) - external - view - virtual - override - returns ( - uint256[] memory withdrawableShares, - uint256[] memory depositShares + function initialize(address initialOwner, uint256 initialPausedStatus) external virtual {} + + function registerAsOperator( + OperatorDetails calldata registeringOperatorDetails, + uint32 allocationDelay, + string calldata metadataURI + ) external virtual {} + + function modifyOperatorDetails( + OperatorDetails calldata newOperatorDetails + ) external virtual {} + + function updateOperatorMetadataURI( + string calldata metadataURI + ) external virtual {} + + function delegateTo( + address operator, + SignatureWithExpiry memory approverSignatureAndExpiry, + bytes32 approverSalt + ) external virtual {} + + function undelegate( + address staker + ) external virtual returns (bytes32[] memory withdrawalRoots) {} + + function queueWithdrawals( + QueuedWithdrawalParams[] calldata params + ) external virtual returns (bytes32[] memory) {} + + function completeQueuedWithdrawals( + IERC20[][] calldata tokens, + bool[] calldata receiveAsTokens, + uint256 numToComplete + ) external virtual {} + + function completeQueuedWithdrawal( + Withdrawal calldata withdrawal, + IERC20[] calldata tokens, + bool receiveAsTokens + ) external virtual {} + + function completeQueuedWithdrawals( + Withdrawal[] calldata withdrawals, + IERC20[][] calldata tokens, + bool[] calldata receiveAsTokens + ) external virtual {} + + function increaseDelegatedShares( + address staker, + IStrategy strategy, + uint256 existingDepositShares, + uint256 addedShares + ) external virtual {} + + function decreaseBeaconChainScalingFactor( + address staker, + uint256 existingShares, + uint64 proportionOfOldBalance + ) external virtual {} + + function burnOperatorShares( + address operator, + IStrategy strategy, + uint64 prevMaxMagnitude, + uint64 newMaxMagnitude + ) external virtual {} + + function completeQueuedWithdrawal( + Withdrawal calldata withdrawal, + IERC20[] calldata tokens, + uint256 middlewareTimesIndex, + bool receiveAsTokens + ) external virtual {} + + function completeQueuedWithdrawals( + Withdrawal[] calldata withdrawals, + IERC20[][] calldata tokens, + uint256[] calldata middlewareTimesIndexes, + bool[] calldata receiveAsTokens + ) external virtual {} + + function delegatedTo( + address staker + ) external view virtual returns (address) {} + + function delegationApproverSaltIsSpent( + address _delegationApprover, + bytes32 salt + ) external view virtual returns (bool) {} + + function cumulativeWithdrawalsQueued( + address staker + ) external view virtual returns (uint256) {} + + function isDelegated( + address staker + ) external view virtual returns (bool) {} + + function isOperator( + address operator + ) external view virtual returns (bool) {} + + function operatorDetails( + address operator + ) external view virtual returns (OperatorDetails memory) {} + + function delegationApprover( + address operator + ) external view virtual returns (address) {} + + function getOperatorShares( + address operator, + IStrategy[] memory strategies + ) external view virtual returns (uint256[] memory) {} + + function getOperatorsShares( + address[] memory operators, + IStrategy[] memory strategies + ) external view virtual returns (uint256[][] memory) {} + + function getSlashableSharesInQueue( + address operator, + IStrategy strategy + ) external view virtual returns (uint256) {} + + function getWithdrawableShares( + address staker, + IStrategy[] memory strategies + ) + external + view + virtual + override + returns (uint256[] memory withdrawableShares, uint256[] memory depositShares) + {} + + function getDepositedShares( + address staker + ) external view virtual returns (IStrategy[] memory, uint256[] memory) {} + + function depositScalingFactor( + address staker, + IStrategy strategy + ) external view virtual returns (uint256) {} + + function getBeaconChainSlashingFactor( + address staker + ) external view virtual returns (uint64) {} + + function getQueuedWithdrawals( + address staker ) - {} - - function getDepositedShares( - address staker - ) external view virtual returns (IStrategy[] memory, uint256[] memory) {} - - function depositScalingFactor( - address staker, - IStrategy strategy - ) external view virtual returns (uint256) {} - - function getBeaconChainSlashingFactor( - address staker - ) external view virtual returns (uint64) {} - - function getQueuedWithdrawals( - address staker - ) - external - view - virtual - override - returns (Withdrawal[] memory withdrawals, uint256[][] memory shares) - {} - - function calculateWithdrawalRoot( - Withdrawal memory withdrawal - ) external pure virtual returns (bytes32) {} - - function calculateDelegationApprovalDigestHash( - address staker, - address operator, - address _delegationApprover, - bytes32 approverSalt, - uint256 expiry - ) external view virtual returns (bytes32) {} - - function beaconChainETHStrategy() - external - view - virtual - override - returns (IStrategy) - {} - - function DELEGATION_APPROVAL_TYPEHASH() - external - view - virtual - override - returns (bytes32) - {} - - function registerAsOperator( - address initDelegationApprover, - uint32 allocationDelay, - string calldata metadataURI - ) external virtual {} - - function modifyOperatorDetails( - address operator, - address newDelegationApprover - ) external virtual {} - - function updateOperatorMetadataURI( - address operator, - string calldata metadataURI - ) external virtual {} - - function redelegate( - address newOperator, - SignatureWithExpiry memory newOperatorApproverSig, - bytes32 approverSalt - ) external virtual returns (bytes32[] memory withdrawalRoots) {} - - function decreaseDelegatedShares( - address staker, - uint256 curDepositShares, - uint64 prevBeaconChainSlashingFactor, - uint256 wadSlashed - ) external virtual {} - - function decreaseDelegatedShares( - address staker, - uint256 curDepositShares, - uint64 beaconChainSlashingFactorDecrease - ) external virtual {} - - function minWithdrawalDelayBlocks() - external - view - virtual - override - returns (uint32) - {} - - function slashOperatorShares( - address operator, - IStrategy strategy, - uint64 prevMaxMagnitude, - uint64 newMaxMagnitude - ) external override {} - - function getQueuedWithdrawal( - bytes32 withdrawalRoot - ) external view override returns (Withdrawal memory) {} - - function getQueuedWithdrawalRoots( - address staker - ) external view override returns (bytes32[] memory) {} - - function convertToDepositShares( - address staker, - IStrategy[] memory strategies, - uint256[] memory withdrawableShares - ) external view override returns (uint256[] memory) {} + external + view + virtual + override + returns (Withdrawal[] memory withdrawals, uint256[][] memory shares) + {} + + function calculateWithdrawalRoot( + Withdrawal memory withdrawal + ) external pure virtual returns (bytes32) {} + + function calculateDelegationApprovalDigestHash( + address staker, + address operator, + address _delegationApprover, + bytes32 approverSalt, + uint256 expiry + ) external view virtual returns (bytes32) {} + + function beaconChainETHStrategy() external view virtual override returns (IStrategy) {} + + function DELEGATION_APPROVAL_TYPEHASH() external view virtual override returns (bytes32) {} + + function registerAsOperator( + address initDelegationApprover, + uint32 allocationDelay, + string calldata metadataURI + ) external virtual {} + + function modifyOperatorDetails( + address operator, + address newDelegationApprover + ) external virtual {} + + function updateOperatorMetadataURI( + address operator, + string calldata metadataURI + ) external virtual {} + + function redelegate( + address newOperator, + SignatureWithExpiry memory newOperatorApproverSig, + bytes32 approverSalt + ) external virtual returns (bytes32[] memory withdrawalRoots) {} + + function decreaseDelegatedShares( + address staker, + uint256 curDepositShares, + uint64 prevBeaconChainSlashingFactor, + uint256 wadSlashed + ) external virtual {} + + function decreaseDelegatedShares( + address staker, + uint256 curDepositShares, + uint64 beaconChainSlashingFactorDecrease + ) external virtual {} + + function minWithdrawalDelayBlocks() external view virtual override returns (uint32) {} + + function slashOperatorShares( + address operator, + IStrategy strategy, + uint64 prevMaxMagnitude, + uint64 newMaxMagnitude + ) external override {} + + function getQueuedWithdrawal( + bytes32 withdrawalRoot + ) external view override returns (Withdrawal memory) {} + + function getQueuedWithdrawalRoots( + address staker + ) external view override returns (bytes32[] memory) {} + + function convertToDepositShares( + address staker, + IStrategy[] memory strategies, + uint256[] memory withdrawableShares + ) external view override returns (uint256[] memory) {} } contract DelegationMock is DelegationIntermediate { mapping(address => bool) internal _isOperator; mapping(address => mapping(IStrategy => uint256)) internal _weightOf; - function setOperatorShares(address operator, IStrategy strategy, uint256 actualWeight) external { + + function setOperatorShares( + address operator, + IStrategy strategy, + uint256 actualWeight + ) external { _weightOf[operator][strategy] = actualWeight; } @@ -279,7 +265,9 @@ contract DelegationMock is DelegationIntermediate { _isOperator[operator] = isOperator; } - function isOperator(address operator) external view override returns (bool) { + function isOperator( + address operator + ) external view override returns (bool) { return _isOperator[operator]; } @@ -293,7 +281,8 @@ contract DelegationMock is DelegationIntermediate { } return shares; } - function minWithdrawalDelayBlocks() external view override returns (uint32){ - return 10000; + + function minWithdrawalDelayBlocks() external view override returns (uint32) { + return 10_000; } -} \ No newline at end of file +} diff --git a/test/mocks/ECDSAServiceManagerMock.sol b/test/mocks/ECDSAServiceManagerMock.sol index df93cdd1..488e5eef 100644 --- a/test/mocks/ECDSAServiceManagerMock.sol +++ b/test/mocks/ECDSAServiceManagerMock.sol @@ -2,7 +2,8 @@ pragma solidity ^0.8.27; import "../../src/unaudited/ECDSAServiceManagerBase.sol"; -import {IAllocationManagerTypes} from "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; +import {IAllocationManagerTypes} from + "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; contract ECDSAServiceManagerMock is ECDSAServiceManagerBase { constructor( @@ -28,21 +29,19 @@ contract ECDSAServiceManagerMock is ECDSAServiceManagerBase { __ServiceManagerBase_init(initialOwner, rewardsInitiator); } - function addPendingAdmin(address admin) external {} - - function removePendingAdmin(address pendingAdmin) external {} - - function removeAdmin(address admin) external {} + function addPendingAdmin( + address admin + ) external {} - function setAppointee( - address appointee, - address target, - bytes4 selector + function removePendingAdmin( + address pendingAdmin ) external {} - function removeAppointee( - address appointee, - address target, - bytes4 selector + function removeAdmin( + address admin ) external {} + + function setAppointee(address appointee, address target, bytes4 selector) external {} + + function removeAppointee(address appointee, address target, bytes4 selector) external {} } diff --git a/test/mocks/ECDSAStakeRegistryMock.sol b/test/mocks/ECDSAStakeRegistryMock.sol index e2b756be..fb43079b 100644 --- a/test/mocks/ECDSAStakeRegistryMock.sol +++ b/test/mocks/ECDSAStakeRegistryMock.sol @@ -8,7 +8,7 @@ import "../../src/unaudited/ECDSAStakeRegistry.sol"; * @dev This contract is a mock implementation of the ECDSAStakeRegistry for testing purposes. */ contract ECDSAStakeRegistryMock is ECDSAStakeRegistry { - - constructor(IDelegationManager _delegationManager) ECDSAStakeRegistry(_delegationManager) { - } + constructor( + IDelegationManager _delegationManager + ) ECDSAStakeRegistry(_delegationManager) {} } diff --git a/test/mocks/EigenPodManagerMock.sol b/test/mocks/EigenPodManagerMock.sol index 700d1840..dccdbef8 100644 --- a/test/mocks/EigenPodManagerMock.sol +++ b/test/mocks/EigenPodManagerMock.sol @@ -11,11 +11,15 @@ contract EigenPodManagerMock is Test, Pausable, IEigenPodManager { mapping(address => int256) public podShares; - constructor(IPauserRegistry _pauserRegistry) Pausable(_pauserRegistry){ + constructor( + IPauserRegistry _pauserRegistry + ) Pausable(_pauserRegistry) { _setPausedStatus(0); } - function podOwnerShares(address podOwner) external view returns (int256) { + function podOwnerShares( + address podOwner + ) external view returns (int256) { return podShares[podOwner]; } @@ -27,77 +31,82 @@ contract EigenPodManagerMock is Test, Pausable, IEigenPodManager { return type(uint64).max; } - function createPod() external returns (address) { - } + function createPod() external returns (address) {} - function stake(bytes calldata pubkey, bytes calldata signature, bytes32 depositDataRoot) external payable { - } + function stake( + bytes calldata pubkey, + bytes calldata signature, + bytes32 depositDataRoot + ) external payable {} function recordBeaconChainETHBalanceUpdate( address podOwner, int256 sharesDelta, uint64 proportionPodBalanceDecrease - ) external { - } + ) external {} - function ownerToPod(address podOwner) external view returns (IEigenPod) { - } + function ownerToPod( + address podOwner + ) external view returns (IEigenPod) {} - function getPod(address podOwner) external view returns (IEigenPod) { - } + function getPod( + address podOwner + ) external view returns (IEigenPod) {} - function ethPOS() external view returns (IETHPOSDeposit) { - } + function ethPOS() external view returns (IETHPOSDeposit) {} - function eigenPodBeacon() external view returns (IBeacon) { - } + function eigenPodBeacon() external view returns (IBeacon) {} - function strategyManager() external view returns (IStrategyManager) { - } + function strategyManager() external view returns (IStrategyManager) {} - function hasPod(address podOwner) external view returns (bool) { - } + function hasPod( + address podOwner + ) external view returns (bool) {} - function numPods() external view returns (uint256) { - } + function numPods() external view returns (uint256) {} - function podOwnerDepositShares(address podOwner) external view returns (int256) { - } + function podOwnerDepositShares( + address podOwner + ) external view returns (int256) {} - function beaconChainETHStrategy() external view returns (IStrategy) { - } + function beaconChainETHStrategy() external view returns (IStrategy) {} - function removeDepositShares(address staker, IStrategy strategy, uint256 depositSharesToRemove) external { - } + function removeDepositShares( + address staker, + IStrategy strategy, + uint256 depositSharesToRemove + ) external {} - function stakerDepositShares(address user, IStrategy strategy) external view returns (uint256 depositShares) { - } + function stakerDepositShares( + address user, + IStrategy strategy + ) external view returns (uint256 depositShares) {} - function withdrawSharesAsTokens(address staker, IStrategy strategy, IERC20 token, uint256 shares) external{} + function withdrawSharesAsTokens( + address staker, + IStrategy strategy, + IERC20 token, + uint256 shares + ) external {} function addShares( address staker, IStrategy strategy, IERC20 token, uint256 shares - ) external returns (uint256, uint256) { - } + ) external returns (uint256, uint256) {} function beaconChainSlashingFactor( address staker - ) external view returns (uint64) { - } + ) external view returns (uint64) {} function recordBeaconChainETHBalanceUpdate( address podOwner, uint256 prevRestakedBalanceWei, int256 balanceDeltaWei - ) external { - } + ) external {} - function burnableETHShares() external view returns (uint256) { - } + function burnableETHShares() external view returns (uint256) {} - function increaseBurnableShares(IStrategy strategy, uint256 addedSharesToBurn) external { - } -} \ No newline at end of file + function increaseBurnableShares(IStrategy strategy, uint256 addedSharesToBurn) external {} +} diff --git a/test/mocks/PermissionControllerMock.sol b/test/mocks/PermissionControllerMock.sol index 9a9eca00..11452675 100644 --- a/test/mocks/PermissionControllerMock.sol +++ b/test/mocks/PermissionControllerMock.sol @@ -1,73 +1,71 @@ // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.27; -import {IPermissionController} from "eigenlayer-contracts/src/contracts/interfaces/IPermissionController.sol"; +import {IPermissionController} from + "eigenlayer-contracts/src/contracts/interfaces/IPermissionController.sol"; contract PermissionControllerIntermediate is IPermissionController { - function addPendingAdmin(address account, address admin) external virtual {} - - function removePendingAdmin( - address account, - address admin - ) external virtual {} - - function acceptAdmin(address account) external virtual {} - - function removeAdmin(address account, address admin) external virtual {} - - function setAppointee( - address account, - address appointee, - address target, - bytes4 selector - ) external virtual {} - - function removeAppointee( - address account, - address appointee, - address target, - bytes4 selector - ) external virtual {} - - function isAdmin( - address account, - address caller - ) external view virtual returns (bool) {} - - function isPendingAdmin( - address account, - address pendingAdmin - ) external view virtual returns (bool) {} - - function getAdmins( - address account - ) external view virtual returns (address[] memory) {} - - function getPendingAdmins( - address account - ) external view virtual returns (address[] memory) {} - - function canCall( - address account, - address caller, - address target, - bytes4 selector - ) external virtual returns (bool) {} - - function getAppointeePermissions( - address account, - address appointee - ) external virtual returns (address[] memory, bytes4[] memory) {} - - function getAppointees( - address account, - address target, - bytes4 selector - ) external virtual returns (address[] memory) {} + function addPendingAdmin(address account, address admin) external virtual {} + + function removePendingAdmin(address account, address admin) external virtual {} + + function acceptAdmin( + address account + ) external virtual {} + + function removeAdmin(address account, address admin) external virtual {} + + function setAppointee( + address account, + address appointee, + address target, + bytes4 selector + ) external virtual {} + + function removeAppointee( + address account, + address appointee, + address target, + bytes4 selector + ) external virtual {} + + function isAdmin(address account, address caller) external view virtual returns (bool) {} + + function isPendingAdmin( + address account, + address pendingAdmin + ) external view virtual returns (bool) {} + + function getAdmins( + address account + ) external view virtual returns (address[] memory) {} + + function getPendingAdmins( + address account + ) external view virtual returns (address[] memory) {} + + function canCall( + address account, + address caller, + address target, + bytes4 selector + ) external virtual returns (bool) {} + + function getAppointeePermissions( + address account, + address appointee + ) external virtual returns (address[] memory, bytes4[] memory) {} + + function getAppointees( + address account, + address target, + bytes4 selector + ) external virtual returns (address[] memory) {} } contract PermissionControllerMock is PermissionControllerIntermediate { - mapping(address => mapping(address => mapping(address => mapping(bytes4 => bool)))) internal _canCall; + mapping(address => mapping(address => mapping(address => mapping(bytes4 => bool)))) internal + _canCall; function setCanCall( address account, @@ -87,5 +85,4 @@ contract PermissionControllerMock is PermissionControllerIntermediate { if (account == caller) return true; return _canCall[account][caller][target][selector]; } - } diff --git a/test/mocks/RegistryCoordinatorMock.sol b/test/mocks/RegistryCoordinatorMock.sol index 165a649d..d0464db2 100644 --- a/test/mocks/RegistryCoordinatorMock.sol +++ b/test/mocks/RegistryCoordinatorMock.sol @@ -1,19 +1,16 @@ // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.27; - import "../../src/interfaces/IRegistryCoordinator.sol"; - contract RegistryCoordinatorMock is IRegistryCoordinator { function blsApkRegistry() external view returns (IBLSApkRegistry) {} - function ejectOperator( - address operator, - bytes calldata quorumNumbers - ) external {} + function ejectOperator(address operator, bytes calldata quorumNumbers) external {} - function getOperatorSetParams(uint8 quorumNumber) external view returns (OperatorSetParam memory) {} + function getOperatorSetParams( + uint8 quorumNumber + ) external view returns (OperatorSetParam memory) {} function indexRegistry() external view returns (IIndexRegistry) {} @@ -21,61 +18,93 @@ contract RegistryCoordinatorMock is IRegistryCoordinator { function quorumCount() external view returns (uint8) {} /// @notice Returns the bitmap of the quorums the operator is registered for. - function operatorIdToQuorumBitmap(bytes32 pubkeyHash) external view returns (uint256){} + function operatorIdToQuorumBitmap( + bytes32 pubkeyHash + ) external view returns (uint256) {} - function getOperator(address operator) external view returns (OperatorInfo memory){} + function getOperator( + address operator + ) external view returns (OperatorInfo memory) {} /// @notice Returns the stored id for the specified `operator`. - function getOperatorId(address operator) external view returns (bytes32){} + function getOperatorId( + address operator + ) external view returns (bytes32) {} /// @notice Returns the operator address for the given `operatorId` - function getOperatorFromId(bytes32 operatorId) external view returns (address) {} + function getOperatorFromId( + bytes32 operatorId + ) external view returns (address) {} /// @notice Returns the status for the given `operator` - function getOperatorStatus(address operator) external view returns (IRegistryCoordinator.OperatorStatus){} + function getOperatorStatus( + address operator + ) external view returns (IRegistryCoordinator.OperatorStatus) {} /// @notice Returns task number from when `operator` has been registered. - function getFromTaskNumberForOperator(address operator) external view returns (uint32){} + function getFromTaskNumberForOperator( + address operator + ) external view returns (uint32) {} - function getQuorumBitmapIndicesAtBlockNumber(uint32 blockNumber, bytes32[] memory operatorIds) external view returns (uint32[] memory){} + function getQuorumBitmapIndicesAtBlockNumber( + uint32 blockNumber, + bytes32[] memory operatorIds + ) external view returns (uint32[] memory) {} /// @notice Returns the quorum bitmap for the given `operatorId` at the given `blockNumber` via the `index` - function getQuorumBitmapAtBlockNumberByIndex(bytes32 operatorId, uint32 blockNumber, uint256 index) external view returns (uint192) {} + function getQuorumBitmapAtBlockNumberByIndex( + bytes32 operatorId, + uint32 blockNumber, + uint256 index + ) external view returns (uint192) {} /// @notice Returns the `index`th entry in the operator with `operatorId`'s bitmap history - function getQuorumBitmapUpdateByIndex(bytes32 operatorId, uint256 index) external view returns (QuorumBitmapUpdate memory) {} + function getQuorumBitmapUpdateByIndex( + bytes32 operatorId, + uint256 index + ) external view returns (QuorumBitmapUpdate memory) {} /// @notice Returns the current quorum bitmap for the given `operatorId` - function getCurrentQuorumBitmap(bytes32 operatorId) external view returns (uint192) {} + function getCurrentQuorumBitmap( + bytes32 operatorId + ) external view returns (uint192) {} /// @notice Returns the length of the quorum bitmap history for the given `operatorId` - function getQuorumBitmapHistoryLength(bytes32 operatorId) external view returns (uint256) {} + function getQuorumBitmapHistoryLength( + bytes32 operatorId + ) external view returns (uint256) {} - function numRegistries() external view returns (uint256){} + function numRegistries() external view returns (uint256) {} - function registries(uint256) external view returns (address){} + function registries( + uint256 + ) external view returns (address) {} function registerOperator(bytes memory quorumNumbers, bytes calldata) external {} function deregisterOperator(bytes calldata quorumNumbers, bytes calldata) external {} - function pubkeyRegistrationMessageHash(address operator) public view returns (BN254.G1Point memory) { - return BN254.hashToG1( - keccak256(abi.encode(operator)) - ); + function pubkeyRegistrationMessageHash( + address operator + ) public view returns (BN254.G1Point memory) { + return BN254.hashToG1(keccak256(abi.encode(operator))); } - function quorumUpdateBlockNumber(uint8 quorumNumber) external view returns (uint256) {} + function quorumUpdateBlockNumber( + uint8 quorumNumber + ) external view returns (uint256) {} function owner() external view returns (address) {} - function serviceManager() external view returns (IServiceManager){} + function serviceManager() external view returns (IServiceManager) {} - function isM2Quorum(uint8 quorumNumber) external view returns (bool) { + function isM2Quorum( + uint8 quorumNumber + ) external view returns (bool) { return false; } function isOperatorSetAVS() external view returns (bool) { return false; } -} \ No newline at end of file +} diff --git a/test/mocks/RewardsCoordinatorMock.sol b/test/mocks/RewardsCoordinatorMock.sol index 9d992962..b16f7cc5 100644 --- a/test/mocks/RewardsCoordinatorMock.sol +++ b/test/mocks/RewardsCoordinatorMock.sol @@ -4,168 +4,142 @@ pragma solidity ^0.8.27; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IPauserRegistry} from "eigenlayer-contracts/src/contracts/interfaces/IPauserRegistry.sol"; -import {IRewardsCoordinator} from "eigenlayer-contracts/src/contracts/interfaces/IRewardsCoordinator.sol"; +import {IRewardsCoordinator} from + "eigenlayer-contracts/src/contracts/interfaces/IRewardsCoordinator.sol"; import "./AVSDirectoryMock.sol"; contract RewardsCoordinatorMock is IRewardsCoordinator { - function initialize( - address initialOwner, - uint256 initialPausedStatus, - address _rewardsUpdater, - uint32 _activationDelay, - uint16 _defaultSplitBips - ) external override {} - - function createAVSRewardsSubmission( - RewardsSubmission[] calldata rewardsSubmissions - ) external override {} - - function createRewardsForAllSubmission( - RewardsSubmission[] calldata rewardsSubmissions - ) external override {} - - function createRewardsForAllEarners( - RewardsSubmission[] calldata rewardsSubmissions - ) external override {} - - function createOperatorDirectedAVSRewardsSubmission( - address avs, - OperatorDirectedRewardsSubmission[] - calldata operatorDirectedRewardsSubmissions - ) external override {} - - function processClaim( - RewardsMerkleClaim calldata claim, - address recipient - ) external override {} - - function processClaims( - RewardsMerkleClaim[] calldata claims, - address recipient - ) external override {} - - function submitRoot( - bytes32 root, - uint32 rewardsCalculationEndTimestamp - ) external override {} - - function disableRoot(uint32 rootIndex) external override {} - - function setClaimerFor(address claimer) external override {} - - function setClaimerFor(address earner, address claimer) external override {} - - function setActivationDelay(uint32 _activationDelay) external override {} - - function setDefaultOperatorSplit(uint16 split) external override {} - - function setOperatorAVSSplit( - address operator, - address avs, - uint16 split - ) external override {} - - function setOperatorPISplit( - address operator, - uint16 split - ) external override {} - - function setRewardsUpdater(address _rewardsUpdater) external override {} - - function setRewardsForAllSubmitter( - address _submitter, - bool _newValue - ) external override {} - - function activationDelay() external view override returns (uint32) {} - - function currRewardsCalculationEndTimestamp() - external - view - override - returns (uint32) - {} - - function claimerFor( - address earner - ) external view override returns (address) {} - - function cumulativeClaimed( - address claimer, - IERC20 token - ) external view override returns (uint256) {} - - function defaultOperatorSplitBips() external view override returns (uint16) {} - - function getOperatorAVSSplit( - address operator, - address avs - ) external view override returns (uint16) {} - - function getOperatorPISplit( - address operator - ) external view override returns (uint16) {} - - function calculateEarnerLeafHash( - EarnerTreeMerkleLeaf calldata leaf - ) external pure override returns (bytes32) {} - - function calculateTokenLeafHash( - TokenTreeMerkleLeaf calldata leaf - ) external pure override returns (bytes32) {} - - function checkClaim( - RewardsMerkleClaim calldata claim - ) external view override returns (bool) {} - - function getDistributionRootsLength() - external - view - override - returns (uint256) - {} - - function getDistributionRootAtIndex( - uint256 index - ) external view override returns (DistributionRoot memory) {} - - function getCurrentDistributionRoot() - external - view - override - returns (DistributionRoot memory) - {} - - function getCurrentClaimableDistributionRoot() - external - view - override - returns (DistributionRoot memory) - {} + function initialize( + address initialOwner, + uint256 initialPausedStatus, + address _rewardsUpdater, + uint32 _activationDelay, + uint16 _defaultSplitBips + ) external override {} - function getRootIndexFromHash( - bytes32 rootHash - ) external view override returns (uint32) {} + function createAVSRewardsSubmission( + RewardsSubmission[] calldata rewardsSubmissions + ) external override {} - function rewardsUpdater() external view override returns (address) {} + function createRewardsForAllSubmission( + RewardsSubmission[] calldata rewardsSubmissions + ) external override {} - function CALCULATION_INTERVAL_SECONDS() - external - view - override - returns (uint32) - {} - - function MAX_REWARDS_DURATION() external view override returns (uint32) {} - - function MAX_RETROACTIVE_LENGTH() external view override returns (uint32) {} - - function MAX_FUTURE_LENGTH() external view override returns (uint32) {} - - function GENESIS_REWARDS_TIMESTAMP() - external - view - override - returns (uint32) - {} -} \ No newline at end of file + function createRewardsForAllEarners( + RewardsSubmission[] calldata rewardsSubmissions + ) external override {} + + function createOperatorDirectedAVSRewardsSubmission( + address avs, + OperatorDirectedRewardsSubmission[] calldata operatorDirectedRewardsSubmissions + ) external override {} + + function processClaim(RewardsMerkleClaim calldata claim, address recipient) external override {} + + function processClaims( + RewardsMerkleClaim[] calldata claims, + address recipient + ) external override {} + + function submitRoot(bytes32 root, uint32 rewardsCalculationEndTimestamp) external override {} + + function disableRoot( + uint32 rootIndex + ) external override {} + + function setClaimerFor( + address claimer + ) external override {} + + function setClaimerFor(address earner, address claimer) external override {} + + function setActivationDelay( + uint32 _activationDelay + ) external override {} + + function setDefaultOperatorSplit( + uint16 split + ) external override {} + + function setOperatorAVSSplit(address operator, address avs, uint16 split) external override {} + + function setOperatorPISplit(address operator, uint16 split) external override {} + + function setRewardsUpdater( + address _rewardsUpdater + ) external override {} + + function setRewardsForAllSubmitter(address _submitter, bool _newValue) external override {} + + function activationDelay() external view override returns (uint32) {} + + function currRewardsCalculationEndTimestamp() external view override returns (uint32) {} + + function claimerFor( + address earner + ) external view override returns (address) {} + + function cumulativeClaimed( + address claimer, + IERC20 token + ) external view override returns (uint256) {} + + function defaultOperatorSplitBips() external view override returns (uint16) {} + + function getOperatorAVSSplit( + address operator, + address avs + ) external view override returns (uint16) {} + + function getOperatorPISplit( + address operator + ) external view override returns (uint16) {} + + function calculateEarnerLeafHash( + EarnerTreeMerkleLeaf calldata leaf + ) external pure override returns (bytes32) {} + + function calculateTokenLeafHash( + TokenTreeMerkleLeaf calldata leaf + ) external pure override returns (bytes32) {} + + function checkClaim( + RewardsMerkleClaim calldata claim + ) external view override returns (bool) {} + + function getDistributionRootsLength() external view override returns (uint256) {} + + function getDistributionRootAtIndex( + uint256 index + ) external view override returns (DistributionRoot memory) {} + + function getCurrentDistributionRoot() + external + view + override + returns (DistributionRoot memory) + {} + + function getCurrentClaimableDistributionRoot() + external + view + override + returns (DistributionRoot memory) + {} + + function getRootIndexFromHash( + bytes32 rootHash + ) external view override returns (uint32) {} + + function rewardsUpdater() external view override returns (address) {} + + function CALCULATION_INTERVAL_SECONDS() external view override returns (uint32) {} + + function MAX_REWARDS_DURATION() external view override returns (uint32) {} + + function MAX_RETROACTIVE_LENGTH() external view override returns (uint32) {} + + function MAX_FUTURE_LENGTH() external view override returns (uint32) {} + + function GENESIS_REWARDS_TIMESTAMP() external view override returns (uint32) {} +} diff --git a/test/mocks/StakeRegistryMock.sol b/test/mocks/StakeRegistryMock.sol index 58f46256..a70c8f13 100644 --- a/test/mocks/StakeRegistryMock.sol +++ b/test/mocks/StakeRegistryMock.sol @@ -12,7 +12,9 @@ contract StakeRegistryMock is IStakeRegistry { // bitmap returned by the mocked `updateOperatorStake` function uint192 updateOperatorStakeReturnBitmap; - function set_updateOperatorStakeReturnBitmap(uint192 newValue) external { + function set_updateOperatorStakeReturnBitmap( + uint192 newValue + ) external { updateOperatorStakeReturnBitmap = newValue; } @@ -67,14 +69,15 @@ contract StakeRegistryMock is IStakeRegistry { /** * @notice Initialize a new quorum created by the registry coordinator by setting strategies, weights, and minimum stake */ - function initializeQuorum(uint8 quorumNumber, uint96 minimumStake, StrategyParams[] memory strategyParams) external {} - - /// @notice Adds new strategies and the associated multipliers to the @param quorumNumber. - function addStrategies( + function initializeQuorum( uint8 quorumNumber, + uint96 minimumStake, StrategyParams[] memory strategyParams ) external {} + /// @notice Adds new strategies and the associated multipliers to the @param quorumNumber. + function addStrategies(uint8 quorumNumber, StrategyParams[] memory strategyParams) external {} + /** * @notice This function is used for removing strategies and their associated weights from the * mapping strategiesConsideredAndMultipliers for a specific @param quorumNumber. @@ -100,10 +103,14 @@ contract StakeRegistryMock is IStakeRegistry { function WEIGHTING_DIVISOR() external pure returns (uint256) {} - function strategyParamsLength(uint8 quorumNumber) external view returns (uint256) {} + function strategyParamsLength( + uint8 quorumNumber + ) external view returns (uint256) {} /// @notice In order to register for a quorum i, an operator must have at least `minimumStakeForQuorum[i]` - function minimumStakeForQuorum(uint8 quorumNumber) external view returns (uint96) {} + function minimumStakeForQuorum( + uint8 quorumNumber + ) external view returns (uint96) {} /// @notice Returns the strategy and weight multiplier for the `index`'th strategy in the quorum `quorumNumber` function strategyParamsByIndex( @@ -115,32 +122,47 @@ contract StakeRegistryMock is IStakeRegistry { * @notice This function computes the total weight of the @param operator in the quorum @param quorumNumber. * @dev reverts in the case that `quorumNumber` is greater than or equal to `quorumCount` */ - function weightOfOperatorForQuorum(uint8 quorumNumber, address operator) external view returns (uint96) {} + function weightOfOperatorForQuorum( + uint8 quorumNumber, + address operator + ) external view returns (uint96) {} /** * @notice Returns the entire `operatorIdToStakeHistory[operatorId][quorumNumber]` array. * @param operatorId The id of the operator of interest. * @param quorumNumber The quorum number to get the stake for. */ - function getStakeHistory(bytes32 operatorId, uint8 quorumNumber) external view returns (StakeUpdate[] memory) {} + function getStakeHistory( + bytes32 operatorId, + uint8 quorumNumber + ) external view returns (StakeUpdate[] memory) {} - function getTotalStakeHistoryLength(uint8 quorumNumber) external view returns (uint256) {} + function getTotalStakeHistoryLength( + uint8 quorumNumber + ) external view returns (uint256) {} /** * @notice Returns the `index`-th entry in the dynamic array of total stake, `totalStakeHistory` for quorum `quorumNumber`. * @param quorumNumber The quorum number to get the stake for. * @param index Array index for lookup, within the dynamic array `totalStakeHistory[quorumNumber]`. */ - function getTotalStakeUpdateAtIndex(uint8 quorumNumber, uint256 index) external view returns (StakeUpdate memory) {} + function getTotalStakeUpdateAtIndex( + uint8 quorumNumber, + uint256 index + ) external view returns (StakeUpdate memory) {} /// @notice Returns the indices of the operator stakes for the provided `quorumNumber` at the given `blockNumber` - function getStakeUpdateIndexAtBlockNumber(bytes32 operatorId, uint8 quorumNumber, uint32 blockNumber) - external - view - returns (uint32) {} + function getStakeUpdateIndexAtBlockNumber( + bytes32 operatorId, + uint8 quorumNumber, + uint32 blockNumber + ) external view returns (uint32) {} /// @notice Returns the indices of the total stakes for the provided `quorumNumbers` at the given `blockNumber` - function getTotalStakeIndicesAtBlockNumber(uint32 blockNumber, bytes calldata quorumNumbers) external view returns(uint32[] memory) {} + function getTotalStakeIndicesAtBlockNumber( + uint32 blockNumber, + bytes calldata quorumNumbers + ) external view returns (uint32[] memory) {} /** * @notice Returns the `index`-th entry in the `operatorIdToStakeHistory[operatorId][quorumNumber]` array. @@ -149,16 +171,20 @@ contract StakeRegistryMock is IStakeRegistry { * @param index Array index for lookup, within the dynamic array `operatorIdToStakeHistory[operatorId][quorumNumber]`. * @dev Function will revert if `index` is out-of-bounds. */ - function getStakeUpdateAtIndex(uint8 quorumNumber, bytes32 operatorId, uint256 index) - external - view - returns (StakeUpdate memory) {} + function getStakeUpdateAtIndex( + uint8 quorumNumber, + bytes32 operatorId, + uint256 index + ) external view returns (StakeUpdate memory) {} /** * @notice Returns the most recent stake weight for the `operatorId` for a certain quorum * @dev Function returns an StakeUpdate struct with **every entry equal to 0** in the event that the operator has no stake history */ - function getLatestStakeUpdate(bytes32 operatorId, uint8 quorumNumber) external view returns (StakeUpdate memory) {} + function getLatestStakeUpdate( + bytes32 operatorId, + uint8 quorumNumber + ) external view returns (StakeUpdate memory) {} /** * @notice Returns the stake weight corresponding to `operatorId` for quorum `quorumNumber`, at the @@ -171,10 +197,12 @@ contract StakeRegistryMock is IStakeRegistry { * @dev Function will revert if `index` is out-of-bounds. * @dev used the BLSSignatureChecker to get past stakes of signing operators */ - function getStakeAtBlockNumberAndIndex(uint8 quorumNumber, uint32 blockNumber, bytes32 operatorId, uint256 index) - external - view - returns (uint96) {} + function getStakeAtBlockNumberAndIndex( + uint8 quorumNumber, + uint32 blockNumber, + bytes32 operatorId, + uint256 index + ) external view returns (uint96) {} /** * @notice Returns the total stake weight for quorum `quorumNumber`, at the `index`-th entry in the @@ -186,25 +214,35 @@ contract StakeRegistryMock is IStakeRegistry { * @dev Function will revert if `index` is out-of-bounds. * @dev used the BLSSignatureChecker to get past stakes of signing operators */ - function getTotalStakeAtBlockNumberFromIndex(uint8 quorumNumber, uint32 blockNumber, uint256 index) external view returns (uint96) {} + function getTotalStakeAtBlockNumberFromIndex( + uint8 quorumNumber, + uint32 blockNumber, + uint256 index + ) external view returns (uint96) {} /** * @notice Returns the most recent stake weight for the `operatorId` for quorum `quorumNumber` * @dev Function returns weight of **0** in the event that the operator has no stake history */ - function getCurrentStake(bytes32 operatorId, uint8 quorumNumber) external view returns (uint96) {} + function getCurrentStake( + bytes32 operatorId, + uint8 quorumNumber + ) external view returns (uint96) {} /// @notice Returns the stake of the operator for the provided `quorumNumber` at the given `blockNumber` - function getStakeAtBlockNumber(bytes32 operatorId, uint8 quorumNumber, uint32 blockNumber) - external - view - returns (uint96){} + function getStakeAtBlockNumber( + bytes32 operatorId, + uint8 quorumNumber, + uint32 blockNumber + ) external view returns (uint96) {} /** * @notice Returns the stake weight from the latest entry in `_totalStakeHistory` for quorum `quorumNumber`. * @dev Will revert if `_totalStakeHistory[quorumNumber]` is empty. */ - function getCurrentTotalStake(uint8 quorumNumber) external view returns (uint96) {} + function getCurrentTotalStake( + uint8 quorumNumber + ) external view returns (uint96) {} /** * @notice Called by the registry coordinator to update an operator's stake for one @@ -214,14 +252,16 @@ contract StakeRegistryMock is IStakeRegistry { * added to the */ function updateOperatorStake( - address /*operator*/, - bytes32 /*operatorId*/, + address, /*operator*/ + bytes32, /*operatorId*/ bytes calldata /*quorumNumbers*/ ) external returns (uint192) { return updateOperatorStakeReturnBitmap; } - function getMockOperatorId(address operator) external pure returns(bytes32) { + function getMockOperatorId( + address operator + ) external pure returns (bytes32) { return bytes32(uint256(keccak256(abi.encodePacked(operator, "operatorId")))); } } diff --git a/test/unit/AVSRegistrar.t.sol b/test/unit/AVSRegistrar.t.sol index deea28a2..1dd90226 100644 --- a/test/unit/AVSRegistrar.t.sol +++ b/test/unit/AVSRegistrar.t.sol @@ -8,7 +8,8 @@ import {IStakeRegistry} from "../../src/interfaces/IStakeRegistry.sol"; import {BitmapUtils} from "../../src/libraries/BitmapUtils.sol"; import {IAVSRegistrar} from "eigenlayer-contracts/src/contracts/interfaces/IAVSRegistrar.sol"; import {IStrategy} from "eigenlayer-contracts/src/contracts/interfaces/IStrategy.sol"; -import {IAllocationManagerTypes} from "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; +import {IAllocationManagerTypes} from + "eigenlayer-contracts/src/contracts/interfaces/IAllocationManager.sol"; import {AVSRegistrarMock} from "../mocks/AVSRegistrarMock.sol"; import {console2 as console} from "forge-std/Test.sol"; @@ -25,18 +26,26 @@ contract AVSRegistrarTest is MockAVSDeployer { function testSetAVSRegistrar() public { vm.prank(address(serviceManager)); - allocationManager.setAVSRegistrar(address(serviceManager), IAVSRegistrar(address(avsRegistrarMock))); - assertEq(address(allocationManager.getAVSRegistrar(address(serviceManager))), address(avsRegistrarMock)); + allocationManager.setAVSRegistrar( + address(serviceManager), IAVSRegistrar(address(avsRegistrarMock)) + ); + assertEq( + address(allocationManager.getAVSRegistrar(address(serviceManager))), + address(avsRegistrarMock) + ); } function testRegisterOperator() public { // Set up AVS registrar vm.prank(address(serviceManager)); - allocationManager.setAVSRegistrar(address(serviceManager), IAVSRegistrar(address(avsRegistrarMock))); + allocationManager.setAVSRegistrar( + address(serviceManager), IAVSRegistrar(address(avsRegistrarMock)) + ); // Create operator set uint32 operatorSetId = 1; - IAllocationManagerTypes.CreateSetParams[] memory createSetParams = new IAllocationManagerTypes.CreateSetParams[](1); + IAllocationManagerTypes.CreateSetParams[] memory createSetParams = + new IAllocationManagerTypes.CreateSetParams[](1); createSetParams[0] = IAllocationManagerTypes.CreateSetParams({ operatorSetId: operatorSetId, strategies: new IStrategy[](0) @@ -57,17 +66,22 @@ contract AVSRegistrarTest is MockAVSDeployer { vm.prank(operator); allocationManager.registerForOperatorSets( address(operator), - IAllocationManagerTypes.RegisterParams(address(serviceManager), operatorSetIds, emptyBytes) + IAllocationManagerTypes.RegisterParams( + address(serviceManager), operatorSetIds, emptyBytes + ) ); } function testRegisterOperator_RevertsIfNotOperator() public { vm.prank(address(serviceManager)); - allocationManager.setAVSRegistrar(address(serviceManager), IAVSRegistrar(address(avsRegistrarMock))); + allocationManager.setAVSRegistrar( + address(serviceManager), IAVSRegistrar(address(avsRegistrarMock)) + ); // Create operator set uint32 operatorSetId = 1; - IAllocationManagerTypes.CreateSetParams[] memory createSetParams = new IAllocationManagerTypes.CreateSetParams[](1); + IAllocationManagerTypes.CreateSetParams[] memory createSetParams = + new IAllocationManagerTypes.CreateSetParams[](1); createSetParams[0] = IAllocationManagerTypes.CreateSetParams({ operatorSetId: operatorSetId, strategies: new IStrategy[](0) @@ -90,11 +104,17 @@ contract AVSRegistrarTest is MockAVSDeployer { vm.expectRevert(); allocationManager.registerForOperatorSets( address(operator), - IAllocationManagerTypes.RegisterParams(address(serviceManager), operatorSetIds, emptyBytes) + IAllocationManagerTypes.RegisterParams( + address(serviceManager), operatorSetIds, emptyBytes + ) ); } + function testAllocationManagerDeployed() public { assertTrue(address(allocationManager) != address(0), "AllocationManager not deployed"); - assertTrue(address(allocationManagerImplementation) != address(0), "AllocationManager implementation not deployed"); + assertTrue( + address(allocationManagerImplementation) != address(0), + "AllocationManager implementation not deployed" + ); } } diff --git a/test/unit/BLSApkRegistryUnit.t.sol b/test/unit/BLSApkRegistryUnit.t.sol index fa644cae..295d5cec 100644 --- a/test/unit/BLSApkRegistryUnit.t.sol +++ b/test/unit/BLSApkRegistryUnit.t.sol @@ -43,8 +43,9 @@ contract BLSApkRegistryUnitTests is BLSMockAVSDeployer, IBLSApkRegistryEvents { * HELPERS AND MODIFIERS * */ - - modifier filterFuzzedAddressInputs(address fuzzedAddress) { + modifier filterFuzzedAddressInputs( + address fuzzedAddress + ) { cheats.assume(!addressIsExcludedFromFuzzedInputs[fuzzedAddress]); _; } @@ -58,26 +59,20 @@ contract BLSApkRegistryUnitTests is BLSMockAVSDeployer, IBLSApkRegistryEvents { addressIsExcludedFromFuzzedInputs[defaultOperator] = true; addressIsExcludedFromFuzzedInputs[address(proxyAdmin)] = true; - pubkeyRegistrationParams.pubkeyG1 = BN254.generatorG1().scalar_mul( - privKey - ); + pubkeyRegistrationParams.pubkeyG1 = BN254.generatorG1().scalar_mul(privKey); defaultPubkey = pubkeyRegistrationParams.pubkeyG1; defaultPubkeyHash = BN254.hashG1Point(defaultPubkey); //privKey*G2 - pubkeyRegistrationParams.pubkeyG2.X[ - 1 - ] = 19_101_821_850_089_705_274_637_533_855_249_918_363_070_101_489_527_618_151_493_230_256_975_900_223_847; - pubkeyRegistrationParams.pubkeyG2.X[ - 0 - ] = 5_334_410_886_741_819_556_325_359_147_377_682_006_012_228_123_419_628_681_352_847_439_302_316_235_957; - pubkeyRegistrationParams.pubkeyG2.Y[ - 1 - ] = 354_176_189_041_917_478_648_604_979_334_478_067_325_821_134_838_555_150_300_539_079_146_482_658_331; - pubkeyRegistrationParams.pubkeyG2.Y[ - 0 - ] = 4_185_483_097_059_047_421_902_184_823_581_361_466_320_657_066_600_218_863_748_375_739_772_335_928_910; + pubkeyRegistrationParams.pubkeyG2.X[1] = + 19_101_821_850_089_705_274_637_533_855_249_918_363_070_101_489_527_618_151_493_230_256_975_900_223_847; + pubkeyRegistrationParams.pubkeyG2.X[0] = + 5_334_410_886_741_819_556_325_359_147_377_682_006_012_228_123_419_628_681_352_847_439_302_316_235_957; + pubkeyRegistrationParams.pubkeyG2.Y[1] = + 354_176_189_041_917_478_648_604_979_334_478_067_325_821_134_838_555_150_300_539_079_146_482_658_331; + pubkeyRegistrationParams.pubkeyG2.Y[0] = + 4_185_483_097_059_047_421_902_184_823_581_361_466_320_657_066_600_218_863_748_375_739_772_335_928_910; // Initialize 3 quorums _initializeQuorum(); @@ -96,14 +91,14 @@ contract BLSApkRegistryUnitTests is BLSMockAVSDeployer, IBLSApkRegistryEvents { initializedQuorums[quorumNumber] = true; // Mark quorum initialized for other tests - initializedQuorumBitmap = uint192( - initializedQuorumBitmap.setBit(quorumNumber) - ); + initializedQuorumBitmap = uint192(initializedQuorumBitmap.setBit(quorumNumber)); initializedQuorumBytes = initializedQuorumBitmap.bitmapToBytesArray(); } /// @dev Doesn't increment nextQuorum as assumes quorumNumber is any valid arbitrary quorumNumber - function _initializeQuorum(uint8 quorumNumber) internal { + function _initializeQuorum( + uint8 quorumNumber + ) internal { cheats.prank(address(registryCoordinator)); // Initialize quorum and mark registered @@ -113,10 +108,10 @@ contract BLSApkRegistryUnitTests is BLSMockAVSDeployer, IBLSApkRegistryEvents { /// @dev initializeQuorum based on passed in bitmap of quorum numbers /// assumes that bitmap does not contain already initailized quorums and doesn't increment nextQuorum - function _initializeFuzzedQuorums(uint192 bitmap) internal { - bytes memory quorumNumbers = bitmapUtilsWrapper.bitmapToBytesArray( - bitmap - ); + function _initializeFuzzedQuorums( + uint192 bitmap + ) internal { + bytes memory quorumNumbers = bitmapUtilsWrapper.bitmapToBytesArray(bitmap); for (uint256 i = 0; i < quorumNumbers.length; i++) { uint8 quorumNumber = uint8(quorumNumbers[i]); @@ -124,7 +119,9 @@ contract BLSApkRegistryUnitTests is BLSMockAVSDeployer, IBLSApkRegistryEvents { } } - function _initializeFuzzedQuorum(uint8 quorumNumber) internal { + function _initializeFuzzedQuorum( + uint8 quorumNumber + ) internal { cheats.assume(!initializedQuorums[quorumNumber]); _initializeQuorum(quorumNumber); } @@ -137,14 +134,16 @@ contract BLSApkRegistryUnitTests is BLSMockAVSDeployer, IBLSApkRegistryEvents { return operator; } - function _getRandomPk(uint256 seed) internal view returns (bytes32) { + function _getRandomPk( + uint256 seed + ) internal view returns (bytes32) { return keccak256(abi.encodePacked(block.timestamp, seed)); } - function _getRandBool(uint256 seed) internal view returns (bool) { - uint256 randomNumber = uint256( - keccak256(abi.encodePacked(block.timestamp, seed)) - ); + function _getRandBool( + uint256 seed + ) internal view returns (bool) { + uint256 randomNumber = uint256(keccak256(abi.encodePacked(block.timestamp, seed))); return randomNumber % 2 == 0; } @@ -153,12 +152,10 @@ contract BLSApkRegistryUnitTests is BLSMockAVSDeployer, IBLSApkRegistryEvents { * Helpers using the default preset BLS key * */ - function _signMessage( address signer ) internal view returns (BN254.G1Point memory) { - BN254.G1Point memory messageHash = registryCoordinator - .pubkeyRegistrationMessageHash(signer); + BN254.G1Point memory messageHash = registryCoordinator.pubkeyRegistrationMessageHash(signer); return BN254.scalar_mul(messageHash, privKey); } @@ -184,28 +181,18 @@ contract BLSApkRegistryUnitTests is BLSMockAVSDeployer, IBLSApkRegistryEvents { function _registerDefaultBLSPubkey( address operator ) internal returns (bytes32) { - pubkeyRegistrationParams.pubkeyRegistrationSignature = _signMessage( - operator - ); - BN254.G1Point memory messageHash = registryCoordinator - .pubkeyRegistrationMessageHash(operator); + pubkeyRegistrationParams.pubkeyRegistrationSignature = _signMessage(operator); + BN254.G1Point memory messageHash = + registryCoordinator.pubkeyRegistrationMessageHash(operator); cheats.prank(address(registryCoordinator)); - return - blsApkRegistry.registerBLSPublicKey( - operator, - pubkeyRegistrationParams, - messageHash - ); + return blsApkRegistry.registerBLSPublicKey(operator, pubkeyRegistrationParams, messageHash); } /** * @dev register operator, assumes operator has a registered BLS public key and that quorumNumbers are valid */ - function _registerOperator( - address operator, - bytes memory quorumNumbers - ) internal { + function _registerOperator(address operator, bytes memory quorumNumbers) internal { bytes32 operatorId = blsApkRegistry.getOperatorId(operator); cheats.prank(address(registryCoordinator)); cheats.expectEmit(true, true, true, true, address(blsApkRegistry)); @@ -216,10 +203,7 @@ contract BLSApkRegistryUnitTests is BLSMockAVSDeployer, IBLSApkRegistryEvents { /** * @dev deregister operator, assumes operator has a registered BLS public key and that quorumNumbers are valid */ - function _deregisterOperator( - address operator, - bytes memory quorumNumbers - ) internal { + function _deregisterOperator(address operator, bytes memory quorumNumbers) internal { bytes32 operatorId = blsApkRegistry.getOperatorId(operator); cheats.prank(address(registryCoordinator)); cheats.expectEmit(true, true, true, true, address(blsApkRegistry)); @@ -232,13 +216,10 @@ contract BLSApkRegistryUnitTests is BLSMockAVSDeployer, IBLSApkRegistryEvents { * Helpers for assertions * */ - function _getApks( bytes memory quorumNumbers ) internal view returns (BN254.G1Point[] memory) { - BN254.G1Point[] memory quorumApks = new BN254.G1Point[]( - quorumNumbers.length - ); + BN254.G1Point[] memory quorumApks = new BN254.G1Point[](quorumNumbers.length); for (uint8 i = 0; i < quorumNumbers.length; i++) { quorumApks[i] = blsApkRegistry.getApk(uint8(quorumNumbers[i])); } @@ -257,9 +238,7 @@ contract BLSApkRegistryUnitTests is BLSMockAVSDeployer, IBLSApkRegistryEvents { "apksBefore and quorumNumbers must be the same length" ); assertEq( - apksBefore.length, - apksAfter.length, - "apksBefore and apksAfter must be the same length" + apksBefore.length, apksAfter.length, "apksBefore and apksAfter must be the same length" ); for (uint256 i = 0; i < apksBefore.length; i++) { uint8 quorumNumber = uint8(quorumNumbers[i]); @@ -271,11 +250,9 @@ contract BLSApkRegistryUnitTests is BLSMockAVSDeployer, IBLSApkRegistryEvents { "quorum apk not updated correctly adding the operator pubkey" ); - uint32 quorumHistoryLength = blsApkRegistry.getApkHistoryLength( - quorumNumber - ); - IBLSApkRegistry.ApkUpdate memory latestApkUpdate = blsApkRegistry - .getApkUpdateAtIndex(quorumNumber, quorumHistoryLength - 1); + uint32 quorumHistoryLength = blsApkRegistry.getApkHistoryLength(quorumNumber); + IBLSApkRegistry.ApkUpdate memory latestApkUpdate = + blsApkRegistry.getApkUpdateAtIndex(quorumNumber, quorumHistoryLength - 1); assertEq( latestApkUpdate.apkHash, bytes24(BN254.hashG1Point(apkAfter)), @@ -316,9 +293,7 @@ contract BLSApkRegistryUnitTests_configAndGetters is BLSApkRegistryUnitTests { } /// @notice test for BLSApkRegistry.registerBLSPublicKey() -contract BLSApkRegistryUnitTests_registerBLSPublicKey is - BLSApkRegistryUnitTests -{ +contract BLSApkRegistryUnitTests_registerBLSPublicKey is BLSApkRegistryUnitTests { using BN254 for BN254.G1Point; function testFuzz_registerOperator_Revert_WhenNotRegistryCoordinator( @@ -326,19 +301,13 @@ contract BLSApkRegistryUnitTests_registerBLSPublicKey is ) public filterFuzzedAddressInputs(nonCoordinatorAddress) { cheats.assume(nonCoordinatorAddress != address(registryCoordinator)); - pubkeyRegistrationParams.pubkeyRegistrationSignature = _signMessage( - defaultOperator - ); - BN254.G1Point memory messageHash = registryCoordinator - .pubkeyRegistrationMessageHash(defaultOperator); + pubkeyRegistrationParams.pubkeyRegistrationSignature = _signMessage(defaultOperator); + BN254.G1Point memory messageHash = + registryCoordinator.pubkeyRegistrationMessageHash(defaultOperator); cheats.prank(address(nonCoordinatorAddress)); cheats.expectRevert(IBLSApkRegistryErrors.OnlyRegistryCoordinatorOwner.selector); - blsApkRegistry.registerBLSPublicKey( - defaultOperator, - pubkeyRegistrationParams, - messageHash - ); + blsApkRegistry.registerBLSPublicKey(defaultOperator, pubkeyRegistrationParams, messageHash); } function testFuzz_registerOperator_Revert_WhenZeroPubkeyHash( @@ -346,71 +315,43 @@ contract BLSApkRegistryUnitTests_registerBLSPublicKey is ) public filterFuzzedAddressInputs(operator) { pubkeyRegistrationParams.pubkeyG1.X = 0; pubkeyRegistrationParams.pubkeyG1.Y = 0; - BN254.G1Point memory messageHash = registryCoordinator - .pubkeyRegistrationMessageHash(operator); + BN254.G1Point memory messageHash = + registryCoordinator.pubkeyRegistrationMessageHash(operator); cheats.prank(address(registryCoordinator)); cheats.expectRevert(IBLSApkRegistryErrors.ZeroPubKey.selector); - blsApkRegistry.registerBLSPublicKey( - operator, - pubkeyRegistrationParams, - messageHash - ); + blsApkRegistry.registerBLSPublicKey(operator, pubkeyRegistrationParams, messageHash); } function testFuzz_registerOperator_Revert_WhenOperatorAlreadyRegistered( address operator ) public filterFuzzedAddressInputs(operator) { - pubkeyRegistrationParams.pubkeyRegistrationSignature = _signMessage( - operator - ); - BN254.G1Point memory messageHash = registryCoordinator - .pubkeyRegistrationMessageHash(operator); + pubkeyRegistrationParams.pubkeyRegistrationSignature = _signMessage(operator); + BN254.G1Point memory messageHash = + registryCoordinator.pubkeyRegistrationMessageHash(operator); cheats.startPrank(address(registryCoordinator)); - blsApkRegistry.registerBLSPublicKey( - operator, - pubkeyRegistrationParams, - messageHash - ); + blsApkRegistry.registerBLSPublicKey(operator, pubkeyRegistrationParams, messageHash); cheats.expectRevert(IBLSApkRegistryErrors.OperatorAlreadyRegistered.selector); - blsApkRegistry.registerBLSPublicKey( - operator, - pubkeyRegistrationParams, - messageHash - ); + blsApkRegistry.registerBLSPublicKey(operator, pubkeyRegistrationParams, messageHash); } function testFuzz_registerOperator_Revert_WhenPubkeyAlreadyRegistered( address operator, address operator2 - ) - public - filterFuzzedAddressInputs(operator) - filterFuzzedAddressInputs(operator2) - { + ) public filterFuzzedAddressInputs(operator) filterFuzzedAddressInputs(operator2) { cheats.assume(operator != address(0)); cheats.assume(operator != operator2); - BN254.G1Point memory messageHash = registryCoordinator - .pubkeyRegistrationMessageHash(operator); - pubkeyRegistrationParams.pubkeyRegistrationSignature = _signMessage( - operator - ); + BN254.G1Point memory messageHash = + registryCoordinator.pubkeyRegistrationMessageHash(operator); + pubkeyRegistrationParams.pubkeyRegistrationSignature = _signMessage(operator); cheats.startPrank(address(registryCoordinator)); - blsApkRegistry.registerBLSPublicKey( - operator, - pubkeyRegistrationParams, - messageHash - ); + blsApkRegistry.registerBLSPublicKey(operator, pubkeyRegistrationParams, messageHash); cheats.expectRevert(IBLSApkRegistryErrors.BLSPubkeyAlreadyRegistered.selector); - blsApkRegistry.registerBLSPublicKey( - operator2, - pubkeyRegistrationParams, - messageHash - ); + blsApkRegistry.registerBLSPublicKey(operator2, pubkeyRegistrationParams, messageHash); } /** @@ -420,25 +361,17 @@ contract BLSApkRegistryUnitTests_registerBLSPublicKey is function testFuzz_registerOperator_Revert_WhenInvalidSignature( address operator, address invalidOperator - ) - public - filterFuzzedAddressInputs(operator) - filterFuzzedAddressInputs(invalidOperator) - { + ) public filterFuzzedAddressInputs(operator) filterFuzzedAddressInputs(invalidOperator) { cheats.assume(invalidOperator != operator); - BN254.G1Point memory messageHash = registryCoordinator - .pubkeyRegistrationMessageHash(operator); + BN254.G1Point memory messageHash = + registryCoordinator.pubkeyRegistrationMessageHash(operator); BN254.G1Point memory invalidSignature = _signMessage(invalidOperator); pubkeyRegistrationParams.pubkeyRegistrationSignature = invalidSignature; cheats.startPrank(address(registryCoordinator)); cheats.expectRevert(IBLSApkRegistryErrors.InvalidBLSSignatureOrPrivateKey.selector); - blsApkRegistry.registerBLSPublicKey( - operator, - pubkeyRegistrationParams, - messageHash - ); + blsApkRegistry.registerBLSPublicKey(operator, pubkeyRegistrationParams, messageHash); } /** @@ -447,22 +380,16 @@ contract BLSApkRegistryUnitTests_registerBLSPublicKey is function testFuzz_registerOperator_Revert_WhenInvalidSignatureMismatchKey( address operator ) public filterFuzzedAddressInputs(operator) { - pubkeyRegistrationParams.pubkeyRegistrationSignature = _signMessage( - operator - ); + pubkeyRegistrationParams.pubkeyRegistrationSignature = _signMessage(operator); BN254.G1Point memory badPubkeyG1 = BN254.generatorG1().scalar_mul(420); // mismatch public keys pubkeyRegistrationParams.pubkeyG1 = badPubkeyG1; - BN254.G1Point memory messageHash = registryCoordinator - .pubkeyRegistrationMessageHash(operator); + BN254.G1Point memory messageHash = + registryCoordinator.pubkeyRegistrationMessageHash(operator); cheats.prank(address(registryCoordinator)); cheats.expectRevert(IBLSApkRegistryErrors.InvalidBLSSignatureOrPrivateKey.selector); - blsApkRegistry.registerBLSPublicKey( - operator, - pubkeyRegistrationParams, - messageHash - ); + blsApkRegistry.registerBLSPublicKey(operator, pubkeyRegistrationParams, messageHash); } /** @@ -473,47 +400,23 @@ contract BLSApkRegistryUnitTests_registerBLSPublicKey is address operator ) public filterFuzzedAddressInputs(operator) { // sign messagehash for operator with private key - pubkeyRegistrationParams.pubkeyRegistrationSignature = _signMessage( - operator - ); - BN254.G1Point memory messageHash = registryCoordinator - .pubkeyRegistrationMessageHash(operator); + pubkeyRegistrationParams.pubkeyRegistrationSignature = _signMessage(operator); + BN254.G1Point memory messageHash = + registryCoordinator.pubkeyRegistrationMessageHash(operator); cheats.prank(address(registryCoordinator)); cheats.expectEmit(true, true, true, true, address(blsApkRegistry)); emit NewPubkeyRegistration( - operator, - pubkeyRegistrationParams.pubkeyG1, - pubkeyRegistrationParams.pubkeyG2 - ); - blsApkRegistry.registerBLSPublicKey( - operator, - pubkeyRegistrationParams, - messageHash + operator, pubkeyRegistrationParams.pubkeyG1, pubkeyRegistrationParams.pubkeyG2 ); + blsApkRegistry.registerBLSPublicKey(operator, pubkeyRegistrationParams, messageHash); - ( - BN254.G1Point memory registeredPubkey, - bytes32 registeredpkHash - ) = blsApkRegistry.getRegisteredPubkey(operator); - assertEq( - registeredPubkey.X, - defaultPubkey.X, - "registeredPubkey not set correctly" - ); + (BN254.G1Point memory registeredPubkey, bytes32 registeredpkHash) = + blsApkRegistry.getRegisteredPubkey(operator); + assertEq(registeredPubkey.X, defaultPubkey.X, "registeredPubkey not set correctly"); + assertEq(registeredPubkey.Y, defaultPubkey.Y, "registeredPubkey not set correctly"); + assertEq(registeredpkHash, defaultPubkeyHash, "registeredpkHash not set correctly"); assertEq( - registeredPubkey.Y, - defaultPubkey.Y, - "registeredPubkey not set correctly" - ); - assertEq( - registeredpkHash, - defaultPubkeyHash, - "registeredpkHash not set correctly" - ); - assertEq( - blsApkRegistry.pubkeyHashToOperator( - BN254.hashG1Point(defaultPubkey) - ), + blsApkRegistry.pubkeyHashToOperator(BN254.hashG1Point(defaultPubkey)), operator, "operator address not stored correctly" ); @@ -550,12 +453,8 @@ contract BLSApkRegistryUnitTests_registerOperator is BLSApkRegistryUnitTests { cheats.prank(address(registryCoordinator)); cheats.assume(quorumBitmap > initializedQuorumBitmap); // mask out quorums that are already initialized - quorumBitmap = uint192( - quorumBitmap.minus(uint256(initializedQuorumBitmap)) - ); - bytes memory quorumNumbers = bitmapUtilsWrapper.bitmapToBytesArray( - quorumBitmap - ); + quorumBitmap = uint192(quorumBitmap.minus(uint256(initializedQuorumBitmap))); + bytes memory quorumNumbers = bitmapUtilsWrapper.bitmapToBytesArray(quorumBitmap); _registerDefaultBLSPubkey(operator); @@ -576,26 +475,15 @@ contract BLSApkRegistryUnitTests_registerOperator is BLSApkRegistryUnitTests { ) public filterFuzzedAddressInputs(operator) { // Test setup, initialize fuzzed quorums and register operator BLS pubkey cheats.assume(quorumBitmap > initializedQuorumBitmap); - uint192 initializingBitmap = uint192( - quorumBitmap.minus(uint256(initializedQuorumBitmap)) - ); + uint192 initializingBitmap = uint192(quorumBitmap.minus(uint256(initializedQuorumBitmap))); _initializeFuzzedQuorums(initializingBitmap); - bytes memory quorumNumbers = bitmapUtilsWrapper.bitmapToBytesArray( - quorumBitmap - ); - (BN254.G1Point memory pubkey, ) = _registerRandomBLSPubkey( - operator, - randomSeed - ); + bytes memory quorumNumbers = bitmapUtilsWrapper.bitmapToBytesArray(quorumBitmap); + (BN254.G1Point memory pubkey,) = _registerRandomBLSPubkey(operator, randomSeed); // get before values - BN254.G1Point[] memory quorumApksBefore = new BN254.G1Point[]( - quorumNumbers.length - ); + BN254.G1Point[] memory quorumApksBefore = new BN254.G1Point[](quorumNumbers.length); for (uint8 i = 0; i < quorumNumbers.length; i++) { - quorumApksBefore[i] = blsApkRegistry.getApk( - uint8(quorumNumbers[i]) - ); + quorumApksBefore[i] = blsApkRegistry.getApk(uint8(quorumNumbers[i])); } // registerOperator with expected OperatorAddedToQuorums event @@ -609,20 +497,16 @@ contract BLSApkRegistryUnitTests_registerOperator is BLSApkRegistryUnitTests { for (uint8 i = 0; i < quorumNumbers.length; i++) { // Check currentApk[quorumNumber] values uint8 quorumNumber = uint8(quorumNumbers[i]); - BN254.G1Point memory quorumApkAfter = blsApkRegistry.getApk( - uint8(quorumNumbers[i]) - ); + BN254.G1Point memory quorumApkAfter = blsApkRegistry.getApk(uint8(quorumNumbers[i])); assertEq( BN254.hashG1Point(quorumApkAfter), BN254.hashG1Point(quorumApksBefore[i].plus(pubkey)), "quorum apk not updated correctly adding the operator pubkey" ); // Check the latest ApkUpdate values - uint32 quorumHistoryLength = blsApkRegistry.getApkHistoryLength( - quorumNumber - ); - IBLSApkRegistry.ApkUpdate memory latestApkUpdate = blsApkRegistry - .getApkUpdateAtIndex(quorumNumber, quorumHistoryLength - 1); + uint32 quorumHistoryLength = blsApkRegistry.getApkHistoryLength(quorumNumber); + IBLSApkRegistry.ApkUpdate memory latestApkUpdate = + blsApkRegistry.getApkUpdateAtIndex(quorumNumber, quorumHistoryLength - 1); assertEq( latestApkUpdate.apkHash, bytes24(BN254.hashG1Point(quorumApkAfter)), @@ -672,14 +556,10 @@ contract BLSApkRegistryUnitTests_deregisterOperator is BLSApkRegistryUnitTests { cheats.prank(address(registryCoordinator)); cheats.assume(quorumBitmap > initializedQuorumBitmap); // mask out quorums that are already initialized - quorumBitmap = uint192( - quorumBitmap.minus(uint256(initializedQuorumBitmap)) - ); - bytes memory validQuorumNumbers = bitmapUtilsWrapper.bitmapToBytesArray( - initializedQuorumBitmap - ); - bytes memory invalidQuorumNumbers = bitmapUtilsWrapper - .bitmapToBytesArray(quorumBitmap); + quorumBitmap = uint192(quorumBitmap.minus(uint256(initializedQuorumBitmap))); + bytes memory validQuorumNumbers = + bitmapUtilsWrapper.bitmapToBytesArray(initializedQuorumBitmap); + bytes memory invalidQuorumNumbers = bitmapUtilsWrapper.bitmapToBytesArray(quorumBitmap); _registerDefaultBLSPubkey(operator); _registerOperator(operator, validQuorumNumbers); @@ -701,27 +581,16 @@ contract BLSApkRegistryUnitTests_deregisterOperator is BLSApkRegistryUnitTests { ) public filterFuzzedAddressInputs(operator) { // Test setup, initialize fuzzed quorums and register operator BLS pubkey cheats.assume(quorumBitmap > initializedQuorumBitmap); - uint192 initializingBitmap = uint192( - quorumBitmap.minus(uint256(initializedQuorumBitmap)) - ); + uint192 initializingBitmap = uint192(quorumBitmap.minus(uint256(initializedQuorumBitmap))); _initializeFuzzedQuorums(initializingBitmap); - bytes memory quorumNumbers = bitmapUtilsWrapper.bitmapToBytesArray( - quorumBitmap - ); - (BN254.G1Point memory pubkey, ) = _registerRandomBLSPubkey( - operator, - randomSeed - ); + bytes memory quorumNumbers = bitmapUtilsWrapper.bitmapToBytesArray(quorumBitmap); + (BN254.G1Point memory pubkey,) = _registerRandomBLSPubkey(operator, randomSeed); _registerOperator(operator, quorumNumbers); // get before values - BN254.G1Point[] memory quorumApksBefore = new BN254.G1Point[]( - quorumNumbers.length - ); + BN254.G1Point[] memory quorumApksBefore = new BN254.G1Point[](quorumNumbers.length); for (uint8 i = 0; i < quorumNumbers.length; i++) { - quorumApksBefore[i] = blsApkRegistry.getApk( - uint8(quorumNumbers[i]) - ); + quorumApksBefore[i] = blsApkRegistry.getApk(uint8(quorumNumbers[i])); } // registerOperator with expected OperatorAddedToQuorums event @@ -735,20 +604,16 @@ contract BLSApkRegistryUnitTests_deregisterOperator is BLSApkRegistryUnitTests { for (uint8 i = 0; i < quorumNumbers.length; i++) { // Check currentApk[quorumNumber] values uint8 quorumNumber = uint8(quorumNumbers[i]); - BN254.G1Point memory quorumApkAfter = blsApkRegistry.getApk( - uint8(quorumNumbers[i]) - ); + BN254.G1Point memory quorumApkAfter = blsApkRegistry.getApk(uint8(quorumNumbers[i])); assertEq( BN254.hashG1Point(quorumApkAfter), BN254.hashG1Point(quorumApksBefore[i].plus(pubkey.negate())), "quorum apk not updated correctly removing the operator pubkey" ); // Check the latest ApkUpdate values - uint32 quorumHistoryLength = blsApkRegistry.getApkHistoryLength( - quorumNumber - ); - IBLSApkRegistry.ApkUpdate memory latestApkUpdate = blsApkRegistry - .getApkUpdateAtIndex(quorumNumber, quorumHistoryLength - 1); + uint32 quorumHistoryLength = blsApkRegistry.getApkHistoryLength(quorumNumber); + IBLSApkRegistry.ApkUpdate memory latestApkUpdate = + blsApkRegistry.getApkUpdateAtIndex(quorumNumber, quorumHistoryLength - 1); assertEq( latestApkUpdate.apkHash, bytes24(BN254.hashG1Point(quorumApkAfter)), @@ -780,10 +645,7 @@ contract BLSApkRegistryUnitTests_quorumApkUpdates is BLSApkRegistryUnitTests { * @dev register/deregister up to 200 operators and check quorum apk updates * Test uses only the defaultQuorumNumber */ - function testFuzz_quorumApkUpdates( - uint256 numOperators, - uint256[200] memory randSeed - ) public { + function testFuzz_quorumApkUpdates(uint256 numOperators, uint256[200] memory randSeed) public { cheats.assume(0 < numOperators && numOperators <= 200); bytes memory quorumNumbers = new bytes(1); quorumNumbers[0] = bytes1(defaultQuorumNumber); @@ -797,17 +659,11 @@ contract BLSApkRegistryUnitTests_quorumApkUpdates is BLSApkRegistryUnitTests { // register and check quorum apk updates BN254.G1Point[] memory quorumApksBefore = _getApks(quorumNumbers); address operator = _selectNewOperator(); - (BN254.G1Point memory operatorPubkey, ) = _registerRandomBLSPubkey( - operator, - randSeed[i] - ); + (BN254.G1Point memory operatorPubkey,) = _registerRandomBLSPubkey(operator, randSeed[i]); _registerOperator(operator, quorumNumbers); BN254.G1Point[] memory quorumApksAfter = _getApks(quorumNumbers); _assertQuorumApkUpdates( - quorumNumbers, - quorumApksBefore, - quorumApksAfter, - operatorPubkey + quorumNumbers, quorumApksBefore, quorumApksAfter, operatorPubkey ); // deregister and check quorum apk updates @@ -817,10 +673,7 @@ contract BLSApkRegistryUnitTests_quorumApkUpdates is BLSApkRegistryUnitTests { _deregisterOperator(operator, quorumNumbers); quorumApksAfter = _getApks(quorumNumbers); _assertQuorumApkUpdates( - quorumNumbers, - quorumApksBefore, - quorumApksAfter, - operatorPubkey.negate() + quorumNumbers, quorumApksBefore, quorumApksAfter, operatorPubkey.negate() ); } } @@ -838,13 +691,9 @@ contract BLSApkRegistryUnitTests_quorumApkUpdates is BLSApkRegistryUnitTests { cheats.assume(0 < numOperators && numOperators <= 50); cheats.assume(quorumBitmap > initializedQuorumBitmap); // mask out quorums that are already initialized - uint192 initializingBitmap = uint192( - quorumBitmap.minus(uint256(initializedQuorumBitmap)) - ); + uint192 initializingBitmap = uint192(quorumBitmap.minus(uint256(initializedQuorumBitmap))); _initializeFuzzedQuorums(initializingBitmap); - bytes memory quorumNumbers = bitmapUtilsWrapper.bitmapToBytesArray( - quorumBitmap - ); + bytes memory quorumNumbers = bitmapUtilsWrapper.bitmapToBytesArray(quorumBitmap); /** * For each operator, randomly proceed with either registering/deregistering an operator @@ -855,17 +704,11 @@ contract BLSApkRegistryUnitTests_quorumApkUpdates is BLSApkRegistryUnitTests { // register and check quorum apk updates BN254.G1Point[] memory quorumApksBefore = _getApks(quorumNumbers); address operator = _selectNewOperator(); - (BN254.G1Point memory operatorPubkey, ) = _registerRandomBLSPubkey( - operator, - randSeed[i] - ); + (BN254.G1Point memory operatorPubkey,) = _registerRandomBLSPubkey(operator, randSeed[i]); _registerOperator(operator, quorumNumbers); BN254.G1Point[] memory quorumApksAfter = _getApks(quorumNumbers); _assertQuorumApkUpdates( - quorumNumbers, - quorumApksBefore, - quorumApksAfter, - operatorPubkey + quorumNumbers, quorumApksBefore, quorumApksAfter, operatorPubkey ); // deregister and check quorum apk updates @@ -875,10 +718,7 @@ contract BLSApkRegistryUnitTests_quorumApkUpdates is BLSApkRegistryUnitTests { _deregisterOperator(operator, quorumNumbers); quorumApksAfter = _getApks(quorumNumbers); _assertQuorumApkUpdates( - quorumNumbers, - quorumApksBefore, - quorumApksAfter, - operatorPubkey.negate() + quorumNumbers, quorumApksBefore, quorumApksAfter, operatorPubkey.negate() ); } } @@ -900,13 +740,9 @@ contract BLSApkRegistryUnitTests_quorumApkUpdates is BLSApkRegistryUnitTests { _initializeFuzzedQuorum(quorumNumber2); } - BN254.G1Point[] memory quorumApksBefore = new BN254.G1Point[]( - quorumNumbers.length - ); + BN254.G1Point[] memory quorumApksBefore = new BN254.G1Point[](quorumNumbers.length); for (uint8 i = 0; i < quorumNumbers.length; i++) { - quorumApksBefore[i] = blsApkRegistry.getApk( - uint8(quorumNumbers[i]) - ); + quorumApksBefore[i] = blsApkRegistry.getApk(uint8(quorumNumbers[i])); } // use harnessed function to directly set the pubkey, bypassing the ordinary checks @@ -917,16 +753,9 @@ contract BLSApkRegistryUnitTests_quorumApkUpdates is BLSApkRegistryUnitTests { //check quorum apk updates for (uint8 i = 0; i < quorumNumbers.length; i++) { - BN254.G1Point memory quorumApkAfter = blsApkRegistry.getApk( - uint8(quorumNumbers[i]) - ); + BN254.G1Point memory quorumApkAfter = blsApkRegistry.getApk(uint8(quorumNumbers[i])); assertEq( - BN254.hashG1Point( - BN254.plus( - quorumApkAfter, - BN254.negate(quorumApksBefore[i]) - ) - ), + BN254.hashG1Point(BN254.plus(quorumApkAfter, BN254.negate(quorumApksBefore[i]))), BN254.hashG1Point(defaultPubKey), "quorum apk not updated correctly" ); @@ -946,9 +775,7 @@ contract BLSApkRegistryUnitTests_quorumApkUpdates is BLSApkRegistryUnitTests { _registerRandomBLSPubkey(defaultOperator, randSeed); _registerOperator(defaultOperator, quorumNumbers); - BN254.G1Point memory quorumApk = blsApkRegistry.getApk( - defaultQuorumNumber - ); + BN254.G1Point memory quorumApk = blsApkRegistry.getApk(defaultQuorumNumber); BN254.G1Point memory negatedQuorumApk = BN254.negate(quorumApk); //register for one quorum with negative quorum apk @@ -984,23 +811,18 @@ contract BLSApkRegistryUnitTests_quorumApkUpdates is BLSApkRegistryUnitTests { for (uint256 i = 0; i < numRegistrants; i++) { // generate operator and register them with BLS pubkey address operator = _selectNewOperator(); - (BN254.G1Point memory operatorPubkey, ) = _registerRandomBLSPubkey( - operator, - uint256(keccak256(abi.encodePacked(operator, randSeed))) + (BN254.G1Point memory operatorPubkey,) = _registerRandomBLSPubkey( + operator, uint256(keccak256(abi.encodePacked(operator, randSeed))) ); _registerOperator(operator, quorumNumbers); quorumApk = quorumApk.plus(operatorPubkey); quorumApkHash = bytes24(BN254.hashG1Point(quorumApk)); - uint256 historyLength = blsApkRegistry.getApkHistoryLength( - defaultQuorumNumber - ); + uint256 historyLength = blsApkRegistry.getApkHistoryLength(defaultQuorumNumber); assertEq( quorumApkHash, blsApkRegistry.getApkHashAtBlockNumberAndIndex( - defaultQuorumNumber, - uint32(block.number + blockGap), - historyLength - 1 + defaultQuorumNumber, uint32(block.number + blockGap), historyLength - 1 ), "incorrect quorum apk update" ); @@ -1009,15 +831,11 @@ contract BLSApkRegistryUnitTests_quorumApkUpdates is BLSApkRegistryUnitTests { _deregisterOperator(operator, quorumNumbers); quorumApk = quorumApk.plus(operatorPubkey.negate()); quorumApkHash = bytes24(BN254.hashG1Point(quorumApk)); - historyLength = blsApkRegistry.getApkHistoryLength( - defaultQuorumNumber - ); + historyLength = blsApkRegistry.getApkHistoryLength(defaultQuorumNumber); assertEq( quorumApkHash, blsApkRegistry.getApkHashAtBlockNumberAndIndex( - defaultQuorumNumber, - uint32(block.number + blockGap), - historyLength - 1 + defaultQuorumNumber, uint32(block.number + blockGap), historyLength - 1 ), "incorrect quorum apk update" ); @@ -1047,8 +865,7 @@ contract BLSApkRegistryUnitTests_quorumApkUpdates is BLSApkRegistryUnitTests { for (uint256 i = 0; i < numRegistrants; i++) { address operator = _selectNewOperator(); _registerRandomBLSPubkey( - operator, - uint256(keccak256(abi.encodePacked(operator, randSeed))) + operator, uint256(keccak256(abi.encodePacked(operator, randSeed))) ); _registerOperator(operator, quorumNumbers); cheats.roll(block.number + 100); @@ -1057,20 +874,14 @@ contract BLSApkRegistryUnitTests_quorumApkUpdates is BLSApkRegistryUnitTests { emit log_named_uint("index too recent: ", indexToCheck); cheats.expectRevert(IBLSApkRegistryErrors.BlockNumberTooRecent.selector); blsApkRegistry.getApkHashAtBlockNumberAndIndex( - defaultQuorumNumber, - wrongBlockNumber, - indexToCheck + defaultQuorumNumber, wrongBlockNumber, indexToCheck ); } - if ( - wrongBlockNumber >= startingBlockNumber + (indexToCheck + 1) * 100 - ) { + if (wrongBlockNumber >= startingBlockNumber + (indexToCheck + 1) * 100) { emit log_named_uint("index not latest: ", indexToCheck); cheats.expectRevert(IBLSApkRegistryErrors.BlockNumberNotLatest.selector); blsApkRegistry.getApkHashAtBlockNumberAndIndex( - defaultQuorumNumber, - wrongBlockNumber, - indexToCheck + defaultQuorumNumber, wrongBlockNumber, indexToCheck ); } } @@ -1096,9 +907,7 @@ contract BLSApkRegistryUnitTests_quorumApkUpdates is BLSApkRegistryUnitTests { BN254.G1Point[] memory quorumApksBefore = new BN254.G1Point[](2); for (uint8 i = 0; i < quorumNumbers.length; i++) { - quorumApksBefore[i] = blsApkRegistry.getApk( - uint8(quorumNumbers[i]) - ); + quorumApksBefore[i] = blsApkRegistry.getApk(uint8(quorumNumbers[i])); } cheats.startPrank(address(registryCoordinator)); @@ -1108,13 +917,9 @@ contract BLSApkRegistryUnitTests_quorumApkUpdates is BLSApkRegistryUnitTests { BN254.G1Point memory quorumApkAfter; for (uint8 i = 0; i < quorumNumbers.length; i++) { quorumApkAfter = blsApkRegistry.getApk(uint8(quorumNumbers[i])); - BN254.G1Point memory quorumApk = blsApkRegistry.getApk( - defaultQuorumNumber - ); + BN254.G1Point memory quorumApk = blsApkRegistry.getApk(defaultQuorumNumber); assertEq( - BN254.hashG1Point( - quorumApksBefore[i].plus(defaultPubKey.negate()) - ), + BN254.hashG1Point(quorumApksBefore[i].plus(defaultPubKey.negate())), BN254.hashG1Point(quorumApkAfter), "quorum apk not updated correctly" ); diff --git a/test/unit/BLSSignatureCheckerUnit.t.sol b/test/unit/BLSSignatureCheckerUnit.t.sol index d1d0ac7f..a58d6112 100644 --- a/test/unit/BLSSignatureCheckerUnit.t.sol +++ b/test/unit/BLSSignatureCheckerUnit.t.sol @@ -15,7 +15,7 @@ contract BLSSignatureCheckerUnitTests is BLSMockAVSDeployer { event StaleStakesForbiddenUpdate(bool value); - function setUp() virtual public { + function setUp() public virtual { _setUpBLSMockAVSDeployer(); blsSignatureChecker = new BLSSignatureChecker(registryCoordinator); @@ -31,7 +31,9 @@ contract BLSSignatureCheckerUnitTests is BLSMockAVSDeployer { testFuzz_setStaleStakesForbidden(true); } - function testFuzz_setStaleStakesForbidden(bool newState) public { + function testFuzz_setStaleStakesForbidden( + bool newState + ) public { cheats.expectEmit(true, true, true, true, address(blsSignatureChecker)); emit StaleStakesForbiddenUpdate(newState); cheats.prank(registryCoordinatorOwner); @@ -42,35 +44,46 @@ contract BLSSignatureCheckerUnitTests is BLSMockAVSDeployer { // this test checks that a valid signature from maxOperatorsToRegister with a random number of nonsigners is checked // correctly on the BLSSignatureChecker contract when all operators are only regsitered for a single quorum and // the signature is only checked for stakes on that quorum - function testFuzz_checkSignatures_SingleQuorum(uint256 pseudoRandomNumber) public { + function testFuzz_checkSignatures_SingleQuorum( + uint256 pseudoRandomNumber + ) public { uint256 numNonSigners = pseudoRandomNumber % (maxOperatorsToRegister - 1); uint256 quorumBitmap = 1; bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmap); - (uint32 referenceBlockNumber, BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature) = - _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom(pseudoRandomNumber, numNonSigners, quorumBitmap); + ( + uint32 referenceBlockNumber, + BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature + ) = _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom( + pseudoRandomNumber, numNonSigners, quorumBitmap + ); - bytes32[] memory pubkeyHashes = new bytes32[](nonSignerStakesAndSignature.nonSignerPubkeys.length); + bytes32[] memory pubkeyHashes = + new bytes32[](nonSignerStakesAndSignature.nonSignerPubkeys.length); for (uint256 i = 0; i < nonSignerStakesAndSignature.nonSignerPubkeys.length; ++i) { pubkeyHashes[i] = nonSignerStakesAndSignature.nonSignerPubkeys[i].hashG1Point(); } - bytes32 expectedSignatoryRecordHash = keccak256(abi.encodePacked(referenceBlockNumber, pubkeyHashes)); + bytes32 expectedSignatoryRecordHash = + keccak256(abi.encodePacked(referenceBlockNumber, pubkeyHashes)); uint256 gasBefore = gasleft(); ( BLSSignatureChecker.QuorumStakeTotals memory quorumStakeTotals, bytes32 signatoryRecordHash ) = blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - nonSignerStakesAndSignature + msgHash, quorumNumbers, referenceBlockNumber, nonSignerStakesAndSignature ); uint256 gasAfter = gasleft(); emit log_named_uint("gasUsed", gasBefore - gasAfter); - assertTrue(quorumStakeTotals.signedStakeForQuorum[0] > 0, "signedStakeForQuorum should be nonzero"); - assertEq(expectedSignatoryRecordHash, signatoryRecordHash, "signatoryRecordHash does not match expectation"); + assertTrue( + quorumStakeTotals.signedStakeForQuorum[0] > 0, "signedStakeForQuorum should be nonzero" + ); + assertEq( + expectedSignatoryRecordHash, + signatoryRecordHash, + "signatoryRecordHash does not match expectation" + ); // 0 nonSigners: 159908 // 1 nonSigner: 178683 // 2 nonSigners: 197410 @@ -82,82 +95,114 @@ contract BLSSignatureCheckerUnitTests is BLSMockAVSDeployer { uint256 quorumBitmap = 1; bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmap); - (uint32 referenceBlockNumber, BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature) = - _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom(nonRandomNumber, numNonSigners, quorumBitmap); + ( + uint32 referenceBlockNumber, + BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature + ) = _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom( + nonRandomNumber, numNonSigners, quorumBitmap + ); - bytes32[] memory pubkeyHashes = new bytes32[](nonSignerStakesAndSignature.nonSignerPubkeys.length); + bytes32[] memory pubkeyHashes = + new bytes32[](nonSignerStakesAndSignature.nonSignerPubkeys.length); for (uint256 i = 0; i < nonSignerStakesAndSignature.nonSignerPubkeys.length; ++i) { pubkeyHashes[i] = nonSignerStakesAndSignature.nonSignerPubkeys[i].hashG1Point(); } - bytes32 expectedSignatoryRecordHash = keccak256(abi.encodePacked(referenceBlockNumber, pubkeyHashes)); + bytes32 expectedSignatoryRecordHash = + keccak256(abi.encodePacked(referenceBlockNumber, pubkeyHashes)); uint256 gasBefore = gasleft(); ( BLSSignatureChecker.QuorumStakeTotals memory quorumStakeTotals, bytes32 signatoryRecordHash ) = blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - nonSignerStakesAndSignature + msgHash, quorumNumbers, referenceBlockNumber, nonSignerStakesAndSignature ); uint256 gasAfter = gasleft(); emit log_named_uint("gasUsed", gasBefore - gasAfter); - assertEq(expectedSignatoryRecordHash, signatoryRecordHash, "signatoryRecordHash does not match expectation"); + assertEq( + expectedSignatoryRecordHash, + signatoryRecordHash, + "signatoryRecordHash does not match expectation" + ); - assertEq(quorumStakeTotals.signedStakeForQuorum[0], 3000000000000000000, "signedStakeForQuorum incorrect"); - assertEq(quorumStakeTotals.totalStakeForQuorum[0], 4000000000000000000, "totalStakeForQuorum incorrect"); + assertEq( + quorumStakeTotals.signedStakeForQuorum[0], + 3_000_000_000_000_000_000, + "signedStakeForQuorum incorrect" + ); + assertEq( + quorumStakeTotals.totalStakeForQuorum[0], + 4_000_000_000_000_000_000, + "totalStakeForQuorum incorrect" + ); } // this test checks that a valid signature from maxOperatorsToRegister with a random number of nonsigners is checked // correctly on the BLSSignatureChecker contract when all operators are registered for the first 100 quorums // and the signature is only checked for stakes on those quorums - function test_checkSignatures_100Quorums(uint256 pseudoRandomNumber) public { + function test_checkSignatures_100Quorums( + uint256 pseudoRandomNumber + ) public { uint256 numNonSigners = pseudoRandomNumber % (maxOperatorsToRegister - 1); // 100 set bits uint256 quorumBitmap = (1 << 100) - 1; bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmap); - (uint32 referenceBlockNumber, BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature) = - _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom(pseudoRandomNumber, numNonSigners, quorumBitmap); + ( + uint32 referenceBlockNumber, + BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature + ) = _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom( + pseudoRandomNumber, numNonSigners, quorumBitmap + ); nonSignerStakesAndSignature.sigma = sigma.scalar_mul(quorumNumbers.length); nonSignerStakesAndSignature.apkG2 = oneHundredQuorumApkG2; - bytes32[] memory pubkeyHashes = new bytes32[](nonSignerStakesAndSignature.nonSignerPubkeys.length); + bytes32[] memory pubkeyHashes = + new bytes32[](nonSignerStakesAndSignature.nonSignerPubkeys.length); for (uint256 i = 0; i < nonSignerStakesAndSignature.nonSignerPubkeys.length; ++i) { pubkeyHashes[i] = nonSignerStakesAndSignature.nonSignerPubkeys[i].hashG1Point(); } - bytes32 expectedSignatoryRecordHash = keccak256(abi.encodePacked(referenceBlockNumber, pubkeyHashes)); + bytes32 expectedSignatoryRecordHash = + keccak256(abi.encodePacked(referenceBlockNumber, pubkeyHashes)); uint256 gasBefore = gasleft(); ( BLSSignatureChecker.QuorumStakeTotals memory quorumStakeTotals, bytes32 signatoryRecordHash ) = blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - nonSignerStakesAndSignature + msgHash, quorumNumbers, referenceBlockNumber, nonSignerStakesAndSignature ); uint256 gasAfter = gasleft(); emit log_named_uint("gasUsed", gasBefore - gasAfter); for (uint256 i = 0; i < quorumStakeTotals.signedStakeForQuorum.length; ++i) { - assertTrue(quorumStakeTotals.signedStakeForQuorum[i] > 0, "signedStakeForQuorum should be nonzero"); + assertTrue( + quorumStakeTotals.signedStakeForQuorum[i] > 0, + "signedStakeForQuorum should be nonzero" + ); } - assertEq(expectedSignatoryRecordHash, signatoryRecordHash, "signatoryRecordHash does not match expectation"); + assertEq( + expectedSignatoryRecordHash, + signatoryRecordHash, + "signatoryRecordHash does not match expectation" + ); } function test_checkSignatures_revert_inputLengthMismatch() public { uint256 numNonSigners = 0; uint256 quorumBitmap = 1; bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmap); - (uint32 referenceBlockNumber, BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature) = - _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom(1, numNonSigners, quorumBitmap); + ( + uint32 referenceBlockNumber, + BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature + ) = _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom( + 1, numNonSigners, quorumBitmap + ); - IBLSSignatureChecker.NonSignerStakesAndSignature memory incorrectLengthInputs = IBLSSignatureChecker.NonSignerStakesAndSignature({ + IBLSSignatureChecker.NonSignerStakesAndSignature memory incorrectLengthInputs = + IBLSSignatureChecker.NonSignerStakesAndSignature({ nonSignerQuorumBitmapIndices: nonSignerStakesAndSignature.nonSignerQuorumBitmapIndices, nonSignerPubkeys: nonSignerStakesAndSignature.nonSignerPubkeys, quorumApks: nonSignerStakesAndSignature.quorumApks, @@ -172,10 +217,7 @@ contract BLSSignatureCheckerUnitTests is BLSMockAVSDeployer { cheats.expectRevert(IBLSSignatureCheckerErrors.InputArrayLengthMismatch.selector); blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - incorrectLengthInputs + msgHash, quorumNumbers, referenceBlockNumber, incorrectLengthInputs ); // reset the input to correct values @@ -184,10 +226,7 @@ contract BLSSignatureCheckerUnitTests is BLSMockAVSDeployer { incorrectLengthInputs.quorumApkIndices = new uint32[](5); cheats.expectRevert(IBLSSignatureCheckerErrors.InputArrayLengthMismatch.selector); blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - incorrectLengthInputs + msgHash, quorumNumbers, referenceBlockNumber, incorrectLengthInputs ); // reset the input to correct values @@ -196,10 +235,7 @@ contract BLSSignatureCheckerUnitTests is BLSMockAVSDeployer { incorrectLengthInputs.totalStakeIndices = new uint32[](5); cheats.expectRevert(IBLSSignatureCheckerErrors.InputArrayLengthMismatch.selector); blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - incorrectLengthInputs + msgHash, quorumNumbers, referenceBlockNumber, incorrectLengthInputs ); // reset the input to correct values @@ -208,51 +244,47 @@ contract BLSSignatureCheckerUnitTests is BLSMockAVSDeployer { incorrectLengthInputs.nonSignerStakeIndices = new uint32[][](5); cheats.expectRevert(IBLSSignatureCheckerErrors.InputArrayLengthMismatch.selector); blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - incorrectLengthInputs + msgHash, quorumNumbers, referenceBlockNumber, incorrectLengthInputs ); // reset the input to correct values - incorrectLengthInputs.nonSignerStakeIndices = nonSignerStakesAndSignature.nonSignerStakeIndices; + incorrectLengthInputs.nonSignerStakeIndices = + nonSignerStakesAndSignature.nonSignerStakeIndices; // make one part of the input incorrect length - incorrectLengthInputs.nonSignerQuorumBitmapIndices = new uint32[](nonSignerStakesAndSignature.nonSignerPubkeys.length + 1); + incorrectLengthInputs.nonSignerQuorumBitmapIndices = + new uint32[](nonSignerStakesAndSignature.nonSignerPubkeys.length + 1); cheats.expectRevert(IBLSSignatureCheckerErrors.InputNonSignerLengthMismatch.selector); blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - incorrectLengthInputs + msgHash, quorumNumbers, referenceBlockNumber, incorrectLengthInputs ); // reset the input to correct values - incorrectLengthInputs.nonSignerQuorumBitmapIndices = nonSignerStakesAndSignature.nonSignerQuorumBitmapIndices; + incorrectLengthInputs.nonSignerQuorumBitmapIndices = + nonSignerStakesAndSignature.nonSignerQuorumBitmapIndices; // sanity check for call passing with the correct values blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - incorrectLengthInputs + msgHash, quorumNumbers, referenceBlockNumber, incorrectLengthInputs ); } - function test_checkSignatures_revert_referenceBlockNumberInFuture(uint256 pseudoRandomNumber) public { + function test_checkSignatures_revert_referenceBlockNumberInFuture( + uint256 pseudoRandomNumber + ) public { uint256 numNonSigners = pseudoRandomNumber % (maxOperatorsToRegister - 2) + 1; uint256 quorumBitmap = 1; bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmap); - (/*uint32 referenceBlockNumber*/, BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature) = - _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom(pseudoRandomNumber, numNonSigners, quorumBitmap); + ( /*uint32 referenceBlockNumber*/ + , BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature + ) = _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom( + pseudoRandomNumber, numNonSigners, quorumBitmap + ); // Create an invalid reference block: any block number >= the current block uint32 invalidReferenceBlock = uint32(block.number + (pseudoRandomNumber % 20)); cheats.expectRevert(IBLSSignatureCheckerErrors.InvalidReferenceBlocknumber.selector); blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - invalidReferenceBlock, - nonSignerStakesAndSignature + msgHash, quorumNumbers, invalidReferenceBlock, nonSignerStakesAndSignature ); } @@ -262,17 +294,19 @@ contract BLSSignatureCheckerUnitTests is BLSMockAVSDeployer { uint256 nonRandomNumber = 777; bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmap); - (uint32 referenceBlockNumber, BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature) = - _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom(nonRandomNumber, numNonSigners, quorumBitmap); + ( + uint32 referenceBlockNumber, + BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature + ) = _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom( + nonRandomNumber, numNonSigners, quorumBitmap + ); // swap out a pubkey to make sure there is a duplicate - nonSignerStakesAndSignature.nonSignerPubkeys[1] = nonSignerStakesAndSignature.nonSignerPubkeys[0]; + nonSignerStakesAndSignature.nonSignerPubkeys[1] = + nonSignerStakesAndSignature.nonSignerPubkeys[0]; cheats.expectRevert(IBLSSignatureCheckerErrors.NonSignerPubkeysNotSorted.selector); blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - nonSignerStakesAndSignature + msgHash, quorumNumbers, referenceBlockNumber, nonSignerStakesAndSignature ); } @@ -282,18 +316,24 @@ contract BLSSignatureCheckerUnitTests is BLSMockAVSDeployer { uint256 nonRandomNumber = 777; bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmap); - (uint32 referenceBlockNumber, BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature) = - _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom(nonRandomNumber, numNonSigners, quorumBitmap); + ( + uint32 referenceBlockNumber, + BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature + ) = _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom( + nonRandomNumber, numNonSigners, quorumBitmap + ); // swap two pubkeys to ensure ordering is wrong - (nonSignerStakesAndSignature.nonSignerPubkeys[0], nonSignerStakesAndSignature.nonSignerPubkeys[1]) = - (nonSignerStakesAndSignature.nonSignerPubkeys[1], nonSignerStakesAndSignature.nonSignerPubkeys[0]); + ( + nonSignerStakesAndSignature.nonSignerPubkeys[0], + nonSignerStakesAndSignature.nonSignerPubkeys[1] + ) = ( + nonSignerStakesAndSignature.nonSignerPubkeys[1], + nonSignerStakesAndSignature.nonSignerPubkeys[0] + ); cheats.expectRevert(IBLSSignatureCheckerErrors.NonSignerPubkeysNotSorted.selector); blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - nonSignerStakesAndSignature + msgHash, quorumNumbers, referenceBlockNumber, nonSignerStakesAndSignature ); } @@ -303,31 +343,34 @@ contract BLSSignatureCheckerUnitTests is BLSMockAVSDeployer { uint256 nonRandomNumber = 777; bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmap); - (uint32 referenceBlockNumber, BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature) = - _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom(nonRandomNumber, numNonSigners, quorumBitmap); + ( + uint32 referenceBlockNumber, + BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature + ) = _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom( + nonRandomNumber, numNonSigners, quorumBitmap + ); // make sure the `staleStakesForbidden` flag is set to 'true' testFuzz_setStaleStakesForbidden(true); uint256 stalestUpdateBlock = type(uint256).max; for (uint256 i = 0; i < quorumNumbers.length; ++i) { - uint256 quorumUpdateBlockNumber = registryCoordinator.quorumUpdateBlockNumber(uint8(quorumNumbers[i])); + uint256 quorumUpdateBlockNumber = + registryCoordinator.quorumUpdateBlockNumber(uint8(quorumNumbers[i])); if (quorumUpdateBlockNumber < stalestUpdateBlock) { stalestUpdateBlock = quorumUpdateBlockNumber; } } // move referenceBlockNumber forward to a block number the last block number where the stakes will be considered "not stale" - referenceBlockNumber = uint32(stalestUpdateBlock + delegationMock.minWithdrawalDelayBlocks()) - 1; + referenceBlockNumber = + uint32(stalestUpdateBlock + delegationMock.minWithdrawalDelayBlocks()) - 1; // roll forward to make the reference block number valid // we roll to referenceBlockNumber + 1 because the current block number is not a valid reference block cheats.roll(referenceBlockNumber + 1); blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - nonSignerStakesAndSignature + msgHash, quorumNumbers, referenceBlockNumber, nonSignerStakesAndSignature ); // move referenceBlockNumber forward one more block, making the stakes "stale" @@ -336,153 +379,172 @@ contract BLSSignatureCheckerUnitTests is BLSMockAVSDeployer { cheats.roll(referenceBlockNumber + 1); cheats.expectRevert(IBLSSignatureCheckerErrors.StaleStakesForbidden.selector); blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - nonSignerStakesAndSignature + msgHash, quorumNumbers, referenceBlockNumber, nonSignerStakesAndSignature ); } - function test_checkSignatures_revert_incorrectQuorumBitmapIndex(uint256 pseudoRandomNumber) public { + function test_checkSignatures_revert_incorrectQuorumBitmapIndex( + uint256 pseudoRandomNumber + ) public { uint256 numNonSigners = pseudoRandomNumber % (maxOperatorsToRegister - 2) + 1; uint256 quorumBitmap = 1; bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmap); - (uint32 referenceBlockNumber, BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature) = - _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom(pseudoRandomNumber, numNonSigners, quorumBitmap); + ( + uint32 referenceBlockNumber, + BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature + ) = _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom( + pseudoRandomNumber, numNonSigners, quorumBitmap + ); // record a quorumBitmap update via a harnessed function - registryCoordinator._updateOperatorBitmapExternal(nonSignerStakesAndSignature.nonSignerPubkeys[0].hashG1Point(), uint192(quorumBitmap | 2)); + registryCoordinator._updateOperatorBitmapExternal( + nonSignerStakesAndSignature.nonSignerPubkeys[0].hashG1Point(), uint192(quorumBitmap | 2) + ); // set the nonSignerQuorumBitmapIndices to a different value nonSignerStakesAndSignature.nonSignerQuorumBitmapIndices[0] = 1; cheats.expectRevert(QuorumBitmapHistoryLib.BitmapUpdateIsAfterBlockNumber.selector); blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - nonSignerStakesAndSignature + msgHash, quorumNumbers, referenceBlockNumber, nonSignerStakesAndSignature ); } - function test_checkSignatures_revert_incorrectTotalStakeIndex(uint256 pseudoRandomNumber) public { + function test_checkSignatures_revert_incorrectTotalStakeIndex( + uint256 pseudoRandomNumber + ) public { uint256 numNonSigners = pseudoRandomNumber % (maxOperatorsToRegister - 2) + 1; uint256 quorumBitmap = 1; bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmap); - (uint32 referenceBlockNumber, BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature) = - _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom(pseudoRandomNumber, numNonSigners, quorumBitmap); + ( + uint32 referenceBlockNumber, + BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature + ) = _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom( + pseudoRandomNumber, numNonSigners, quorumBitmap + ); // set the totalStakeIndices to a different value nonSignerStakesAndSignature.totalStakeIndices[0] = 0; cheats.expectRevert(IStakeRegistryErrors.InvalidBlockNumber.selector); blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - nonSignerStakesAndSignature + msgHash, quorumNumbers, referenceBlockNumber, nonSignerStakesAndSignature ); } - function test_checkSignatures_revert_incorrectNonSignerStakeIndex(uint256 pseudoRandomNumber) public { + function test_checkSignatures_revert_incorrectNonSignerStakeIndex( + uint256 pseudoRandomNumber + ) public { uint256 numNonSigners = pseudoRandomNumber % (maxOperatorsToRegister - 2) + 1; uint256 quorumBitmap = 1; bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmap); - (uint32 referenceBlockNumber, BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature) = - _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom(pseudoRandomNumber, numNonSigners, quorumBitmap); + ( + uint32 referenceBlockNumber, + BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature + ) = _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom( + pseudoRandomNumber, numNonSigners, quorumBitmap + ); bytes32 nonSignerOperatorId = nonSignerStakesAndSignature.nonSignerPubkeys[0].hashG1Point(); // record a stake update - stakeRegistry.recordOperatorStakeUpdate( - nonSignerOperatorId, - uint8(quorumNumbers[0]), - 1234 - ); + stakeRegistry.recordOperatorStakeUpdate(nonSignerOperatorId, uint8(quorumNumbers[0]), 1234); // set the nonSignerStakeIndices to a different value nonSignerStakesAndSignature.nonSignerStakeIndices[0][0] = 1; cheats.expectRevert(IStakeRegistryErrors.InvalidBlockNumber.selector); blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - nonSignerStakesAndSignature + msgHash, quorumNumbers, referenceBlockNumber, nonSignerStakesAndSignature ); - } - function test_checkSignatures_revert_incorrectQuorumAPKIndex(uint256 pseudoRandomNumber) public { + function test_checkSignatures_revert_incorrectQuorumAPKIndex( + uint256 pseudoRandomNumber + ) public { uint256 numNonSigners = pseudoRandomNumber % (maxOperatorsToRegister - 2) + 1; uint256 quorumBitmap = 1; bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmap); - (uint32 referenceBlockNumber, BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature) = - _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom(pseudoRandomNumber, numNonSigners, quorumBitmap); + ( + uint32 referenceBlockNumber, + BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature + ) = _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom( + pseudoRandomNumber, numNonSigners, quorumBitmap + ); // set the quorumApkIndices to a different value nonSignerStakesAndSignature.quorumApkIndices[0] = 0; cheats.expectRevert(IBLSApkRegistryErrors.BlockNumberNotLatest.selector); blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - nonSignerStakesAndSignature + msgHash, quorumNumbers, referenceBlockNumber, nonSignerStakesAndSignature ); } - function test_checkSignatures_revert_incorrectQuorumAPK(uint256 pseudoRandomNumber) public { + function test_checkSignatures_revert_incorrectQuorumAPK( + uint256 pseudoRandomNumber + ) public { uint256 numNonSigners = pseudoRandomNumber % (maxOperatorsToRegister - 2) + 1; uint256 quorumBitmap = 1; bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmap); - (uint32 referenceBlockNumber, BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature) = - _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom(pseudoRandomNumber, numNonSigners, quorumBitmap); + ( + uint32 referenceBlockNumber, + BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature + ) = _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom( + pseudoRandomNumber, numNonSigners, quorumBitmap + ); // set the quorumApk to a different value - nonSignerStakesAndSignature.quorumApks[0] = nonSignerStakesAndSignature.quorumApks[0].negate(); + nonSignerStakesAndSignature.quorumApks[0] = + nonSignerStakesAndSignature.quorumApks[0].negate(); cheats.expectRevert(IBLSSignatureCheckerErrors.InvalidQuorumApkHash.selector); blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - nonSignerStakesAndSignature + msgHash, quorumNumbers, referenceBlockNumber, nonSignerStakesAndSignature ); } - function test_checkSignatures_revert_incorrectSignature(uint256 pseudoRandomNumber) public { + function test_checkSignatures_revert_incorrectSignature( + uint256 pseudoRandomNumber + ) public { uint256 numNonSigners = pseudoRandomNumber % (maxOperatorsToRegister - 2) + 1; uint256 quorumBitmap = 1; bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmap); - (uint32 referenceBlockNumber, BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature) = - _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom(pseudoRandomNumber, numNonSigners, quorumBitmap); + ( + uint32 referenceBlockNumber, + BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature + ) = _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom( + pseudoRandomNumber, numNonSigners, quorumBitmap + ); // set the sigma to a different value nonSignerStakesAndSignature.sigma = nonSignerStakesAndSignature.sigma.negate(); cheats.expectRevert(IBLSSignatureCheckerErrors.InvalidBLSSignature.selector); blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - nonSignerStakesAndSignature + msgHash, quorumNumbers, referenceBlockNumber, nonSignerStakesAndSignature ); } - function test_checkSignatures_revert_invalidSignature(uint256 pseudoRandomNumber) public { + function test_checkSignatures_revert_invalidSignature( + uint256 pseudoRandomNumber + ) public { uint256 numNonSigners = pseudoRandomNumber % (maxOperatorsToRegister - 2) + 1; uint256 quorumBitmap = 1; bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmap); - (uint32 referenceBlockNumber, BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature) = - _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom(pseudoRandomNumber, numNonSigners, quorumBitmap); + ( + uint32 referenceBlockNumber, + BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature + ) = _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom( + pseudoRandomNumber, numNonSigners, quorumBitmap + ); // set the sigma to a different value nonSignerStakesAndSignature.sigma.X++; @@ -490,20 +552,23 @@ contract BLSSignatureCheckerUnitTests is BLSMockAVSDeployer { // expect a non-specific low-level revert, since this call will ultimately fail as part of the precompile call cheats.expectRevert(); blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - nonSignerStakesAndSignature + msgHash, quorumNumbers, referenceBlockNumber, nonSignerStakesAndSignature ); } - function testBLSSignatureChecker_reverts_emptyQuorums(uint256 pseudoRandomNumber) public { + function testBLSSignatureChecker_reverts_emptyQuorums( + uint256 pseudoRandomNumber + ) public { uint256 numNonSigners = pseudoRandomNumber % (maxOperatorsToRegister - 2) + 1; uint256 quorumBitmap = 1; - (uint32 referenceBlockNumber, BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature) = - _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom(pseudoRandomNumber, numNonSigners, quorumBitmap); + ( + uint32 referenceBlockNumber, + BLSSignatureChecker.NonSignerStakesAndSignature memory nonSignerStakesAndSignature + ) = _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom( + pseudoRandomNumber, numNonSigners, quorumBitmap + ); // Create an empty quorumNumbers array bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(0); @@ -511,10 +576,7 @@ contract BLSSignatureCheckerUnitTests is BLSMockAVSDeployer { // expect a non-specific low-level revert, since this call will ultimately fail as part of the precompile call cheats.expectRevert(IBLSSignatureCheckerErrors.InputEmptyQuorumNumbers.selector); blsSignatureChecker.checkSignatures( - msgHash, - quorumNumbers, - referenceBlockNumber, - nonSignerStakesAndSignature + msgHash, quorumNumbers, referenceBlockNumber, nonSignerStakesAndSignature ); } } diff --git a/test/unit/BitmapUtils.t.sol b/test/unit/BitmapUtils.t.sol index a998dbe3..1563d687 100644 --- a/test/unit/BitmapUtils.t.sol +++ b/test/unit/BitmapUtils.t.sol @@ -18,7 +18,9 @@ contract BitmapUtilsUnitTests is Test { contract BitmapUtilsUnitTests_bitwiseOperations is BitmapUtilsUnitTests { /// @notice check for consistency of `countNumOnes` function - function testFuzz_countNumOnes(uint256 input) public { + function testFuzz_countNumOnes( + uint256 input + ) public { uint16 libraryOutput = bitmapUtilsWrapper.countNumOnes(input); // run dumb routine uint16 numOnes = 0; @@ -37,7 +39,9 @@ contract BitmapUtilsUnitTests_bitwiseOperations is BitmapUtilsUnitTests { assertTrue(bitmapUtilsWrapper.isSet(255, 7), "isSet function is broken 2"); assertTrue(bitmapUtilsWrapper.isSet(1024, 10), "isSet function is broken 3"); for (uint256 i = 0; i < 256; ++i) { - assertTrue(bitmapUtilsWrapper.isSet(type(uint256).max, uint8(i)), "isSet function is broken 4"); + assertTrue( + bitmapUtilsWrapper.isSet(type(uint256).max, uint8(i)), "isSet function is broken 4" + ); assertFalse(bitmapUtilsWrapper.isSet(0, uint8(i)), "isSet function is broken 5"); } } @@ -46,12 +50,12 @@ contract BitmapUtilsUnitTests_bitwiseOperations is BitmapUtilsUnitTests { // Ensure that numberToAdd isn't already in the bitmap cheats.assume(bitmap | (1 << bitToSet) != bitmap); uint256 updatedBitmap = bitmapUtilsWrapper.setBit(bitmap, bitToSet); - assertTrue( - bitmapUtilsWrapper.isSet(updatedBitmap, bitToSet), "setBit function is broken" - ); + assertTrue(bitmapUtilsWrapper.isSet(updatedBitmap, bitToSet), "setBit function is broken"); } - function testFuzz_isEmpty(uint256 input) public { + function testFuzz_isEmpty( + uint256 input + ) public { if (input == 0) { // assertTrue(bitmapUtilsWrapper.isEmpty(input), "isEmpty function is broken"); assertTrue(bitmapUtilsWrapper.isEmpty(input), "isEmpty function is broken"); @@ -123,16 +127,24 @@ contract BitmapUtilsUnitTests_bytesArrayToBitmap is BitmapUtilsUnitTests { function test_EmptyArrayEncoding() public { bytes memory emptyBytesArray; uint256 returnedBitMap = bitmapUtilsWrapper.orderedBytesArrayToBitmap(emptyBytesArray); - assertEq(returnedBitMap, 0, "BitmapUtilsUnitTests.testEmptyArrayEncoding: empty array not encoded to empty bitmap"); + assertEq( + returnedBitMap, + 0, + "BitmapUtilsUnitTests.testEmptyArrayEncoding: empty array not encoded to empty bitmap" + ); } // ensure that the bitmap encoding of a single uint8 (i.e. a single byte) matches the expected output - function testFuzz_SingleByteEncoding(uint8 fuzzedNumber) public { + function testFuzz_SingleByteEncoding( + uint8 fuzzedNumber + ) public { bytes1 singleByte = bytes1(fuzzedNumber); bytes memory bytesArray = abi.encodePacked(singleByte); uint256 returnedBitMap = bitmapUtilsWrapper.orderedBytesArrayToBitmap(bytesArray); uint256 bitMask = uint256(1 << fuzzedNumber); - assertEq(returnedBitMap, bitMask, "BitmapUtilsUnitTests.testSingleByteEncoding: non-equivalence"); + assertEq( + returnedBitMap, bitMask, "BitmapUtilsUnitTests.testSingleByteEncoding: non-equivalence" + ); } // ensure that the bitmap encoding of a two uint8's (i.e. a two byte array) matches the expected output @@ -142,20 +154,28 @@ contract BitmapUtilsUnitTests_bytesArrayToBitmap is BitmapUtilsUnitTests { bytes1 secondSingleByte = bytes1(secondFuzzedNumber); bytes memory bytesArray = abi.encodePacked(firstSingleByte, secondSingleByte); if (firstFuzzedNumber == secondFuzzedNumber) { - cheats.expectRevert(bytes("BitmapUtils.orderedBytesArrayToBitmap: repeat entry in bytesArray")); + cheats.expectRevert( + bytes("BitmapUtils.orderedBytesArrayToBitmap: repeat entry in bytesArray") + ); bitmapUtilsWrapper.orderedBytesArrayToBitmap(bytesArray); } else { uint256 returnedBitMap = bitmapUtilsWrapper.orderedBytesArrayToBitmap(bytesArray); uint256 firstBitMask = uint256(1 << firstFuzzedNumber); uint256 secondBitMask = uint256(1 << secondFuzzedNumber); uint256 combinedBitMask = firstBitMask | secondBitMask; - assertEq(returnedBitMap, combinedBitMask, "BitmapUtilsUnitTests.testTwoByteEncoding: non-equivalence"); + assertEq( + returnedBitMap, + combinedBitMask, + "BitmapUtilsUnitTests.testTwoByteEncoding: non-equivalence" + ); } } // ensure that converting bytes array => bitmap => bytes array returns the original bytes array (i.e. is lossless and artifactless) // note that this only works on ordered arrays, because unordered arrays will be returned ordered - function testFuzz_BytesArrayToBitmapToBytesArray(bytes memory originalBytesArray) public { + function testFuzz_BytesArrayToBitmapToBytesArray( + bytes memory originalBytesArray + ) public { // filter down to only ordered inputs cheats.assume(bitmapUtilsWrapper.isArrayStrictlyAscendingOrdered(originalBytesArray)); uint256 bitmap = bitmapUtilsWrapper.orderedBytesArrayToBitmap(originalBytesArray); @@ -169,7 +189,9 @@ contract BitmapUtilsUnitTests_bytesArrayToBitmap is BitmapUtilsUnitTests { // ensure that converting bytes array => bitmap => bytes array returns the original bytes array (i.e. is lossless and artifactless) // note that this only works on ordered arrays - function testFuzz_BytesArrayToBitmapToBytesArray_OrderedVersion(bytes memory originalBytesArray) public { + function testFuzz_BytesArrayToBitmapToBytesArray_OrderedVersion( + bytes memory originalBytesArray + ) public { // filter down to only ordered inputs cheats.assume(bitmapUtilsWrapper.isArrayStrictlyAscendingOrdered(originalBytesArray)); uint256 bitmap = bitmapUtilsWrapper.orderedBytesArrayToBitmap(originalBytesArray); @@ -183,7 +205,9 @@ contract BitmapUtilsUnitTests_bytesArrayToBitmap is BitmapUtilsUnitTests { /// @notice Test that for non-strictly ascending bytes array ordering always reverts /// when calling orderedBytesArrayToBitmap - function testFuzz_OrderedBytesArrayToBitmap_Revert_WhenNotOrdered(bytes memory originalBytesArray) public { + function testFuzz_OrderedBytesArrayToBitmap_Revert_WhenNotOrdered( + bytes memory originalBytesArray + ) public { cheats.assume(!bitmapUtilsWrapper.isArrayStrictlyAscendingOrdered(originalBytesArray)); cheats.expectRevert(BitmapUtils.BytesArrayNotOrdered.selector); bitmapUtilsWrapper.orderedBytesArrayToBitmap(originalBytesArray); @@ -191,7 +215,9 @@ contract BitmapUtilsUnitTests_bytesArrayToBitmap is BitmapUtilsUnitTests { // ensure that converting bytes array => bitmap => bytes array returns the original bytes array (i.e. is lossless and artifactless) // note that this only works on ordered arrays - function testFuzz_BytesArrayToBitmapToBytesArray_OrderedVersion_Yul(bytes memory originalBytesArray) public { + function testFuzz_BytesArrayToBitmapToBytesArray_OrderedVersion_Yul( + bytes memory originalBytesArray + ) public { // filter down to only ordered inputs cheats.assume(bitmapUtilsWrapper.isArrayStrictlyAscendingOrdered(originalBytesArray)); uint256 bitmap = bitmapUtilsWrapper.orderedBytesArrayToBitmap(originalBytesArray); @@ -206,7 +232,14 @@ contract BitmapUtilsUnitTests_bytesArrayToBitmap is BitmapUtilsUnitTests { // testing one function for a specific input. used for comparing gas costs function test_BytesArrayToBitmap_OrderedVersion_SpecificInput() public { bytes memory originalBytesArray = abi.encodePacked( - bytes1(uint8(5)), bytes1(uint8(6)), bytes1(uint8(7)), bytes1(uint8(8)), bytes1(uint8(9)), bytes1(uint8(10)), bytes1(uint8(11)), bytes1(uint8(12)) + bytes1(uint8(5)), + bytes1(uint8(6)), + bytes1(uint8(7)), + bytes1(uint8(8)), + bytes1(uint8(9)), + bytes1(uint8(10)), + bytes1(uint8(11)), + bytes1(uint8(12)) ); uint256 gasLeftBefore = gasleft(); uint256 bitmap = bitmapUtilsWrapper.orderedBytesArrayToBitmap(originalBytesArray); @@ -219,7 +252,14 @@ contract BitmapUtilsUnitTests_bytesArrayToBitmap is BitmapUtilsUnitTests { // testing one function for a specific input. used for comparing gas costs function test_BytesArrayToBitmap_SpecificInput() public { bytes memory originalBytesArray = abi.encodePacked( - bytes1(uint8(5)), bytes1(uint8(6)), bytes1(uint8(7)), bytes1(uint8(8)), bytes1(uint8(9)), bytes1(uint8(10)), bytes1(uint8(11)), bytes1(uint8(12)) + bytes1(uint8(5)), + bytes1(uint8(6)), + bytes1(uint8(7)), + bytes1(uint8(8)), + bytes1(uint8(9)), + bytes1(uint8(10)), + bytes1(uint8(11)), + bytes1(uint8(12)) ); uint256 gasLeftBefore = gasleft(); uint256 bitmap = bitmapUtilsWrapper.orderedBytesArrayToBitmap(originalBytesArray); @@ -229,7 +269,9 @@ contract BitmapUtilsUnitTests_bytesArrayToBitmap is BitmapUtilsUnitTests { emit log_named_uint("gasSpent", gasSpent); } - function testFuzz_bitmapToBytesArrayToBitmap(uint256 originalBitmap) public { + function testFuzz_bitmapToBytesArrayToBitmap( + uint256 originalBitmap + ) public { uint256 gasLeftBefore = gasleft(); bytes memory bytesArray = bitmapUtilsWrapper.bitmapToBytesArray(originalBitmap); uint256 gasLeftAfter = gasleft(); @@ -256,7 +298,7 @@ contract BitmapUtilsUnitTests_bytesArrayToBitmap is BitmapUtilsUnitTests { function test_bitmapToBytesArrayToBitmap_distributedTenEntriesBitmap() public { // 2^0+2^10+2^20+2^30+2^40+2^50+2^60+2^70+2^80+2^90 - uint256 originalBitmap = 1239150146850664126585242625; + uint256 originalBitmap = 1_239_150_146_850_664_126_585_242_625; testFuzz_bitmapToBytesArrayToBitmap(originalBitmap); } } @@ -265,16 +307,37 @@ contract BitmapUtilsUnitTests_isArrayStrictlyAscendingOrdered is BitmapUtilsUnit function test_DifferentBytesArrayOrdering() public { // Descending order and duplicate element bytes arrays should return false bytes memory descendingBytesArray = abi.encodePacked( - bytes1(uint8(12)), bytes1(uint8(11)), bytes1(uint8(10)), bytes1(uint8(9)), bytes1(uint8(8)), bytes1(uint8(7)), bytes1(uint8(6)), bytes1(uint8(5)) + bytes1(uint8(12)), + bytes1(uint8(11)), + bytes1(uint8(10)), + bytes1(uint8(9)), + bytes1(uint8(8)), + bytes1(uint8(7)), + bytes1(uint8(6)), + bytes1(uint8(5)) ); assertFalse(bitmapUtilsWrapper.isArrayStrictlyAscendingOrdered(descendingBytesArray)); bytes memory duplicateBytesArray = abi.encodePacked( - bytes1(uint8(5)), bytes1(uint8(5)), bytes1(uint8(5)), bytes1(uint8(5)), bytes1(uint8(5)), bytes1(uint8(5)), bytes1(uint8(5)), bytes1(uint8(5)) + bytes1(uint8(5)), + bytes1(uint8(5)), + bytes1(uint8(5)), + bytes1(uint8(5)), + bytes1(uint8(5)), + bytes1(uint8(5)), + bytes1(uint8(5)), + bytes1(uint8(5)) ); assertFalse(bitmapUtilsWrapper.isArrayStrictlyAscendingOrdered(duplicateBytesArray)); // Strictly ascending returns true bytes memory ascendingBytesArray = abi.encodePacked( - bytes1(uint8(5)), bytes1(uint8(6)), bytes1(uint8(7)), bytes1(uint8(8)), bytes1(uint8(9)), bytes1(uint8(10)), bytes1(uint8(11)), bytes1(uint8(12)) + bytes1(uint8(5)), + bytes1(uint8(6)), + bytes1(uint8(7)), + bytes1(uint8(8)), + bytes1(uint8(9)), + bytes1(uint8(10)), + bytes1(uint8(11)), + bytes1(uint8(12)) ); assertTrue(bitmapUtilsWrapper.isArrayStrictlyAscendingOrdered(ascendingBytesArray)); // Empty bytes array and single element bytes array returns true diff --git a/test/unit/ECDSAStakeRegistryEqualWeightUnit.t.sol b/test/unit/ECDSAStakeRegistryEqualWeightUnit.t.sol index 0008da7f..2878e67d 100644 --- a/test/unit/ECDSAStakeRegistryEqualWeightUnit.t.sol +++ b/test/unit/ECDSAStakeRegistryEqualWeightUnit.t.sol @@ -2,89 +2,60 @@ pragma solidity ^0.8.27; import {ISignatureUtils} from "eigenlayer-contracts/src/contracts/interfaces/ISignatureUtils.sol"; -import {IDelegationManager} from "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; +import {IDelegationManager} from + "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; import {IStrategy} from "eigenlayer-contracts/src/contracts/interfaces/IStrategy.sol"; -import {ECDSAStakeRegistryEventsAndErrors, Quorum, StrategyParams} from "../../src/interfaces/IECDSAStakeRegistryEventsAndErrors.sol"; +import { + ECDSAStakeRegistryEventsAndErrors, + Quorum, + StrategyParams +} from "../../src/interfaces/IECDSAStakeRegistryEventsAndErrors.sol"; import {ECDSAStakeRegistrySetup} from "./ECDSAStakeRegistryUnit.t.sol"; -import {ECDSAStakeRegistryEqualWeight} from "../../src/unaudited/examples/ECDSAStakeRegistryEqualWeight.sol"; +import {ECDSAStakeRegistryEqualWeight} from + "../../src/unaudited/examples/ECDSAStakeRegistryEqualWeight.sol"; contract EqualWeightECDSARegistry is ECDSAStakeRegistrySetup { ECDSAStakeRegistryEqualWeight internal fixedWeightRegistry; function setUp() public virtual override { super.setUp(); - fixedWeightRegistry = new ECDSAStakeRegistryEqualWeight( - IDelegationManager(address(mockDelegationManager)) - ); + fixedWeightRegistry = + new ECDSAStakeRegistryEqualWeight(IDelegationManager(address(mockDelegationManager))); IStrategy mockStrategy = IStrategy(address(0x1234)); Quorum memory quorum = Quorum({strategies: new StrategyParams[](1)}); - quorum.strategies[0] = StrategyParams({ - strategy: mockStrategy, - multiplier: 10000 - }); - fixedWeightRegistry.initialize( - address(mockServiceManager), - 100, - quorum - ); + quorum.strategies[0] = StrategyParams({strategy: mockStrategy, multiplier: 10_000}); + fixedWeightRegistry.initialize(address(mockServiceManager), 100, quorum); fixedWeightRegistry.permitOperator(operator1); fixedWeightRegistry.permitOperator(operator2); ISignatureUtils.SignatureWithSaltAndExpiry memory operatorSignature; vm.prank(operator1); - fixedWeightRegistry.registerOperatorWithSignature( - operatorSignature, - operator1 - ); + fixedWeightRegistry.registerOperatorWithSignature(operatorSignature, operator1); vm.prank(operator2); - fixedWeightRegistry.registerOperatorWithSignature( - operatorSignature, - operator2 - ); + fixedWeightRegistry.registerOperatorWithSignature(operatorSignature, operator2); } function test_FixedStakeUpdates() public { - assertEq( - fixedWeightRegistry.getLastCheckpointOperatorWeight(operator1), - 1 - ); - assertEq( - fixedWeightRegistry.getLastCheckpointOperatorWeight(operator2), - 1 - ); + assertEq(fixedWeightRegistry.getLastCheckpointOperatorWeight(operator1), 1); + assertEq(fixedWeightRegistry.getLastCheckpointOperatorWeight(operator2), 1); assertEq(fixedWeightRegistry.getLastCheckpointTotalWeight(), 2); vm.roll(block.number + 1); vm.prank(operator1); fixedWeightRegistry.deregisterOperator(); - assertEq( - fixedWeightRegistry.getLastCheckpointOperatorWeight(operator1), - 0 - ); - assertEq( - fixedWeightRegistry.getLastCheckpointOperatorWeight(operator2), - 1 - ); + assertEq(fixedWeightRegistry.getLastCheckpointOperatorWeight(operator1), 0); + assertEq(fixedWeightRegistry.getLastCheckpointOperatorWeight(operator2), 1); assertEq(fixedWeightRegistry.getLastCheckpointTotalWeight(), 1); vm.roll(block.number + 1); ISignatureUtils.SignatureWithSaltAndExpiry memory operatorSignature; vm.prank(operator1); - fixedWeightRegistry.registerOperatorWithSignature( - operatorSignature, - operator1 - ); + fixedWeightRegistry.registerOperatorWithSignature(operatorSignature, operator1); - assertEq( - fixedWeightRegistry.getLastCheckpointOperatorWeight(operator1), - 1 - ); - assertEq( - fixedWeightRegistry.getLastCheckpointOperatorWeight(operator2), - 1 - ); + assertEq(fixedWeightRegistry.getLastCheckpointOperatorWeight(operator1), 1); + assertEq(fixedWeightRegistry.getLastCheckpointOperatorWeight(operator2), 1); assertEq(fixedWeightRegistry.getLastCheckpointTotalWeight(), 2); vm.roll(block.number + 1); @@ -93,14 +64,8 @@ contract EqualWeightECDSARegistry is ECDSAStakeRegistrySetup { operators[1] = operator2; fixedWeightRegistry.updateOperators(operators); - assertEq( - fixedWeightRegistry.getLastCheckpointOperatorWeight(operator1), - 1 - ); - assertEq( - fixedWeightRegistry.getLastCheckpointOperatorWeight(operator2), - 1 - ); + assertEq(fixedWeightRegistry.getLastCheckpointOperatorWeight(operator1), 1); + assertEq(fixedWeightRegistry.getLastCheckpointOperatorWeight(operator2), 1); assertEq(fixedWeightRegistry.getLastCheckpointTotalWeight(), 2); } } diff --git a/test/unit/ECDSAStakeRegistryPermissionedUnit.t.sol b/test/unit/ECDSAStakeRegistryPermissionedUnit.t.sol index 8205034d..ced14a41 100644 --- a/test/unit/ECDSAStakeRegistryPermissionedUnit.t.sol +++ b/test/unit/ECDSAStakeRegistryPermissionedUnit.t.sol @@ -2,46 +2,38 @@ pragma solidity ^0.8.27; import {ISignatureUtils} from "eigenlayer-contracts/src/contracts/interfaces/ISignatureUtils.sol"; -import {IDelegationManager} from "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; +import {IDelegationManager} from + "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; import {IStrategy} from "eigenlayer-contracts/src/contracts/interfaces/IStrategy.sol"; -import {ECDSAStakeRegistryEventsAndErrors, Quorum, StrategyParams} from "../../src/interfaces/IECDSAStakeRegistryEventsAndErrors.sol"; +import { + ECDSAStakeRegistryEventsAndErrors, + Quorum, + StrategyParams +} from "../../src/interfaces/IECDSAStakeRegistryEventsAndErrors.sol"; import {ECDSAStakeRegistrySetup} from "./ECDSAStakeRegistryUnit.t.sol"; -import {ECDSAStakeRegistryPermissioned} from "../../src/unaudited/examples/ECDSAStakeRegistryPermissioned.sol"; +import {ECDSAStakeRegistryPermissioned} from + "../../src/unaudited/examples/ECDSAStakeRegistryPermissioned.sol"; contract PermissionedECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { ECDSAStakeRegistryPermissioned internal permissionedRegistry; function setUp() public virtual override { super.setUp(); - permissionedRegistry = new ECDSAStakeRegistryPermissioned( - IDelegationManager(address(mockDelegationManager)) - ); + permissionedRegistry = + new ECDSAStakeRegistryPermissioned(IDelegationManager(address(mockDelegationManager))); IStrategy mockStrategy = IStrategy(address(0x1234)); Quorum memory quorum = Quorum({strategies: new StrategyParams[](1)}); - quorum.strategies[0] = StrategyParams({ - strategy: mockStrategy, - multiplier: 10000 - }); - permissionedRegistry.initialize( - address(mockServiceManager), - 100, - quorum - ); + quorum.strategies[0] = StrategyParams({strategy: mockStrategy, multiplier: 10_000}); + permissionedRegistry.initialize(address(mockServiceManager), 100, quorum); permissionedRegistry.permitOperator(operator1); permissionedRegistry.permitOperator(operator2); ISignatureUtils.SignatureWithSaltAndExpiry memory operatorSignature; vm.prank(operator1); - permissionedRegistry.registerOperatorWithSignature( - operatorSignature, - operator1 - ); + permissionedRegistry.registerOperatorWithSignature(operatorSignature, operator1); vm.prank(operator2); - permissionedRegistry.registerOperatorWithSignature( - operatorSignature, - operator1 - ); + permissionedRegistry.registerOperatorWithSignature(operatorSignature, operator1); } function test_RevertsWhen_NotOwner_PermitOperator() public { @@ -96,15 +88,10 @@ contract PermissionedECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { ISignatureUtils.SignatureWithSaltAndExpiry memory operatorSignature; vm.expectRevert( - abi.encodeWithSelector( - ECDSAStakeRegistryPermissioned.OperatorNotAllowlisted.selector - ) + abi.encodeWithSelector(ECDSAStakeRegistryPermissioned.OperatorNotAllowlisted.selector) ); vm.prank(operator3); - permissionedRegistry.registerOperatorWithSignature( - operatorSignature, - operator3 - ); + permissionedRegistry.registerOperatorWithSignature(operatorSignature, operator3); } function test_WhenAllowlisted_RegisterOperatorWithSig() public { @@ -112,10 +99,7 @@ contract PermissionedECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { permissionedRegistry.permitOperator(operator3); ISignatureUtils.SignatureWithSaltAndExpiry memory operatorSignature; vm.prank(operator3); - permissionedRegistry.registerOperatorWithSignature( - operatorSignature, - operator3 - ); + permissionedRegistry.registerOperatorWithSignature(operatorSignature, operator3); } function test_DeregisterOperator() public { @@ -123,10 +107,7 @@ contract PermissionedECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { permissionedRegistry.permitOperator(operator3); ISignatureUtils.SignatureWithSaltAndExpiry memory operatorSignature; vm.prank(operator3); - permissionedRegistry.registerOperatorWithSignature( - operatorSignature, - operator3 - ); + permissionedRegistry.registerOperatorWithSignature(operatorSignature, operator3); vm.prank(operator3); permissionedRegistry.deregisterOperator(); diff --git a/test/unit/ECDSAStakeRegistryUnit.t.sol b/test/unit/ECDSAStakeRegistryUnit.t.sol index e1d7de77..89a4dc98 100644 --- a/test/unit/ECDSAStakeRegistryUnit.t.sol +++ b/test/unit/ECDSAStakeRegistryUnit.t.sol @@ -4,15 +4,22 @@ pragma solidity ^0.8.27; import {Test, console} from "forge-std/Test.sol"; import {ISignatureUtils} from "eigenlayer-contracts/src/contracts/interfaces/ISignatureUtils.sol"; -import {IDelegationManager} from "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; +import {IDelegationManager} from + "eigenlayer-contracts/src/contracts/interfaces/IDelegationManager.sol"; import {IStrategy} from "eigenlayer-contracts/src/contracts/interfaces/IStrategy.sol"; import {ECDSAStakeRegistry} from "../../src/unaudited/ECDSAStakeRegistry.sol"; -import {ECDSAStakeRegistryEventsAndErrors, Quorum, StrategyParams} from "../../src/interfaces/IECDSAStakeRegistryEventsAndErrors.sol"; +import { + ECDSAStakeRegistryEventsAndErrors, + Quorum, + StrategyParams +} from "../../src/interfaces/IECDSAStakeRegistryEventsAndErrors.sol"; contract MockServiceManager { // solhint-disable-next-line - function deregisterOperatorFromAVS(address) external {} + function deregisterOperatorFromAVS( + address + ) external {} function registerOperatorToAVS( address, @@ -58,13 +65,8 @@ contract ECDSAStakeRegistrySetup is Test, ECDSAStakeRegistryEventsAndErrors { mockServiceManager = new MockServiceManager(); IStrategy mockStrategy = IStrategy(address(0x1234)); Quorum memory quorum = Quorum({strategies: new StrategyParams[](1)}); - quorum.strategies[0] = StrategyParams({ - strategy: mockStrategy, - multiplier: 10_000 - }); - registry = new ECDSAStakeRegistry( - IDelegationManager(address(mockDelegationManager)) - ); + quorum.strategies[0] = StrategyParams({strategy: mockStrategy, multiplier: 10_000}); + registry = new ECDSAStakeRegistry(IDelegationManager(address(mockDelegationManager))); registry.initialize(address(mockServiceManager), 100, quorum); ISignatureUtils.SignatureWithSaltAndExpiry memory operatorSignature; vm.prank(operator1); @@ -81,10 +83,7 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { Quorum memory oldQuorum = registry.quorum(); Quorum memory newQuorum = Quorum({strategies: new StrategyParams[](1)}); - newQuorum.strategies[0] = StrategyParams({ - strategy: mockStrategy, - multiplier: 10_000 - }); + newQuorum.strategies[0] = StrategyParams({strategy: mockStrategy, multiplier: 10_000}); address[] memory operators = new address[](2); operators[0] = operator1; operators[1] = operator2; @@ -96,9 +95,7 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { } function test_RevertsWhen_InvalidQuorum_UpdateQuourmConfig() public { - Quorum memory invalidQuorum = Quorum({ - strategies: new StrategyParams[](1) - }); + Quorum memory invalidQuorum = Quorum({strategies: new StrategyParams[](1)}); invalidQuorum.strategies[0] = StrategyParams({ /// TODO: Make mock strategy strategy: IStrategy(address(420)), @@ -108,20 +105,14 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { operators[0] = operator1; operators[1] = operator2; - vm.expectRevert( - ECDSAStakeRegistryEventsAndErrors.InvalidQuorum.selector - ); + vm.expectRevert(ECDSAStakeRegistryEventsAndErrors.InvalidQuorum.selector); registry.updateQuorumConfig(invalidQuorum, operators); } function test_RevertsWhen_NotOwner_UpdateQuorumConfig() public { - Quorum memory validQuorum = Quorum({ - strategies: new StrategyParams[](1) - }); - validQuorum.strategies[0] = StrategyParams({ - strategy: IStrategy(address(420)), - multiplier: 10_000 - }); + Quorum memory validQuorum = Quorum({strategies: new StrategyParams[](1)}); + validQuorum.strategies[0] = + StrategyParams({strategy: IStrategy(address(420)), multiplier: 10_000}); address[] memory operators = new address[](2); operators[0] = operator1; @@ -145,60 +136,42 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { } function test_RevertSWhen_Duplicate_UpdateQuorumConfig() public { - Quorum memory invalidQuorum = Quorum({ - strategies: new StrategyParams[](2) - }); - invalidQuorum.strategies[0] = StrategyParams({ - strategy: IStrategy(address(420)), - multiplier: 5000 - }); + Quorum memory invalidQuorum = Quorum({strategies: new StrategyParams[](2)}); + invalidQuorum.strategies[0] = + StrategyParams({strategy: IStrategy(address(420)), multiplier: 5000}); address[] memory operators = new address[](2); operators[0] = operator1; operators[1] = operator2; - invalidQuorum.strategies[1] = StrategyParams({ - strategy: IStrategy(address(420)), - multiplier: 5000 - }); + invalidQuorum.strategies[1] = + StrategyParams({strategy: IStrategy(address(420)), multiplier: 5000}); vm.expectRevert(ECDSAStakeRegistryEventsAndErrors.NotSorted.selector); registry.updateQuorumConfig(invalidQuorum, operators); } function test_RevertSWhen_NotSorted_UpdateQuorumConfig() public { - Quorum memory invalidQuorum = Quorum({ - strategies: new StrategyParams[](2) - }); - invalidQuorum.strategies[0] = StrategyParams({ - strategy: IStrategy(address(420)), - multiplier: 5000 - }); + Quorum memory invalidQuorum = Quorum({strategies: new StrategyParams[](2)}); + invalidQuorum.strategies[0] = + StrategyParams({strategy: IStrategy(address(420)), multiplier: 5000}); address[] memory operators = new address[](2); operators[0] = operator1; operators[1] = operator2; - invalidQuorum.strategies[1] = StrategyParams({ - strategy: IStrategy(address(419)), - multiplier: 5000 - }); + invalidQuorum.strategies[1] = + StrategyParams({strategy: IStrategy(address(419)), multiplier: 5000}); vm.expectRevert(ECDSAStakeRegistryEventsAndErrors.NotSorted.selector); registry.updateQuorumConfig(invalidQuorum, operators); } function test_RevertSWhen_OverMultiplierTotal_UpdateQuorumConfig() public { - Quorum memory invalidQuorum = Quorum({ - strategies: new StrategyParams[](1) - }); - invalidQuorum.strategies[0] = StrategyParams({ - strategy: IStrategy(address(420)), - multiplier: 10_001 - }); + Quorum memory invalidQuorum = Quorum({strategies: new StrategyParams[](1)}); + invalidQuorum.strategies[0] = + StrategyParams({strategy: IStrategy(address(420)), multiplier: 10_001}); address[] memory operators = new address[](2); operators[0] = operator1; operators[1] = operator2; - vm.expectRevert( - ECDSAStakeRegistryEventsAndErrors.InvalidQuorum.selector - ); + vm.expectRevert(ECDSAStakeRegistryEventsAndErrors.InvalidQuorum.selector); registry.updateQuorumConfig(invalidQuorum, operators); } @@ -211,23 +184,17 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { assertEq(registry.getLastCheckpointOperatorWeight(operator3), 1000); } - function test_RevertsWhen_AlreadyRegistered_RegisterOperatorWithSignature() - public - { + function test_RevertsWhen_AlreadyRegistered_RegisterOperatorWithSignature() public { assertEq(registry.getLastCheckpointOperatorWeight(operator1), 1000); assertEq(registry.getLastCheckpointTotalWeight(), 2000); ISignatureUtils.SignatureWithSaltAndExpiry memory signature; - vm.expectRevert( - ECDSAStakeRegistryEventsAndErrors.OperatorAlreadyRegistered.selector - ); + vm.expectRevert(ECDSAStakeRegistryEventsAndErrors.OperatorAlreadyRegistered.selector); vm.prank(operator1); registry.registerOperatorWithSignature(signature, operator1); } - function test_RevertsWhen_SignatureIsInvalid_RegisterOperatorWithSignature() - public - { + function test_RevertsWhen_SignatureIsInvalid_RegisterOperatorWithSignature() public { bytes memory signatureData; vm.mockCall( address(mockServiceManager), @@ -258,9 +225,7 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { function test_RevertsWhen_NotOperator_DeregisterOperator() public { address notOperator = address(0x2); vm.prank(notOperator); - vm.expectRevert( - ECDSAStakeRegistryEventsAndErrors.OperatorNotRegistered.selector - ); + vm.expectRevert(ECDSAStakeRegistryEventsAndErrors.OperatorNotRegistered.selector); registry.deregisterOperator(); } @@ -284,9 +249,7 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { operators[0] = operator1; registry.updateOperators(operators); - uint256 updatedWeight = registry.getLastCheckpointOperatorWeight( - operator1 - ); + uint256 updatedWeight = registry.getLastCheckpointOperatorWeight(operator1); assertEq(updatedWeight, 1000); } @@ -318,12 +281,8 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { registry.updateOperators(operators); - uint256 updatedWeight1 = registry.getLastCheckpointOperatorWeight( - operator1 - ); - uint256 updatedWeight2 = registry.getLastCheckpointOperatorWeight( - operator2 - ); + uint256 updatedWeight1 = registry.getLastCheckpointOperatorWeight(operator1); + uint256 updatedWeight2 = registry.getLastCheckpointOperatorWeight(operator2); assertEq(updatedWeight1, 1000); assertEq(updatedWeight2, 1000); } @@ -335,9 +294,7 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { registry.updateOperators(operators); - uint256 updatedWeight = registry.getLastCheckpointOperatorWeight( - operator1 - ); + uint256 updatedWeight = registry.getLastCheckpointOperatorWeight(operator1); assertEq(updatedWeight, 1000); } @@ -346,14 +303,8 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { IStrategy mockStrategy2 = IStrategy(address(421)); Quorum memory quorum = Quorum({strategies: new StrategyParams[](2)}); - quorum.strategies[0] = StrategyParams({ - strategy: mockStrategy, - multiplier: 5000 - }); - quorum.strategies[1] = StrategyParams({ - strategy: mockStrategy2, - multiplier: 5000 - }); + quorum.strategies[0] = StrategyParams({strategy: mockStrategy, multiplier: 5000}); + quorum.strategies[1] = StrategyParams({strategy: mockStrategy2, multiplier: 5000}); address[] memory operators = new address[](2); operators[0] = operator1; @@ -370,21 +321,15 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { vm.mockCall( address(mockDelegationManager), abi.encodeWithSelector( - MockDelegationManager.getOperatorShares.selector, - operator1, - strategies + MockDelegationManager.getOperatorShares.selector, operator1, strategies ), abi.encode(shares) ); registry.updateOperators(operators); - uint256 updatedWeight1 = registry.getLastCheckpointOperatorWeight( - operator1 - ); - uint256 updatedWeight2 = registry.getLastCheckpointOperatorWeight( - operator2 - ); + uint256 updatedWeight1 = registry.getLastCheckpointOperatorWeight(operator1); + uint256 updatedWeight2 = registry.getLastCheckpointOperatorWeight(operator2); assertEq(updatedWeight1, 525); assertEq(updatedWeight2, 1000); vm.roll(block.number + 1); @@ -465,10 +410,7 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { (v, r, s) = vm.sign(operator2Pk, msgHash); signatures[1] = abi.encodePacked(r, s, v); - registry.isValidSignature( - msgHash, - abi.encode(signers, signatures, block.number - 1) - ); + registry.isValidSignature(msgHash, abi.encode(signers, signatures, block.number - 1)); } function test_RevertsWhen_LengthMismatch_CheckSignatures() public { @@ -479,13 +421,8 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { (uint8 v, bytes32 r, bytes32 s) = vm.sign(operator1Pk, msgHash); signatures[0] = abi.encode(v, r, s); - vm.expectRevert( - ECDSAStakeRegistryEventsAndErrors.LengthMismatch.selector - ); - registry.isValidSignature( - msgHash, - abi.encode(signers, signatures, block.number - 1) - ); + vm.expectRevert(ECDSAStakeRegistryEventsAndErrors.LengthMismatch.selector); + registry.isValidSignature(msgHash, abi.encode(signers, signatures, block.number - 1)); } function test_RevertsWhen_InvalidLength_CheckSignatures() public { @@ -493,13 +430,8 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { address[] memory signers = new address[](0); bytes[] memory signatures = new bytes[](0); - vm.expectRevert( - ECDSAStakeRegistryEventsAndErrors.InvalidLength.selector - ); - registry.isValidSignature( - dataHash, - abi.encode(signers, signatures, block.number - 1) - ); + vm.expectRevert(ECDSAStakeRegistryEventsAndErrors.InvalidLength.selector); + registry.isValidSignature(dataHash, abi.encode(signers, signatures, block.number - 1)); } function test_RevertsWhen_NotSorted_CheckSignatures() public { @@ -514,10 +446,7 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { signatures[0] = abi.encodePacked(r, s, v); vm.expectRevert(ECDSAStakeRegistryEventsAndErrors.NotSorted.selector); - registry.isValidSignature( - msgHash, - abi.encode(signers, signatures, block.number - 1) - ); + registry.isValidSignature(msgHash, abi.encode(signers, signatures, block.number - 1)); } function test_RevertsWhen_Duplicates_CheckSignatures() public { @@ -535,10 +464,7 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { signatures[1] = abi.encodePacked(r, s, v); vm.expectRevert(ECDSAStakeRegistryEventsAndErrors.NotSorted.selector); - registry.isValidSignature( - msgHash, - abi.encode(signers, signatures, block.number - 1) - ); + registry.isValidSignature(msgHash, abi.encode(signers, signatures, block.number - 1)); } function test_RevetsWhen_InvalidSignature_CheckSignatures() public { @@ -548,13 +474,8 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { bytes[] memory signatures = new bytes[](1); signatures[0] = "invalid-signature"; - vm.expectRevert( - ECDSAStakeRegistryEventsAndErrors.InvalidSignature.selector - ); - registry.isValidSignature( - dataHash, - abi.encode(signers, signatures, block.number - 1) - ); + vm.expectRevert(ECDSAStakeRegistryEventsAndErrors.InvalidSignature.selector); + registry.isValidSignature(dataHash, abi.encode(signers, signatures, block.number - 1)); } function test_RevertsWhen_InsufficientSignedStake_CheckSignatures() public { @@ -576,19 +497,13 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { vm.mockCall( address(registry), abi.encodeWithSelector( - ECDSAStakeRegistry.getLastCheckpointOperatorWeight.selector, - operator1 + ECDSAStakeRegistry.getLastCheckpointOperatorWeight.selector, operator1 ), abi.encode(50) ); - vm.expectRevert( - ECDSAStakeRegistryEventsAndErrors.InsufficientSignedStake.selector - ); - registry.isValidSignature( - msgHash, - abi.encode(signers, signatures, block.number - 1) - ); + vm.expectRevert(ECDSAStakeRegistryEventsAndErrors.InsufficientSignedStake.selector); + registry.isValidSignature(msgHash, abi.encode(signers, signatures, block.number - 1)); } function test_RevertsWhen_LengthMismatch_CheckSignaturesAtBlock() public { @@ -599,13 +514,8 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { signers[1] = operator2; bytes[] memory signatures = new bytes[](1); - vm.expectRevert( - ECDSAStakeRegistryEventsAndErrors.LengthMismatch.selector - ); - registry.isValidSignature( - dataHash, - abi.encode(signers, signatures, referenceBlock) - ); + vm.expectRevert(ECDSAStakeRegistryEventsAndErrors.LengthMismatch.selector); + registry.isValidSignature(dataHash, abi.encode(signers, signatures, referenceBlock)); } function test_RevertsWhen_InvalidLength_CheckSignaturesAtBlock() public { @@ -614,13 +524,8 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { address[] memory signers = new address[](0); bytes[] memory signatures = new bytes[](0); - vm.expectRevert( - ECDSAStakeRegistryEventsAndErrors.InvalidLength.selector - ); - registry.isValidSignature( - dataHash, - abi.encode(signers, signatures, referenceBlock) - ); + vm.expectRevert(ECDSAStakeRegistryEventsAndErrors.InvalidLength.selector); + registry.isValidSignature(dataHash, abi.encode(signers, signatures, referenceBlock)); } function test_RevertsWhen_NotSorted_CheckSignaturesAtBlock() public { @@ -637,15 +542,10 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { signatures[0] = abi.encodePacked(r, s, v); vm.expectRevert(ECDSAStakeRegistryEventsAndErrors.NotSorted.selector); - registry.isValidSignature( - msgHash, - abi.encode(signers, signatures, referenceBlock) - ); + registry.isValidSignature(msgHash, abi.encode(signers, signatures, referenceBlock)); } - function test_RevetsWhen_InsufficientSignedStake_CheckSignaturesAtBlock() - public - { + function test_RevetsWhen_InsufficientSignedStake_CheckSignaturesAtBlock() public { uint32 referenceBlock = 123; msgHash = keccak256("data"); signers = new address[](2); @@ -665,20 +565,13 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { vm.mockCall( address(registry), abi.encodeWithSelector( - ECDSAStakeRegistry.getOperatorWeightAtBlock.selector, - operator1, - referenceBlock + ECDSAStakeRegistry.getOperatorWeightAtBlock.selector, operator1, referenceBlock ), abi.encode(50) ); - vm.expectRevert( - ECDSAStakeRegistryEventsAndErrors.InsufficientSignedStake.selector - ); - registry.isValidSignature( - msgHash, - abi.encode(signers, signatures, referenceBlock) - ); + vm.expectRevert(ECDSAStakeRegistryEventsAndErrors.InsufficientSignedStake.selector); + registry.isValidSignature(msgHash, abi.encode(signers, signatures, referenceBlock)); } function test_Gas_UpdateOperators() public { @@ -694,10 +587,7 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { for (uint256 i; i < operators.length; i++) { operators[i] = address(uint160(i)); vm.prank(operators[i]); - registry.registerOperatorWithSignature( - operatorSignature, - operators[i] - ); + registry.registerOperatorWithSignature(operatorSignature, operators[i]); } vm.resumeGasMetering(); registry.updateOperators(operators); @@ -723,10 +613,7 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { for (uint256 i = 1; i < operators.length + 1; i++) { operators[i - 1] = address(vm.addr(i)); vm.prank(operators[i - 1]); - registry.registerOperatorWithSignature( - operatorSignature, - operators[i - 1] - ); + registry.registerOperatorWithSignature(operatorSignature, operators[i - 1]); (v, r, s) = vm.sign(i, msgHash); signatures[i - 1] = abi.encodePacked(r, s, v); } @@ -735,10 +622,7 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { vm.roll(block.number + 1); vm.resumeGasMetering(); - registry.isValidSignature( - msgHash, - abi.encode(operators, signatures, block.number - 1) - ); + registry.isValidSignature(msgHash, abi.encode(operators, signatures, block.number - 1)); emit log_named_uint("Gas consumed", before - gasleft()); } @@ -759,9 +643,7 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { registry.registerOperatorWithSignature(operatorSignature, signer); // Verify that the signing key has been successfully registered for the operator - address registeredSigningKey = registry.getLastestOperatorSigningKey( - operator - ); + address registeredSigningKey = registry.getLastestOperatorSigningKey(operator); assertEq( registeredSigningKey, signer, @@ -783,15 +665,11 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { registry.updateOperatorSigningKey(address(420)); // Verify that the signing key has been successfully registered for the operator - address registeredSigningKey = registry.getLastestOperatorSigningKey( - operator - ); + address registeredSigningKey = registry.getLastestOperatorSigningKey(operator); vm.roll(block.number + 1); - registeredSigningKey = registry.getOperatorSigningKeyAtBlock( - operator, - uint32(block.number - 1) - ); + registeredSigningKey = + registry.getOperatorSigningKeyAtBlock(operator, uint32(block.number - 1)); assertEq( registeredSigningKey, address(420), @@ -820,10 +698,7 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { signatures[0] = abi.encodePacked(r, s, v); // Check signatures using the registered signing key - registry.isValidSignature( - dataHash, - abi.encode(operators, signatures, block.number - 1) - ); + registry.isValidSignature(dataHash, abi.encode(operators, signatures, block.number - 1)); } function test_WhenUsingSigningKey_CheckSignaturesAtBlock() public { @@ -835,10 +710,7 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { // Register operator with the initial signing key vm.prank(operator); - registry.registerOperatorWithSignature( - operatorSignature, - initialSigningKey - ); + registry.registerOperatorWithSignature(operatorSignature, initialSigningKey); vm.roll(block.number + 1); // Prepare data for signature with initial signing key @@ -852,10 +724,7 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { signatures[0] = abi.encodePacked(r, s, v); // Check signatures using the initial registered signing key - registry.isValidSignature( - dataHash, - abi.encode(operators, signatures, block.number - 1) - ); + registry.isValidSignature(dataHash, abi.encode(operators, signatures, block.number - 1)); // Increase block number vm.roll(block.number + 10); @@ -870,10 +739,7 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { signatures[0] = abi.encodePacked(r, s, v); // Check signatures using the updated registered signing key - registry.isValidSignature( - dataHash, - abi.encode(operators, signatures, block.number - 1) - ); + registry.isValidSignature(dataHash, abi.encode(operators, signatures, block.number - 1)); } function test_WhenUsingPriorSigningKey_CheckSignaturesAtBlock() public { @@ -885,10 +751,7 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { // Register operator with the initial signing key vm.prank(operator); - registry.registerOperatorWithSignature( - operatorSignature, - initialSigningKey - ); + registry.registerOperatorWithSignature(operatorSignature, initialSigningKey); vm.roll(block.number + 1); // Prepare data for signature with initial signing key @@ -909,10 +772,7 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { registry.updateOperatorSigningKey(updatedSigningKey); // Check signatures using the initial registered signing key at the previous block - registry.isValidSignature( - dataHash, - abi.encode(operators, signatures, block.number - 10) - ); + registry.isValidSignature(dataHash, abi.encode(operators, signatures, block.number - 10)); } function test_RevertsWhen_SigningCurrentBlock_IsValidSignature() public { @@ -929,15 +789,10 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { signatures[0] = signature; vm.expectRevert(abi.encodeWithSignature("InvalidReferenceBlock()")); - registry.isValidSignature( - dataHash, - abi.encode(operators, signatures, currentBlock) - ); + registry.isValidSignature(dataHash, abi.encode(operators, signatures, currentBlock)); } - function test_RevertsWhen_SigningKeyNotValidAtBlock_IsValidSignature() - public - { + function test_RevertsWhen_SigningKeyNotValidAtBlock_IsValidSignature() public { address operator = operator1; uint256 invalidSignerPk = signerPk + 1; address updatedSigningKey = address(vm.addr(invalidSignerPk)); @@ -958,20 +813,14 @@ contract ECDSAStakeRegistryTest is ECDSAStakeRegistrySetup { signatures[0] = signature; vm.expectRevert(abi.encodeWithSignature("InvalidSignature()")); - registry.isValidSignature( - dataHash, - abi.encode(operators, signatures, referenceBlock) - ); + registry.isValidSignature(dataHash, abi.encode(operators, signatures, referenceBlock)); } function _sort( address[] memory operators, bytes[] memory signatures ) internal pure returns (address[] memory, bytes[] memory) { - require( - operators.length == signatures.length, - "Operators and signatures length mismatch" - ); + require(operators.length == signatures.length, "Operators and signatures length mismatch"); uint256 length = operators.length; for (uint256 i = 0; i < length - 1; i++) { diff --git a/test/unit/EjectionManagerUnit.t.sol b/test/unit/EjectionManagerUnit.t.sol index a95366f7..2cfa859e 100644 --- a/test/unit/EjectionManagerUnit.t.sol +++ b/test/unit/EjectionManagerUnit.t.sol @@ -8,9 +8,10 @@ import {IEjectionManager, IEjectionManagerErrors} from "../../src/interfaces/IEj import "../utils/MockAVSDeployer.sol"; contract EjectionManagerUnitTests is MockAVSDeployer { - event EjectorUpdated(address ejector, bool status); - event QuorumEjectionParamsSet(uint8 quorumNumber, uint32 rateLimitWindow, uint16 ejectableStakePercent); + event QuorumEjectionParamsSet( + uint8 quorumNumber, uint32 rateLimitWindow, uint16 ejectableStakePercent + ); event OperatorEjected(bytes32 operatorId, uint8 quorumNumber); event FailedOperatorEjection(bytes32 operatorId, uint8 quorumNumber, bytes err); @@ -22,24 +23,24 @@ contract EjectionManagerUnitTests is MockAVSDeployer { uint32 public ratelimitWindow = 1 days; uint16 public ejectableStakePercent = 1000; - function setUp() virtual public { - for(uint8 i = 0; i < numQuorums; i++) { - quorumEjectionParams.push(IEjectionManager.QuorumEjectionParams({ - rateLimitWindow: ratelimitWindow, - ejectableStakePercent: ejectableStakePercent - })); + function setUp() public virtual { + for (uint8 i = 0; i < numQuorums; i++) { + quorumEjectionParams.push( + IEjectionManager.QuorumEjectionParams({ + rateLimitWindow: ratelimitWindow, + ejectableStakePercent: ejectableStakePercent + }) + ); } defaultMaxOperatorCount = 200; _deployMockEigenLayerAndAVS(); - ejectionManager = EjectionManager(address( - new TransparentUpgradeableProxy( - address(emptyContract), - address(proxyAdmin), - "" + ejectionManager = EjectionManager( + address( + new TransparentUpgradeableProxy(address(emptyContract), address(proxyAdmin), "") ) - )); + ); ejectionManagerImplementation = new EjectionManager(registryCoordinator, stakeRegistry); @@ -73,15 +74,19 @@ contract EjectionManagerUnitTests is MockAVSDeployer { bytes32[][] memory operatorIds = new bytes32[][](numQuorums); for (uint8 i = 0; i < numQuorums; i++) { operatorIds[i] = new bytes32[](operatorsToEject); - for (uint j = 0; j < operatorsToEject; j++) { - operatorIds[i][j] = registryCoordinator.getOperatorId(_incrementAddress(defaultOperator, j)); + for (uint256 j = 0; j < operatorsToEject; j++) { + operatorIds[i][j] = + registryCoordinator.getOperatorId(_incrementAddress(defaultOperator, j)); } } - assertEq(uint8(registryCoordinator.getOperatorStatus(defaultOperator)), uint8(IRegistryCoordinator.OperatorStatus.REGISTERED)); + assertEq( + uint8(registryCoordinator.getOperatorStatus(defaultOperator)), + uint8(IRegistryCoordinator.OperatorStatus.REGISTERED) + ); - for(uint8 i = 0; i < numQuorums; i++) { - for(uint8 j = 0; j < operatorsToEject; j++) { + for (uint8 i = 0; i < numQuorums; i++) { + for (uint8 j = 0; j < operatorsToEject; j++) { cheats.expectEmit(true, true, true, true, address(ejectionManager)); emit OperatorEjected(operatorIds[i][j], i); } @@ -90,7 +95,10 @@ contract EjectionManagerUnitTests is MockAVSDeployer { cheats.prank(ejector); ejectionManager.ejectOperators(operatorIds); - assertEq(uint8(registryCoordinator.getOperatorStatus(defaultOperator)), uint8(IRegistryCoordinator.OperatorStatus.DEREGISTERED)); + assertEq( + uint8(registryCoordinator.getOperatorStatus(defaultOperator)), + uint8(IRegistryCoordinator.OperatorStatus.DEREGISTERED) + ); } function testEjectOperators_MultipleOperatorInsideRatelimit() public { @@ -102,17 +110,21 @@ contract EjectionManagerUnitTests is MockAVSDeployer { bytes32[][] memory operatorIds = new bytes32[][](numQuorums); for (uint8 i = 0; i < numQuorums; i++) { operatorIds[i] = new bytes32[](operatorsToEject); - for (uint j = 0; j < operatorsToEject; j++) { - operatorIds[i][j] = registryCoordinator.getOperatorId(_incrementAddress(defaultOperator, j)); + for (uint256 j = 0; j < operatorsToEject; j++) { + operatorIds[i][j] = + registryCoordinator.getOperatorId(_incrementAddress(defaultOperator, j)); } } - for(uint8 i = 0; i < operatorsToEject; i++) { - assertEq(uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), uint8(IRegistryCoordinator.OperatorStatus.REGISTERED)); + for (uint8 i = 0; i < operatorsToEject; i++) { + assertEq( + uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), + uint8(IRegistryCoordinator.OperatorStatus.REGISTERED) + ); } - for(uint8 i = 0; i < numQuorums; i++) { - for(uint8 j = 0; j < operatorsToEject; j++) { + for (uint8 i = 0; i < numQuorums; i++) { + for (uint8 j = 0; j < operatorsToEject; j++) { cheats.expectEmit(true, true, true, true, address(ejectionManager)); emit OperatorEjected(operatorIds[i][j], i); } @@ -121,8 +133,11 @@ contract EjectionManagerUnitTests is MockAVSDeployer { cheats.prank(ejector); ejectionManager.ejectOperators(operatorIds); - for(uint8 i = 0; i < operatorsToEject; i++) { - assertEq(uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), uint8(IRegistryCoordinator.OperatorStatus.DEREGISTERED)); + for (uint8 i = 0; i < operatorsToEject; i++) { + assertEq( + uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), + uint8(IRegistryCoordinator.OperatorStatus.DEREGISTERED) + ); } } @@ -136,17 +151,21 @@ contract EjectionManagerUnitTests is MockAVSDeployer { bytes32[][] memory operatorIds = new bytes32[][](numQuorums); for (uint8 i = 0; i < numQuorums; i++) { operatorIds[i] = new bytes32[](operatorsToEject); - for (uint j = 0; j < operatorsToEject; j++) { - operatorIds[i][j] = registryCoordinator.getOperatorId(_incrementAddress(defaultOperator, j)); + for (uint256 j = 0; j < operatorsToEject; j++) { + operatorIds[i][j] = + registryCoordinator.getOperatorId(_incrementAddress(defaultOperator, j)); } } - for(uint8 i = 0; i < operatorsToEject; i++) { - assertEq(uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), uint8(IRegistryCoordinator.OperatorStatus.REGISTERED)); + for (uint8 i = 0; i < operatorsToEject; i++) { + assertEq( + uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), + uint8(IRegistryCoordinator.OperatorStatus.REGISTERED) + ); } - for(uint8 i = 0; i < numQuorums; i++) { - for(uint8 j = 0; j < operatorsCanEject; j++) { + for (uint8 i = 0; i < numQuorums; i++) { + for (uint8 j = 0; j < operatorsCanEject; j++) { cheats.expectEmit(true, true, true, true, address(ejectionManager)); emit OperatorEjected(operatorIds[i][j], i); } @@ -155,12 +174,18 @@ contract EjectionManagerUnitTests is MockAVSDeployer { cheats.prank(ejector); ejectionManager.ejectOperators(operatorIds); - for(uint8 i = 0; i < operatorsCanEject; i++) { - assertEq(uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), uint8(IRegistryCoordinator.OperatorStatus.DEREGISTERED)); + for (uint8 i = 0; i < operatorsCanEject; i++) { + assertEq( + uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), + uint8(IRegistryCoordinator.OperatorStatus.DEREGISTERED) + ); } - for(uint8 i = operatorsCanEject; i < operatorsToEject; i++) { - assertEq(uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), uint8(IRegistryCoordinator.OperatorStatus.REGISTERED)); + for (uint8 i = operatorsCanEject; i < operatorsToEject; i++) { + assertEq( + uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), + uint8(IRegistryCoordinator.OperatorStatus.REGISTERED) + ); } } @@ -173,17 +198,21 @@ contract EjectionManagerUnitTests is MockAVSDeployer { bytes32[][] memory operatorIds = new bytes32[][](numQuorums); for (uint8 i = 0; i < numQuorums; i++) { operatorIds[i] = new bytes32[](operatorsToEject); - for (uint j = 0; j < operatorsToEject; j++) { - operatorIds[i][j] = registryCoordinator.getOperatorId(_incrementAddress(defaultOperator, j)); + for (uint256 j = 0; j < operatorsToEject; j++) { + operatorIds[i][j] = + registryCoordinator.getOperatorId(_incrementAddress(defaultOperator, j)); } } - for(uint8 i = 0; i < operatorsToEject; i++) { - assertEq(uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), uint8(IRegistryCoordinator.OperatorStatus.REGISTERED)); + for (uint8 i = 0; i < operatorsToEject; i++) { + assertEq( + uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), + uint8(IRegistryCoordinator.OperatorStatus.REGISTERED) + ); } - for(uint8 i = 0; i < numQuorums; i++) { - for(uint8 j = 0; j < operatorsToEject; j++) { + for (uint8 i = 0; i < numQuorums; i++) { + for (uint8 j = 0; j < operatorsToEject; j++) { cheats.expectEmit(true, true, true, true, address(ejectionManager)); emit OperatorEjected(operatorIds[i][j], i); } @@ -192,8 +221,11 @@ contract EjectionManagerUnitTests is MockAVSDeployer { cheats.prank(ejector); ejectionManager.ejectOperators(operatorIds); - for(uint8 i = 0; i < operatorsToEject; i++) { - assertEq(uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), uint8(IRegistryCoordinator.OperatorStatus.DEREGISTERED)); + for (uint8 i = 0; i < operatorsToEject; i++) { + assertEq( + uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), + uint8(IRegistryCoordinator.OperatorStatus.DEREGISTERED) + ); } cheats.warp(block.timestamp + (ratelimitWindow / 2)); @@ -201,17 +233,26 @@ contract EjectionManagerUnitTests is MockAVSDeployer { operatorIds = new bytes32[][](numQuorums); for (uint8 i = 0; i < numQuorums; i++) { operatorIds[i] = new bytes32[](operatorsToEject); - for (uint j = 0; j < operatorsToEject; j++) { - operatorIds[i][j] = registryCoordinator.getOperatorId(_incrementAddress(defaultOperator, operatorsToEject + j)); + for (uint256 j = 0; j < operatorsToEject; j++) { + operatorIds[i][j] = registryCoordinator.getOperatorId( + _incrementAddress(defaultOperator, operatorsToEject + j) + ); } } - for(uint8 i = 0; i < operatorsToEject; i++) { - assertEq(uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, operatorsToEject + i))), uint8(IRegistryCoordinator.OperatorStatus.REGISTERED)); + for (uint8 i = 0; i < operatorsToEject; i++) { + assertEq( + uint8( + registryCoordinator.getOperatorStatus( + _incrementAddress(defaultOperator, operatorsToEject + i) + ) + ), + uint8(IRegistryCoordinator.OperatorStatus.REGISTERED) + ); } - for(uint8 i = 0; i < numQuorums; i++) { - for(uint8 j = 0; j < operatorsToEject; j++) { + for (uint8 i = 0; i < numQuorums; i++) { + for (uint8 j = 0; j < operatorsToEject; j++) { cheats.expectEmit(true, true, true, true, address(ejectionManager)); emit OperatorEjected(operatorIds[i][j], i); } @@ -220,8 +261,15 @@ contract EjectionManagerUnitTests is MockAVSDeployer { cheats.prank(ejector); ejectionManager.ejectOperators(operatorIds); - for(uint8 i = 0; i < operatorsToEject; i++) { - assertEq(uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, operatorsToEject + i))), uint8(IRegistryCoordinator.OperatorStatus.DEREGISTERED)); + for (uint8 i = 0; i < operatorsToEject; i++) { + assertEq( + uint8( + registryCoordinator.getOperatorStatus( + _incrementAddress(defaultOperator, operatorsToEject + i) + ) + ), + uint8(IRegistryCoordinator.OperatorStatus.DEREGISTERED) + ); } } @@ -241,17 +289,21 @@ contract EjectionManagerUnitTests is MockAVSDeployer { bytes32[][] memory operatorIds = new bytes32[][](numQuorums); for (uint8 i = 0; i < numQuorums; i++) { operatorIds[i] = new bytes32[](operatorsToEject); - for (uint j = 0; j < operatorsToEject; j++) { - operatorIds[i][j] = registryCoordinator.getOperatorId(_incrementAddress(defaultOperator, j)); + for (uint256 j = 0; j < operatorsToEject; j++) { + operatorIds[i][j] = + registryCoordinator.getOperatorId(_incrementAddress(defaultOperator, j)); } } - for(uint8 i = 0; i < operatorsToEject; i++) { - assertEq(uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), uint8(IRegistryCoordinator.OperatorStatus.REGISTERED)); + for (uint8 i = 0; i < operatorsToEject; i++) { + assertEq( + uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), + uint8(IRegistryCoordinator.OperatorStatus.REGISTERED) + ); } - for(uint8 i = 0; i < numQuorums; i++) { - for(uint8 j = 0; j < operatorsToEject; j++) { + for (uint8 i = 0; i < numQuorums; i++) { + for (uint8 j = 0; j < operatorsToEject; j++) { cheats.expectEmit(true, true, true, true, address(ejectionManager)); emit OperatorEjected(operatorIds[i][j], i); } @@ -260,8 +312,11 @@ contract EjectionManagerUnitTests is MockAVSDeployer { cheats.prank(ejector); ejectionManager.ejectOperators(operatorIds); - for(uint8 i = 0; i < operatorsToEject; i++) { - assertEq(uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), uint8(IRegistryCoordinator.OperatorStatus.DEREGISTERED)); + for (uint8 i = 0; i < operatorsToEject; i++) { + assertEq( + uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), + uint8(IRegistryCoordinator.OperatorStatus.DEREGISTERED) + ); } } @@ -274,17 +329,21 @@ contract EjectionManagerUnitTests is MockAVSDeployer { bytes32[][] memory operatorIds = new bytes32[][](numQuorums); for (uint8 i = 0; i < numQuorums; i++) { operatorIds[i] = new bytes32[](operatorsToEject); - for (uint j = 0; j < operatorsToEject; j++) { - operatorIds[i][j] = registryCoordinator.getOperatorId(_incrementAddress(defaultOperator, j)); + for (uint256 j = 0; j < operatorsToEject; j++) { + operatorIds[i][j] = + registryCoordinator.getOperatorId(_incrementAddress(defaultOperator, j)); } } - for(uint8 i = 0; i < operatorsToEject; i++) { - assertEq(uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), uint8(IRegistryCoordinator.OperatorStatus.REGISTERED)); + for (uint8 i = 0; i < operatorsToEject; i++) { + assertEq( + uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), + uint8(IRegistryCoordinator.OperatorStatus.REGISTERED) + ); } - for(uint8 i = 0; i < numQuorums; i++) { - for(uint8 j = 0; j < operatorsToEject; j++) { + for (uint8 i = 0; i < numQuorums; i++) { + for (uint8 j = 0; j < operatorsToEject; j++) { cheats.expectEmit(true, true, true, true, address(ejectionManager)); emit OperatorEjected(operatorIds[i][j], i); } @@ -293,8 +352,11 @@ contract EjectionManagerUnitTests is MockAVSDeployer { cheats.prank(registryCoordinatorOwner); ejectionManager.ejectOperators(operatorIds); - for(uint8 i = 0; i < operatorsToEject; i++) { - assertEq(uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), uint8(IRegistryCoordinator.OperatorStatus.DEREGISTERED)); + for (uint8 i = 0; i < operatorsToEject; i++) { + assertEq( + uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), + uint8(IRegistryCoordinator.OperatorStatus.DEREGISTERED) + ); } } @@ -307,20 +369,24 @@ contract EjectionManagerUnitTests is MockAVSDeployer { bytes32[][] memory operatorIds = new bytes32[][](numQuorums); for (uint8 i = 0; i < numQuorums; i++) { operatorIds[i] = new bytes32[](operatorsToEject); - for (uint j = 0; j < operatorsToEject; j++) { - operatorIds[i][j] = registryCoordinator.getOperatorId(_incrementAddress(defaultOperator, j)); + for (uint256 j = 0; j < operatorsToEject; j++) { + operatorIds[i][j] = + registryCoordinator.getOperatorId(_incrementAddress(defaultOperator, j)); } } cheats.prank(defaultOperator); registryCoordinator.deregisterOperator(BitmapUtils.bitmapToBytesArray(MAX_QUORUM_BITMAP)); - for(uint8 i = 1; i < operatorsToEject; i++) { - assertEq(uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), uint8(IRegistryCoordinator.OperatorStatus.REGISTERED)); + for (uint8 i = 1; i < operatorsToEject; i++) { + assertEq( + uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), + uint8(IRegistryCoordinator.OperatorStatus.REGISTERED) + ); } - for(uint8 i = 0; i < numQuorums; i++) { - for(uint8 j = 1; j < operatorsToEject; j++) { + for (uint8 i = 0; i < numQuorums; i++) { + for (uint8 j = 1; j < operatorsToEject; j++) { cheats.expectEmit(true, true, true, true, address(ejectionManager)); emit OperatorEjected(operatorIds[i][j], i); } @@ -329,8 +395,11 @@ contract EjectionManagerUnitTests is MockAVSDeployer { cheats.prank(ejector); ejectionManager.ejectOperators(operatorIds); - for(uint8 i = 0; i < operatorsToEject; i++) { - assertEq(uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), uint8(IRegistryCoordinator.OperatorStatus.DEREGISTERED)); + for (uint8 i = 0; i < operatorsToEject; i++) { + assertEq( + uint8(registryCoordinator.getOperatorStatus(_incrementAddress(defaultOperator, i))), + uint8(IRegistryCoordinator.OperatorStatus.DEREGISTERED) + ); } } @@ -338,7 +407,8 @@ contract EjectionManagerUnitTests is MockAVSDeployer { uint8 quorumNumber = 0; ratelimitWindow = 2 days; ejectableStakePercent = 2000; - IEjectionManager.QuorumEjectionParams memory _quorumEjectionParams = IEjectionManager.QuorumEjectionParams({ + IEjectionManager.QuorumEjectionParams memory _quorumEjectionParams = IEjectionManager + .QuorumEjectionParams({ rateLimitWindow: ratelimitWindow, ejectableStakePercent: ejectableStakePercent }); @@ -349,7 +419,8 @@ contract EjectionManagerUnitTests is MockAVSDeployer { cheats.prank(registryCoordinatorOwner); ejectionManager.setQuorumEjectionParams(quorumNumber, _quorumEjectionParams); - (uint32 setRatelimitWindow, uint16 setEjectableStakePercent) = ejectionManager.quorumEjectionParams(quorumNumber); + (uint32 setRatelimitWindow, uint16 setEjectableStakePercent) = + ejectionManager.quorumEjectionParams(quorumNumber); assertEq(setRatelimitWindow, _quorumEjectionParams.rateLimitWindow); assertEq(setEjectableStakePercent, _quorumEjectionParams.ejectableStakePercent); } @@ -379,10 +450,13 @@ contract EjectionManagerUnitTests is MockAVSDeployer { function test_Overflow_Regression() public { cheats.prank(registryCoordinatorOwner); - ejectionManager.setQuorumEjectionParams(0, IEjectionManager.QuorumEjectionParams({ - rateLimitWindow: 7 days, - ejectableStakePercent: 9999 - })); + ejectionManager.setQuorumEjectionParams( + 0, + IEjectionManager.QuorumEjectionParams({ + rateLimitWindow: 7 days, + ejectableStakePercent: 9999 + }) + ); stakeRegistry.recordTotalStakeUpdate(1, 2_000_000_000 * 1 ether); @@ -390,7 +464,7 @@ contract EjectionManagerUnitTests is MockAVSDeployer { } function _registerOperaters(uint8 numOperators, uint96 stake) internal { - for (uint i = 0; i < numOperators; i++) { + for (uint256 i = 0; i < numOperators; i++) { BN254.G1Point memory pubKey = BN254.hashToG1(keccak256(abi.encodePacked(i))); address operator = _incrementAddress(defaultOperator, i); _registerOperatorWithCoordinator(operator, MAX_QUORUM_BITMAP, pubKey, stake); diff --git a/test/unit/IndexRegistryUnit.t.sol b/test/unit/IndexRegistryUnit.t.sol index 79d74e91..8846ff9d 100644 --- a/test/unit/IndexRegistryUnit.t.sol +++ b/test/unit/IndexRegistryUnit.t.sol @@ -45,10 +45,11 @@ contract IndexRegistryUnitTests is MockAVSDeployer, IIndexRegistryEvents { _initializeQuorum(); } - /******************************************************************************* - INTERNAL UNIT TEST HELPERS - *******************************************************************************/ - + /** + * + * INTERNAL UNIT TEST HELPERS + * + */ function _initializeQuorum() internal { uint8 quorumNumber = nextQuorum; nextQuorum++; @@ -65,7 +66,9 @@ contract IndexRegistryUnitTests is MockAVSDeployer, IIndexRegistryEvents { } /// @dev Doesn't increment nextQuorum as assumes quorumNumber is any valid arbitrary quorumNumber - function _initializeQuorum(uint8 quorumNumber) internal { + function _initializeQuorum( + uint8 quorumNumber + ) internal { cheats.prank(address(registryCoordinator)); // Initialize quorum and mark registered @@ -75,10 +78,12 @@ contract IndexRegistryUnitTests is MockAVSDeployer, IIndexRegistryEvents { /// @dev initializeQuorum based on passed in bitmap of quorum numbers /// assumes that bitmap does not contain already initailized quorums and doesn't increment nextQuorum - function _initializeFuzzedQuorums(uint192 bitmap) internal { + function _initializeFuzzedQuorums( + uint192 bitmap + ) internal { bytes memory quorumNumbers = bitmapUtilsWrapper.bitmapToBytesArray(bitmap); - for (uint i = 0; i < quorumNumbers.length; i++) { + for (uint256 i = 0; i < quorumNumbers.length; i++) { uint8 quorumNumber = uint8(quorumNumbers[i]); _initializeQuorum(quorumNumber); } @@ -100,7 +105,8 @@ contract IndexRegistryUnitTests is MockAVSDeployer, IIndexRegistryEvents { bytes memory quorumNumbers ) internal returns (uint32[] memory) { cheats.prank(address(registryCoordinator)); - uint32[] memory numOperatorsPerQuorum = indexRegistry.registerOperator(operatorId, quorumNumbers); + uint32[] memory numOperatorsPerQuorum = + indexRegistry.registerOperator(operatorId, quorumNumbers); return numOperatorsPerQuorum; } @@ -112,24 +118,19 @@ contract IndexRegistryUnitTests is MockAVSDeployer, IIndexRegistryEvents { bytes memory quorumNumbers = new bytes(1); quorumNumbers[0] = bytes1(quorumNumber); cheats.prank(address(registryCoordinator)); - uint32[] memory numOperatorsPerQuorum = indexRegistry.registerOperator(operatorId, quorumNumbers); + uint32[] memory numOperatorsPerQuorum = + indexRegistry.registerOperator(operatorId, quorumNumbers); return numOperatorsPerQuorum[0]; } /// @dev deregister an operator for a given set of quorums - function _deregisterOperator( - bytes32 operatorId, - bytes memory quorumNumbers - ) internal { + function _deregisterOperator(bytes32 operatorId, bytes memory quorumNumbers) internal { cheats.prank(address(registryCoordinator)); indexRegistry.deregisterOperator(operatorId, quorumNumbers); } /// @dev deregister an operator for a single quorum - function _deregisterOperatorSingleQuorum( - bytes32 operatorId, - uint8 quorumNumber - ) internal { + function _deregisterOperatorSingleQuorum(bytes32 operatorId, uint8 quorumNumber) internal { bytes memory quorumNumbers = new bytes(1); quorumNumbers[0] = bytes1(quorumNumber); cheats.prank(address(registryCoordinator)); @@ -138,15 +139,15 @@ contract IndexRegistryUnitTests is MockAVSDeployer, IIndexRegistryEvents { /// @dev Uses `rand` to return a random uint, with a range given by `min` and `max` (inclusive) /// @return `min` <= result <= `max` - function _randUint(bytes32 rand, uint min, uint max) internal pure returns (uint) { + function _randUint(bytes32 rand, uint256 min, uint256 max) internal pure returns (uint256) { // hashing makes for more uniform randomness rand = keccak256(abi.encodePacked(rand)); - uint range = max - min + 1; + uint256 range = max - min + 1; // calculate the number of bits needed for the range - uint bitsNeeded = 0; - uint tempRange = range; + uint256 bitsNeeded = 0; + uint256 tempRange = range; while (tempRange > 0) { bitsNeeded++; tempRange >>= 1; @@ -154,8 +155,8 @@ contract IndexRegistryUnitTests is MockAVSDeployer, IIndexRegistryEvents { // create a mask for the required number of bits // and extract the value from the hash - uint mask = (1 << bitsNeeded) - 1; - uint value = uint(rand) & mask; + uint256 mask = (1 << bitsNeeded) - 1; + uint256 value = uint256(rand) & mask; // in case value is out of range, wrap around or retry while (value >= range) { @@ -165,18 +166,19 @@ contract IndexRegistryUnitTests is MockAVSDeployer, IIndexRegistryEvents { return min + value; } - /******************************************************************************* - ASSERTION HELPERS - *******************************************************************************/ - + /** + * + * ASSERTION HELPERS + * + */ function _assertQuorumUpdate( uint8 quorumNumber, uint256 expectedNumOperators, uint256 expectedFromBlockNumber ) internal { // Check _totalOperatorsHistory updates for quorum - IIndexRegistry.QuorumUpdate memory quorumUpdate = indexRegistry - .getLatestQuorumUpdate(quorumNumber); + IIndexRegistry.QuorumUpdate memory quorumUpdate = + indexRegistry.getLatestQuorumUpdate(quorumNumber); assertEq( quorumUpdate.numOperators, expectedNumOperators, @@ -201,17 +203,11 @@ contract IndexRegistryUnitTests is MockAVSDeployer, IIndexRegistryEvents { bytes32 operatorId, uint256 expectedFromBlockNumber ) internal { - IIndexRegistry.OperatorUpdate memory operatorUpdate = indexRegistry - .getOperatorUpdateAtIndex(quorumNumber, operatorIndex, arrayIndex); + IIndexRegistry.OperatorUpdate memory operatorUpdate = + indexRegistry.getOperatorUpdateAtIndex(quorumNumber, operatorIndex, arrayIndex); + assertEq(operatorUpdate.operatorId, operatorId, "incorrect operatorId"); assertEq( - operatorUpdate.operatorId, - operatorId, - "incorrect operatorId" - ); - assertEq( - operatorUpdate.fromBlockNumber, - expectedFromBlockNumber, - "fromBlockNumber not correct" + operatorUpdate.fromBlockNumber, expectedFromBlockNumber, "fromBlockNumber not correct" ); } } @@ -222,10 +218,11 @@ contract IndexRegistryUnitTests_configAndGetters is IndexRegistryUnitTests { assertEq(address(indexRegistry.registryCoordinator()), address(registryCoordinator)); } - /******************************************************************************* - UNIT TESTS - GETTERS - *******************************************************************************/ - + /** + * + * UNIT TESTS - GETTERS + * + */ function _assertOperatorListsEqual( bytes32[] memory operatorList1, bytes32[] memory operatorList2, @@ -237,11 +234,7 @@ contract IndexRegistryUnitTests_configAndGetters is IndexRegistryUnitTests { ); for (uint256 i = 0; i < operatorList1.length; i++) { - assertEq( - operatorList1[i], - operatorList2[i], - "operator lists not equal" - ); + assertEq(operatorList1[i], operatorList2[i], "operator lists not equal"); } } @@ -266,11 +259,8 @@ contract IndexRegistryUnitTests_configAndGetters is IndexRegistryUnitTests { bytes32[] memory currRegisteredOperatorIds = new bytes32[](numOperators); uint256 currIndex = 0; for (uint256 i = 0; i < numOperators; i++) { - uint256 rand = _randUint({ - rand: keccak256(abi.encodePacked(bytes32(i), randSalt)), - min: 0, - max: 1 - }); + uint256 rand = + _randUint({rand: keccak256(abi.encodePacked(bytes32(i), randSalt)), min: 0, max: 1}); // Roll block number currBlockNumber += 10; @@ -282,7 +272,7 @@ contract IndexRegistryUnitTests_configAndGetters is IndexRegistryUnitTests { _deregisterOperatorSingleQuorum(operatorId, quorumNumber); currRegisteredOperatorIds[currIndex] = operatorId; currIndex--; - // register operator + // register operator } else { (, bytes32 operatorId) = _selectNewOperator(); _registerOperatorSingleQuorum(operatorId, quorumNumber); @@ -292,12 +282,11 @@ contract IndexRegistryUnitTests_configAndGetters is IndexRegistryUnitTests { } // should revert with startBlocknumber - cheats.expectRevert("IndexRegistry._operatorCountAtBlockNumber: quorum did not exist at given block number"); - - indexRegistry.getOperatorListAtBlockNumber( - quorumNumber, - startBlockNumber + cheats.expectRevert( + "IndexRegistry._operatorCountAtBlockNumber: quorum did not exist at given block number" ); + + indexRegistry.getOperatorListAtBlockNumber(quorumNumber, startBlockNumber); } } @@ -306,16 +295,16 @@ contract IndexRegistryUnitTests_configAndGetters is IndexRegistryUnitTests { * And keeping track of the total operators and their indexes. Checks that the return list of operatorIds * from `getOperatorListForQuorum` matches the expected list of operatorIds */ - function testFuzz_getOperatorListForQuorumAtBlockNumber(uint8 numOperators, bytes32 randSalt) public { + function testFuzz_getOperatorListForQuorumAtBlockNumber( + uint8 numOperators, + bytes32 randSalt + ) public { bytes32[] memory currRegisteredOperatorIds = new bytes32[](numOperators); uint256 currIndex = 0; uint32 currBlockNumber = uint32(block.number); for (uint256 i = 0; i < numOperators; i++) { - uint256 rand = _randUint({ - rand: keccak256(abi.encodePacked(bytes32(i), randSalt)), - min: 0, - max: 1 - }); + uint256 rand = + _randUint({rand: keccak256(abi.encodePacked(bytes32(i), randSalt)), min: 0, max: 1}); // Roll block number currBlockNumber += 10; @@ -327,7 +316,7 @@ contract IndexRegistryUnitTests_configAndGetters is IndexRegistryUnitTests { _deregisterOperatorSingleQuorum(operatorId, defaultQuorumNumber); currRegisteredOperatorIds[currIndex] = operatorId; currIndex--; - // register operator + // register operator } else { (, bytes32 operatorId) = _selectNewOperator(); _registerOperatorSingleQuorum(operatorId, defaultQuorumNumber); @@ -337,16 +326,10 @@ contract IndexRegistryUnitTests_configAndGetters is IndexRegistryUnitTests { } // Check operator list - bytes32[] memory operatorList = indexRegistry.getOperatorListAtBlockNumber( - defaultQuorumNumber, - currBlockNumber - ); + bytes32[] memory operatorList = + indexRegistry.getOperatorListAtBlockNumber(defaultQuorumNumber, currBlockNumber); - _assertOperatorListsEqual( - operatorList, - currRegisteredOperatorIds, - currIndex - ); + _assertOperatorListsEqual(operatorList, currRegisteredOperatorIds, currIndex); } } @@ -354,15 +337,15 @@ contract IndexRegistryUnitTests_configAndGetters is IndexRegistryUnitTests { * @dev Loop for numOperators randomly registering and deregistering operators for a single quorum. * Checks that the totalOperatorsForQuorum returns the correct total after each register/deregister */ - function testFuzz_TotalOperatorUpdatesForOneQuorum(uint8 numOperators, bytes32 randSalt) public { + function testFuzz_TotalOperatorUpdatesForOneQuorum( + uint8 numOperators, + bytes32 randSalt + ) public { bytes32[] memory currRegisteredOperatorIds = new bytes32[](numOperators); uint256 currIndex = 0; for (uint256 i = 0; i < numOperators; i++) { - uint256 rand = _randUint({ - rand: keccak256(abi.encodePacked(bytes32(i), randSalt)), - min: 0, - max: 1 - }); + uint256 rand = + _randUint({rand: keccak256(abi.encodePacked(bytes32(i), randSalt)), min: 0, max: 1}); // deregister operator, must also have at least one registered operator if (rand == 0 && currIndex > 0) { @@ -370,7 +353,7 @@ contract IndexRegistryUnitTests_configAndGetters is IndexRegistryUnitTests { _deregisterOperatorSingleQuorum(operatorId, defaultQuorumNumber); currRegisteredOperatorIds[currIndex] = operatorId; currIndex--; - // register operator + // register operator } else { (, bytes32 operatorId) = _selectNewOperator(); _registerOperatorSingleQuorum(operatorId, defaultQuorumNumber); @@ -388,7 +371,9 @@ contract IndexRegistryUnitTests_configAndGetters is IndexRegistryUnitTests { } } - function testFuzz_viewFunctions_Revert_WhenInvalidQuorumNumber(uint8 quorumNumber) public { + function testFuzz_viewFunctions_Revert_WhenInvalidQuorumNumber( + uint8 quorumNumber + ) public { cheats.assume(quorumNumber >= nextQuorum); cheats.expectRevert(); @@ -408,12 +393,14 @@ contract IndexRegistryUnitTests_configAndGetters is IndexRegistryUnitTests { contract IndexRegistryUnitTests_registerOperator is IndexRegistryUnitTests { using BitmapUtils for *; - - /******************************************************************************* - UNIT TESTS - REGISTRATION - *******************************************************************************/ - - function testFuzz_Revert_WhenNonRegistryCoordinator(address nonRegistryCoordinator) public { + /** + * + * UNIT TESTS - REGISTRATION + * + */ + function testFuzz_Revert_WhenNonRegistryCoordinator( + address nonRegistryCoordinator + ) public { cheats.assume(nonRegistryCoordinator != address(registryCoordinator)); cheats.assume(nonRegistryCoordinator != proxyAdminOwner); bytes memory quorumNumbers = new bytes(defaultQuorumNumber); @@ -433,7 +420,8 @@ contract IndexRegistryUnitTests_registerOperator is IndexRegistryUnitTests { cheats.assume(invalidBitmap > initializedQuorumBitmap); // mask out quorums that are already initialized and the quorums that are not going to be registered invalidBitmap = uint192(invalidBitmap.minus(uint256(initializedQuorumBitmap))); - bitmap = uint192(bitmap.minus(uint256(initializedQuorumBitmap)).minus(uint256(invalidBitmap))); + bitmap = + uint192(bitmap.minus(uint256(initializedQuorumBitmap)).minus(uint256(invalidBitmap))); // Initialize fuzzed quorum numbers _initializeFuzzedQuorums(bitmap); @@ -457,11 +445,7 @@ contract IndexRegistryUnitTests_registerOperator is IndexRegistryUnitTests { (, bytes32 operatorId) = _selectNewOperator(); uint32 numOperators = _registerOperatorSingleQuorum(operatorId, defaultQuorumNumber); - assertEq( - numOperators, - 1, - "IndexRegistry.registerOperator: numOperators is not 1" - ); + assertEq(numOperators, 1, "IndexRegistry.registerOperator: numOperators is not 1"); // Check _totalOperatorsHistory updates _assertQuorumUpdate({ @@ -551,11 +535,7 @@ contract IndexRegistryUnitTests_registerOperator is IndexRegistryUnitTests { uint32 numOperators = _registerOperatorSingleQuorum(operatorId2, defaultQuorumNumber); // Check return value - assertEq( - numOperators, - 2, - "IndexRegistry.registerOperator: numOperators not 2" - ); + assertEq(numOperators, 2, "IndexRegistry.registerOperator: numOperators not 2"); // Check _totalOperatorsHistory and _indexHistory updates for quorum _assertOperatorUpdate({ @@ -587,7 +567,9 @@ contract IndexRegistryUnitTests_registerOperator is IndexRegistryUnitTests { * 4. quorumNumbers.length != 0 * 5. operator is not already registerd for any quorums being registered for */ - function testFuzz_registerOperator_MultipleQuorums(uint192 bitmap) public { + function testFuzz_registerOperator_MultipleQuorums( + uint192 bitmap + ) public { // mask out quorums that are already initialized bitmap = uint192(bitmap.minus(uint256(initializedQuorumBitmap))); bytes memory quorumNumbers = bitmapUtilsWrapper.bitmapToBytesArray(bitmap); @@ -682,7 +664,11 @@ contract IndexRegistryUnitTests_registerOperator is IndexRegistryUnitTests { for (uint256 i = 0; i < quorumNumbers.length; i++) { quorumUpdate = indexRegistry.getLatestQuorumUpdate(uint8(quorumNumbers[i])); assertEq(quorumUpdate.numOperators, numOperators, "num operators not correct"); - assertEq(quorumUpdate.fromBlockNumber, block.number, "latest update should be from current block number"); + assertEq( + quorumUpdate.fromBlockNumber, + block.number, + "latest update should be from current block number" + ); } } } @@ -690,10 +676,14 @@ contract IndexRegistryUnitTests_registerOperator is IndexRegistryUnitTests { contract IndexRegistryUnitTests_deregisterOperator is IndexRegistryUnitTests { using BitmapUtils for *; - /******************************************************************************* - UNIT TESTS - DEREGISTRATION - *******************************************************************************/ - function testFuzz_Revert_WhenNonRegistryCoordinator(address nonRegistryCoordinator) public { + /** + * + * UNIT TESTS - DEREGISTRATION + * + */ + function testFuzz_Revert_WhenNonRegistryCoordinator( + address nonRegistryCoordinator + ) public { cheats.assume(nonRegistryCoordinator != address(registryCoordinator)); cheats.assume(nonRegistryCoordinator != address(proxyAdmin)); // de-register an operator @@ -714,7 +704,8 @@ contract IndexRegistryUnitTests_deregisterOperator is IndexRegistryUnitTests { cheats.assume(invalidBitmap > initializedQuorumBitmap); // mask out quorums that are already initialized and the quorums that are not going to be registered invalidBitmap = uint192(invalidBitmap.minus(uint256(initializedQuorumBitmap))); - bitmap = uint192(bitmap.minus(uint256(initializedQuorumBitmap)).minus(uint256(invalidBitmap))); + bitmap = + uint192(bitmap.minus(uint256(initializedQuorumBitmap)).minus(uint256(invalidBitmap))); bytes memory quorumNumbers = bitmapUtilsWrapper.bitmapToBytesArray(bitmap); bytes memory invalidQuorumNumbers = bitmapUtilsWrapper.bitmapToBytesArray(invalidBitmap); _initializeFuzzedQuorums(bitmap); @@ -831,10 +822,15 @@ contract IndexRegistryUnitTests_deregisterOperator is IndexRegistryUnitTests { // get operator index, if operator index is new quorumCount // then other operator indexes are unchanged // otherwise the popped index operatorId will replace the deregistered operator's index - uint32 operatorIndex = IndexRegistry(address(indexRegistry)).currentOperatorIndex(quorumNumber, operatorId); - uint32 quorumCountBefore = indexRegistry.getLatestQuorumUpdate(quorumNumber).numOperators; - - assertTrue(operatorIndex <= quorumCountBefore - 1, "operator index should be less than quorumCount"); + uint32 operatorIndex = + IndexRegistry(address(indexRegistry)).currentOperatorIndex(quorumNumber, operatorId); + uint32 quorumCountBefore = + indexRegistry.getLatestQuorumUpdate(quorumNumber).numOperators; + + assertTrue( + operatorIndex <= quorumCountBefore - 1, + "operator index should be less than quorumCount" + ); bytes32 operatorIdAtBeforeQuorumCount = indexRegistry.getLatestOperatorUpdate({ quorumNumber: quorumNumber, operatorIndex: quorumCountBefore - 1 @@ -848,7 +844,11 @@ contract IndexRegistryUnitTests_deregisterOperator is IndexRegistryUnitTests { _deregisterOperatorSingleQuorum(operatorId, quorumNumber); if (operatorIndex != quorumCountBefore - 1) { - assertNotEq(operatorIdAtBeforeQuorumCount, operatorId, "operatorId at currentQuorumCount - 1 should not be operatorId we are deregistering"); + assertNotEq( + operatorIdAtBeforeQuorumCount, + operatorId, + "operatorId at currentQuorumCount - 1 should not be operatorId we are deregistering" + ); _assertOperatorUpdate({ quorumNumber: quorumNumber, operatorIndex: operatorIndex, @@ -898,10 +898,15 @@ contract IndexRegistryUnitTests_deregisterOperator is IndexRegistryUnitTests { // get operator index, if operator index is new quorumCount // then other operator indexes are unchanged // otherwise the popped index operatorId will replace the deregistered operator's index - uint32 operatorIndex = IndexRegistry(address(indexRegistry)).currentOperatorIndex(quorumNumber, operatorId); - uint32 quorumCountBefore = indexRegistry.getLatestQuorumUpdate(quorumNumber).numOperators; - - assertTrue(operatorIndex <= quorumCountBefore - 1, "operator index should be less than quorumCount"); + uint32 operatorIndex = + IndexRegistry(address(indexRegistry)).currentOperatorIndex(quorumNumber, operatorId); + uint32 quorumCountBefore = + indexRegistry.getLatestQuorumUpdate(quorumNumber).numOperators; + + assertTrue( + operatorIndex <= quorumCountBefore - 1, + "operator index should be less than quorumCount" + ); bytes32 operatorIdAtBeforeQuorumCount = indexRegistry.getLatestOperatorUpdate({ quorumNumber: quorumNumber, operatorIndex: quorumCountBefore - 1 @@ -991,7 +996,9 @@ contract IndexRegistryUnitTests_deregisterOperator is IndexRegistryUnitTests { IIndexRegistry.OperatorUpdate memory operatorUpdate = indexRegistry .getLatestOperatorUpdate({quorumNumber: uint8(quorumsToRemove[i]), operatorIndex: 0}); - assertEq(operatorUpdate.fromBlockNumber, block.number, "fromBlockNumber not set correctly"); + assertEq( + operatorUpdate.fromBlockNumber, block.number, "fromBlockNumber not set correctly" + ); assertEq(operatorUpdate.operatorId, operatorId3, "incorrect operatorId"); } } @@ -1044,8 +1051,10 @@ contract IndexRegistryUnitTests_deregisterOperator is IndexRegistryUnitTests { // Check operator's index for removed quorums IIndexRegistry.OperatorUpdate memory operatorUpdate = indexRegistry .getLatestOperatorUpdate({quorumNumber: uint8(quorumsToRemove[i]), operatorIndex: 1}); - assertEq(operatorUpdate.fromBlockNumber, block.number, "fromBlockNumber not set correctly"); + assertEq( + operatorUpdate.fromBlockNumber, block.number, "fromBlockNumber not set correctly" + ); assertEq(operatorUpdate.operatorId, bytes32(0), "incorrect operatorId"); } } -} \ No newline at end of file +} diff --git a/test/unit/LibMergeSort.t.sol b/test/unit/LibMergeSort.t.sol index dc2ddf7d..53031359 100644 --- a/test/unit/LibMergeSort.t.sol +++ b/test/unit/LibMergeSort.t.sol @@ -95,94 +95,93 @@ contract LibMergeSortTest is Test { } } -function testMergeSortArrays_Sort() public { - address[] memory left = new address[](3); - address[] memory right = new address[](3); + function testMergeSortArrays_Sort() public { + address[] memory left = new address[](3); + address[] memory right = new address[](3); - left[0] = address(0x3); - left[1] = address(0x1); - left[2] = address(0x2); + left[0] = address(0x3); + left[1] = address(0x1); + left[2] = address(0x2); - right[0] = address(0x6); - right[1] = address(0x4); - right[2] = address(0x5); + right[0] = address(0x6); + right[1] = address(0x4); + right[2] = address(0x5); - left = left.sort(); - right = right.sort(); + left = left.sort(); + right = right.sort(); - address[] memory expected = new address[](6); - expected[0] = address(0x1); - expected[1] = address(0x2); - expected[2] = address(0x3); - expected[3] = address(0x4); - expected[4] = address(0x5); - expected[5] = address(0x6); + address[] memory expected = new address[](6); + expected[0] = address(0x1); + expected[1] = address(0x2); + expected[2] = address(0x3); + expected[3] = address(0x4); + expected[4] = address(0x5); + expected[5] = address(0x6); - address[] memory result = left.mergeSortArrays(right); + address[] memory result = left.mergeSortArrays(right); - for (uint256 i = 0; i < expected.length; i++) { - assertEq(result[i], expected[i], "Array elements are not sorted correctly"); + for (uint256 i = 0; i < expected.length; i++) { + assertEq(result[i], expected[i], "Array elements are not sorted correctly"); + } } -} -/// NOTE: we're assuming the input arrays themselves are unique. -/// Demonstrating behavior of library -function testMergeSortArraysWithDuplicateInLeft() public { - address[] memory left = new address[](4); - address[] memory right = new address[](3); - - left[0] = address(0x1); - left[1] = address(0x3); - left[2] = address(0x3); // Duplicate - left[3] = address(0x5); - - right[0] = address(0x2); - right[1] = address(0x4); - right[2] = address(0x6); - - address[] memory expected = new address[](7); - expected[0] = address(0x1); - expected[1] = address(0x2); - expected[2] = address(0x3); - expected[3] = address(0x3); - expected[4] = address(0x4); - expected[5] = address(0x5); - expected[6] = address(0x6); - - address[] memory result = left.mergeSortArrays(right); - - for (uint256 i = 0; i < expected.length; i++) { - assertEq(result[i], expected[i], "Array elements are not sorted correctly"); - } -} -function testMergeSortArraysWithDuplicateInRight() public { - address[] memory left = new address[](3); - address[] memory right = new address[](4); - - left[0] = address(0x1); - left[1] = address(0x3); - left[2] = address(0x5); - - right[0] = address(0x2); - right[1] = address(0x4); - right[2] = address(0x4); // Duplicate - right[3] = address(0x6); - - address[] memory expected = new address[](7); - expected[0] = address(0x1); - expected[1] = address(0x2); - expected[2] = address(0x3); - expected[3] = address(0x4); - expected[4] = address(0x4); - expected[5] = address(0x5); - expected[6] = address(0x6); - - address[] memory result = left.mergeSortArrays(right); - - for (uint256 i = 0; i < expected.length; i++) { - assertEq(result[i], expected[i], "Array elements are not sorted correctly"); + /// NOTE: we're assuming the input arrays themselves are unique. + /// Demonstrating behavior of library + function testMergeSortArraysWithDuplicateInLeft() public { + address[] memory left = new address[](4); + address[] memory right = new address[](3); + + left[0] = address(0x1); + left[1] = address(0x3); + left[2] = address(0x3); // Duplicate + left[3] = address(0x5); + + right[0] = address(0x2); + right[1] = address(0x4); + right[2] = address(0x6); + + address[] memory expected = new address[](7); + expected[0] = address(0x1); + expected[1] = address(0x2); + expected[2] = address(0x3); + expected[3] = address(0x3); + expected[4] = address(0x4); + expected[5] = address(0x5); + expected[6] = address(0x6); + + address[] memory result = left.mergeSortArrays(right); + + for (uint256 i = 0; i < expected.length; i++) { + assertEq(result[i], expected[i], "Array elements are not sorted correctly"); + } } -} + function testMergeSortArraysWithDuplicateInRight() public { + address[] memory left = new address[](3); + address[] memory right = new address[](4); + + left[0] = address(0x1); + left[1] = address(0x3); + left[2] = address(0x5); + + right[0] = address(0x2); + right[1] = address(0x4); + right[2] = address(0x4); // Duplicate + right[3] = address(0x6); + + address[] memory expected = new address[](7); + expected[0] = address(0x1); + expected[1] = address(0x2); + expected[2] = address(0x3); + expected[3] = address(0x4); + expected[4] = address(0x4); + expected[5] = address(0x5); + expected[6] = address(0x6); + + address[] memory result = left.mergeSortArrays(right); + for (uint256 i = 0; i < expected.length; i++) { + assertEq(result[i], expected[i], "Array elements are not sorted correctly"); + } + } } diff --git a/test/unit/OperatorStateRetrieverUnit.t.sol b/test/unit/OperatorStateRetrieverUnit.t.sol index 55f6aabd..e16621fc 100644 --- a/test/unit/OperatorStateRetrieverUnit.t.sol +++ b/test/unit/OperatorStateRetrieverUnit.t.sol @@ -94,7 +94,9 @@ contract OperatorStateRetrieverUnitTests is MockAVSDeployer { IStakeRegistry.StrategyParams({strategy: IStrategy(address(1000)), multiplier: 1e16}); cheats.prank(registryCoordinator.owner()); - registryCoordinator.createTotalDelegatedStakeQuorum(operatorSetParams, minimumStake, strategyParams); + registryCoordinator.createTotalDelegatedStakeQuorum( + operatorSetParams, minimumStake, strategyParams + ); cheats.expectRevert( "IndexRegistry._operatorCountAtBlockNumber: quorum did not exist at given block number" @@ -234,7 +236,9 @@ contract OperatorStateRetrieverUnitTests is MockAVSDeployer { IStakeRegistry.StrategyParams({strategy: IStrategy(address(1000)), multiplier: 1e16}); cheats.prank(registryCoordinator.owner()); - registryCoordinator.createTotalDelegatedStakeQuorum(operatorSetParams, minimumStake, strategyParams); + registryCoordinator.createTotalDelegatedStakeQuorum( + operatorSetParams, minimumStake, strategyParams + ); cheats.expectRevert(IStakeRegistryErrors.EmptyStakeHistory.selector); operatorStateRetriever.getCheckSignaturesIndices( @@ -356,7 +360,9 @@ contract OperatorStateRetrieverUnitTests is MockAVSDeployer { assertEq(checkSignaturesIndices.nonSignerStakeIndices[1][0], 0); } - function testGetOperatorState_Valid(uint256 pseudoRandomNumber) public { + function testGetOperatorState_Valid( + uint256 pseudoRandomNumber + ) public { // register random operators and get the expected indices within the quorums and the metadata for the operators ( OperatorMetadata[] memory operatorMetadatas, @@ -425,7 +431,9 @@ contract OperatorStateRetrieverUnitTests is MockAVSDeployer { ); } - function testCheckSignaturesIndices_NoNonSigners_Valid(uint256 pseudoRandomNumber) public { + function testCheckSignaturesIndices_NoNonSigners_Valid( + uint256 pseudoRandomNumber + ) public { ( OperatorMetadata[] memory operatorMetadatas, uint256[][] memory expectedOperatorOverallIndices @@ -490,7 +498,9 @@ contract OperatorStateRetrieverUnitTests is MockAVSDeployer { } } - function testCheckSignaturesIndices_FewNonSigners_Valid(uint256 pseudoRandomNumber) public { + function testCheckSignaturesIndices_FewNonSigners_Valid( + uint256 pseudoRandomNumber + ) public { ( OperatorMetadata[] memory operatorMetadatas, uint256[][] memory expectedOperatorOverallIndices diff --git a/test/unit/RegistryCoordinatorUnit.t.sol b/test/unit/RegistryCoordinatorUnit.t.sol index 048e0cf1..3b62098d 100644 --- a/test/unit/RegistryCoordinatorUnit.t.sol +++ b/test/unit/RegistryCoordinatorUnit.t.sol @@ -7,7 +7,6 @@ import {QuorumBitmapHistoryLib} from "../../src/libraries/QuorumBitmapHistoryLib import {BitmapUtils} from "../../src/libraries/BitmapUtils.sol"; import {console} from "forge-std/console.sol"; - contract RegistryCoordinatorUnitTests is MockAVSDeployer { using BN254 for BN254.G1Point; @@ -24,30 +23,20 @@ contract RegistryCoordinatorUnitTests is MockAVSDeployer { event OperatorSocketUpdate(bytes32 indexed operatorId, string socket); /// @notice emitted whenever the stake of `operator` is updated - event OperatorStakeUpdate( - bytes32 indexed operatorId, - uint8 quorumNumber, - uint96 stake - ); + event OperatorStakeUpdate(bytes32 indexed operatorId, uint8 quorumNumber, uint96 stake); // Emitted when a new operator pubkey is registered for a set of quorums - event OperatorAddedToQuorums( - address operator, - bytes32 operatorId, - bytes quorumNumbers - ); + event OperatorAddedToQuorums(address operator, bytes32 operatorId, bytes quorumNumbers); // Emitted when an operator pubkey is removed from a set of quorums - event OperatorRemovedFromQuorums( - address operator, - bytes32 operatorId, - bytes quorumNumbers - ); + event OperatorRemovedFromQuorums(address operator, bytes32 operatorId, bytes quorumNumbers); // emitted when an operator's index in the orderd operator list for the quorum with number `quorumNumber` is updated event QuorumIndexUpdate(bytes32 indexed operatorId, uint8 quorumNumber, uint32 newIndex); - event OperatorSetParamsUpdated(uint8 indexed quorumNumber, IRegistryCoordinator.OperatorSetParam operatorSetParams); + event OperatorSetParamsUpdated( + uint8 indexed quorumNumber, IRegistryCoordinator.OperatorSetParam operatorSetParams + ); event ChurnApproverUpdated(address prevChurnApprover, address newChurnApprover); @@ -55,7 +44,7 @@ contract RegistryCoordinatorUnitTests is MockAVSDeployer { event QuorumBlockNumberUpdated(uint8 indexed quorumNumber, uint256 blocknumber); - function setUp() virtual public { + function setUp() public virtual { _deployMockEigenLayerAndAVS(numQuorums); } @@ -63,26 +52,31 @@ contract RegistryCoordinatorUnitTests is MockAVSDeployer { uint256 pseudoRandomNumber, bytes memory quorumNumbers, uint96 operatorToKickStake - ) internal returns( - address operatorToRegister, - BN254.G1Point memory operatorToRegisterPubKey, - IRegistryCoordinator.OperatorKickParam[] memory operatorKickParams - ) { + ) + internal + returns ( + address operatorToRegister, + BN254.G1Point memory operatorToRegisterPubKey, + IRegistryCoordinator.OperatorKickParam[] memory operatorKickParams + ) + { uint32 kickRegistrationBlockNumber = 100; uint256 quorumBitmap = BitmapUtils.orderedBytesArrayToBitmap(quorumNumbers); cheats.roll(kickRegistrationBlockNumber); - for (uint i = 0; i < defaultMaxOperatorCount - 1; i++) { - BN254.G1Point memory pubKey = BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, i))); + for (uint256 i = 0; i < defaultMaxOperatorCount - 1; i++) { + BN254.G1Point memory pubKey = + BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, i))); address operator = _incrementAddress(defaultOperator, i); _registerOperatorWithCoordinator(operator, quorumBitmap, pubKey); } operatorToRegister = _incrementAddress(defaultOperator, defaultMaxOperatorCount); - operatorToRegisterPubKey = BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, defaultMaxOperatorCount))); + operatorToRegisterPubKey = + BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, defaultMaxOperatorCount))); bytes32 operatorToRegisterId = BN254.hashG1Point(operatorToRegisterPubKey); bytes32 operatorToKickId; address operatorToKick; @@ -90,12 +84,16 @@ contract RegistryCoordinatorUnitTests is MockAVSDeployer { // register last operator before kick operatorKickParams = new IRegistryCoordinator.OperatorKickParam[](1); { - BN254.G1Point memory pubKey = BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, defaultMaxOperatorCount - 1))); + BN254.G1Point memory pubKey = BN254.hashToG1( + keccak256(abi.encodePacked(pseudoRandomNumber, defaultMaxOperatorCount - 1)) + ); operatorToKickId = BN254.hashG1Point(pubKey); operatorToKick = _incrementAddress(defaultOperator, defaultMaxOperatorCount - 1); // register last operator with much more than the kickBIPsOfTotalStake stake - _registerOperatorWithCoordinator(operatorToKick, quorumBitmap, pubKey, operatorToKickStake); + _registerOperatorWithCoordinator( + operatorToKick, quorumBitmap, pubKey, operatorToKickStake + ); bytes32[] memory operatorIdsToSwap = new bytes32[](1); // operatorIdsToSwap[0] = operatorToRegisterId @@ -118,7 +116,7 @@ contract RegistryCoordinatorUnitTests_Initialization_Setters is RegistryCoordina assertEq(address(registryCoordinator.indexRegistry()), address(indexRegistry)); assertEq(address(registryCoordinator.serviceManager()), address(serviceManager)); - for (uint i = 0; i < numQuorums; i++) { + for (uint256 i = 0; i < numQuorums; i++) { assertEq( keccak256(abi.encode(registryCoordinator.getOperatorSetParams(uint8(i)))), keccak256(abi.encode(operatorSetParams[i])) @@ -131,7 +129,7 @@ contract RegistryCoordinatorUnitTests_Initialization_Setters is RegistryCoordina registryCoordinatorOwner, churnApprover, ejector, - 0/*initialPausedStatus*/, + 0, /*initialPausedStatus*/ operatorSetParams, new uint96[](0), new IStakeRegistry.StrategyParams[][](0), @@ -145,8 +143,11 @@ contract RegistryCoordinatorUnitTests_Initialization_Setters is RegistryCoordina cheats.expectEmit(true, true, true, true, address(registryCoordinator)); emit OperatorSetParamsUpdated(0, operatorSetParams[1]); registryCoordinator.setOperatorSetParams(0, operatorSetParams[1]); - assertEq(keccak256(abi.encode(registryCoordinator.getOperatorSetParams(0))),keccak256(abi.encode(operatorSetParams[1])), - "operator set params not updated correctly"); + assertEq( + keccak256(abi.encode(registryCoordinator.getOperatorSetParams(0))), + keccak256(abi.encode(operatorSetParams[1])), + "operator set params not updated correctly" + ); } function test_setOperatorSetParams_revert_notOwner() public { @@ -198,7 +199,6 @@ contract RegistryCoordinatorUnitTests_Initialization_Setters is RegistryCoordina cheats.expectEmit(true, true, true, true, address(registryCoordinator)); emit OperatorSocketUpdate(defaultOperatorId, "localhost:32004"); registryCoordinator.updateSocket("localhost:32004"); - } function test_updateSocket_revert_notRegistered() public { @@ -214,7 +214,9 @@ contract RegistryCoordinatorUnitTests_Initialization_Setters is RegistryCoordina cheats.expectRevert("Ownable: caller is not the owner"); cheats.prank(defaultOperator); - registryCoordinator.createTotalDelegatedStakeQuorum(operatorSetParams, minimumStake, strategyParams); + registryCoordinator.createTotalDelegatedStakeQuorum( + operatorSetParams, minimumStake, strategyParams + ); } function test_createQuorum() public { @@ -222,26 +224,26 @@ contract RegistryCoordinatorUnitTests_Initialization_Setters is RegistryCoordina // this is necessary since the default setup already configures the max number of quorums, preventing adding more _deployMockEigenLayerAndAVS(0); - IRegistryCoordinator.OperatorSetParam memory operatorSetParams = - IRegistryCoordinator.OperatorSetParam({ - maxOperatorCount: defaultMaxOperatorCount, - kickBIPsOfOperatorStake: defaultKickBIPsOfOperatorStake, - kickBIPsOfTotalStake: defaultKickBIPsOfTotalStake - }); + IRegistryCoordinator.OperatorSetParam memory operatorSetParams = IRegistryCoordinator + .OperatorSetParam({ + maxOperatorCount: defaultMaxOperatorCount, + kickBIPsOfOperatorStake: defaultKickBIPsOfOperatorStake, + kickBIPsOfTotalStake: defaultKickBIPsOfTotalStake + }); uint96 minimumStake = 1; - IStakeRegistry.StrategyParams[] memory strategyParams = new IStakeRegistry.StrategyParams[](1); + IStakeRegistry.StrategyParams[] memory strategyParams = + new IStakeRegistry.StrategyParams[](1); strategyParams[0] = - IStakeRegistry.StrategyParams({ - strategy: IStrategy(address(1000)), - multiplier: 1e16 - }); + IStakeRegistry.StrategyParams({strategy: IStrategy(address(1000)), multiplier: 1e16}); uint8 quorumCountBefore = registryCoordinator.quorumCount(); cheats.expectEmit(true, true, true, true, address(registryCoordinator)); emit OperatorSetParamsUpdated(quorumCountBefore, operatorSetParams); cheats.prank(registryCoordinatorOwner); - registryCoordinator.createTotalDelegatedStakeQuorum(operatorSetParams, minimumStake, strategyParams); + registryCoordinator.createTotalDelegatedStakeQuorum( + operatorSetParams, minimumStake, strategyParams + ); uint8 quorumCountAfter = registryCoordinator.quorumCount(); assertEq(quorumCountAfter, quorumCountBefore + 1, "quorum count did not increase properly"); @@ -256,7 +258,6 @@ contract RegistryCoordinatorUnitTests_Initialization_Setters is RegistryCoordina } contract RegistryCoordinatorUnitTests_RegisterOperator is RegistryCoordinatorUnitTests { - function test_registerOperator_revert_paused() public { bytes memory emptyQuorumNumbers = new bytes(0); ISignatureUtils.SignatureWithSaltAndExpiry memory emptySig; @@ -267,7 +268,9 @@ contract RegistryCoordinatorUnitTests_RegisterOperator is RegistryCoordinatorUni cheats.startPrank(defaultOperator); cheats.expectRevert(bytes4(keccak256("CurrentlyPaused()"))); - registryCoordinator.registerOperator(emptyQuorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + emptyQuorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); } function test_registerOperator_revert_emptyQuorumNumbers() public { @@ -276,7 +279,9 @@ contract RegistryCoordinatorUnitTests_RegisterOperator is RegistryCoordinatorUni cheats.expectRevert(bytes4(keccak256("BitmapEmpty()"))); cheats.prank(defaultOperator); - registryCoordinator.registerOperator(emptyQuorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + emptyQuorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); } function test_registerOperator_revert_invalidQuorum() public { @@ -287,7 +292,9 @@ contract RegistryCoordinatorUnitTests_RegisterOperator is RegistryCoordinatorUni cheats.expectRevert(BitmapUtils.BitmapValueTooLarge.selector); cheats.prank(defaultOperator); - registryCoordinator.registerOperator(quorumNumbersTooLarge, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbersTooLarge, defaultSocket, pubkeyRegistrationParams, emptySig + ); } function test_registerOperator_revert_nonexistentQuorum() public { @@ -299,7 +306,9 @@ contract RegistryCoordinatorUnitTests_RegisterOperator is RegistryCoordinatorUni cheats.prank(defaultOperator); cheats.expectRevert(BitmapUtils.BitmapValueTooLarge.selector); - registryCoordinator.registerOperator(quorumNumbersNotCreated, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbersNotCreated, defaultSocket, pubkeyRegistrationParams, emptySig + ); } function test_registerOperator_singleQuorum() public { @@ -320,7 +329,9 @@ contract RegistryCoordinatorUnitTests_RegisterOperator is RegistryCoordinatorUni uint256 gasBefore = gasleft(); cheats.prank(defaultOperator); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); uint256 gasAfter = gasleft(); emit log_named_uint("gasUsed, register for single quorum", gasBefore - gasAfter); @@ -329,24 +340,36 @@ contract RegistryCoordinatorUnitTests_RegisterOperator is RegistryCoordinatorUni assertEq(registryCoordinator.getOperatorId(defaultOperator), defaultOperatorId); assertEq( keccak256(abi.encode(registryCoordinator.getOperator(defaultOperator))), - keccak256(abi.encode(IRegistryCoordinator.OperatorInfo({ - operatorId: defaultOperatorId, - status: IRegistryCoordinator.OperatorStatus.REGISTERED - }))) + keccak256( + abi.encode( + IRegistryCoordinator.OperatorInfo({ + operatorId: defaultOperatorId, + status: IRegistryCoordinator.OperatorStatus.REGISTERED + }) + ) + ) ); assertEq(registryCoordinator.getCurrentQuorumBitmap(defaultOperatorId), quorumBitmap); assertEq( - keccak256(abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0))), - keccak256(abi.encode(IRegistryCoordinator.QuorumBitmapUpdate({ - quorumBitmap: uint192(quorumBitmap), - updateBlockNumber: uint32(block.number), - nextUpdateBlockNumber: 0 - }))) + keccak256( + abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0)) + ), + keccak256( + abi.encode( + IRegistryCoordinator.QuorumBitmapUpdate({ + quorumBitmap: uint192(quorumBitmap), + updateBlockNumber: uint32(block.number), + nextUpdateBlockNumber: 0 + }) + ) + ) ); } // @notice tests registering an operator for a fuzzed assortment of quorums - function testFuzz_registerOperator(uint256 quorumBitmap) public { + function testFuzz_registerOperator( + uint256 quorumBitmap + ) public { // filter the fuzzed input down to only valid quorums quorumBitmap = quorumBitmap & MAX_QUORUM_BITMAP; ISignatureUtils.SignatureWithSaltAndExpiry memory emptySig; @@ -354,7 +377,7 @@ contract RegistryCoordinatorUnitTests_RegisterOperator is RegistryCoordinatorUni bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmap); uint96 actualStake; - for (uint i = 0; i < quorumNumbers.length; i++) { + for (uint256 i = 0; i < quorumNumbers.length; i++) { actualStake = _setOperatorWeight(defaultOperator, uint8(quorumNumbers[i]), defaultStake); } @@ -366,19 +389,21 @@ contract RegistryCoordinatorUnitTests_RegisterOperator is RegistryCoordinatorUni cheats.expectEmit(true, true, true, true, address(blsApkRegistry)); emit OperatorAddedToQuorums(defaultOperator, defaultOperatorId, quorumNumbers); - for (uint i = 0; i < quorumNumbers.length; i++) { + for (uint256 i = 0; i < quorumNumbers.length; i++) { cheats.expectEmit(true, true, true, true, address(stakeRegistry)); emit OperatorStakeUpdate(defaultOperatorId, uint8(quorumNumbers[i]), actualStake); } - for (uint i = 0; i < quorumNumbers.length; i++) { + for (uint256 i = 0; i < quorumNumbers.length; i++) { cheats.expectEmit(true, true, true, true, address(indexRegistry)); emit QuorumIndexUpdate(defaultOperatorId, uint8(quorumNumbers[i]), 0); } uint256 gasBefore = gasleft(); cheats.prank(defaultOperator); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); uint256 gasAfter = gasleft(); emit log_named_uint("gasUsed", gasBefore - gasAfter); emit log_named_uint("numQuorums", quorumNumbers.length); @@ -386,19 +411,29 @@ contract RegistryCoordinatorUnitTests_RegisterOperator is RegistryCoordinatorUni assertEq(registryCoordinator.getOperatorId(defaultOperator), defaultOperatorId); assertEq( keccak256(abi.encode(registryCoordinator.getOperator(defaultOperator))), - keccak256(abi.encode(IRegistryCoordinator.OperatorInfo({ - operatorId: defaultOperatorId, - status: IRegistryCoordinator.OperatorStatus.REGISTERED - }))) + keccak256( + abi.encode( + IRegistryCoordinator.OperatorInfo({ + operatorId: defaultOperatorId, + status: IRegistryCoordinator.OperatorStatus.REGISTERED + }) + ) + ) ); assertEq(registryCoordinator.getCurrentQuorumBitmap(defaultOperatorId), quorumBitmap); assertEq( - keccak256(abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0))), - keccak256(abi.encode(IRegistryCoordinator.QuorumBitmapUpdate({ - quorumBitmap: uint192(quorumBitmap), - updateBlockNumber: uint32(block.number), - nextUpdateBlockNumber: 0 - }))) + keccak256( + abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0)) + ), + keccak256( + abi.encode( + IRegistryCoordinator.QuorumBitmapUpdate({ + quorumBitmap: uint192(quorumBitmap), + updateBlockNumber: uint32(block.number), + nextUpdateBlockNumber: 0 + }) + ) + ) ); } @@ -414,12 +449,15 @@ contract RegistryCoordinatorUnitTests_RegisterOperator is RegistryCoordinatorUni _setOperatorWeight(defaultOperator, uint8(quorumNumbers[0]), defaultStake); cheats.prank(defaultOperator); cheats.roll(registrationBlockNumber); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); bytes memory newQuorumNumbers = new bytes(1); - newQuorumNumbers[0] = bytes1(defaultQuorumNumber+1); + newQuorumNumbers[0] = bytes1(defaultQuorumNumber + 1); - uint96 actualStake = _setOperatorWeight(defaultOperator, uint8(newQuorumNumbers[0]), defaultStake); + uint96 actualStake = + _setOperatorWeight(defaultOperator, uint8(newQuorumNumbers[0]), defaultStake); cheats.expectEmit(true, true, true, true, address(registryCoordinator)); emit OperatorSocketUpdate(defaultOperatorId, defaultSocket); cheats.expectEmit(true, true, true, true, address(blsApkRegistry)); @@ -430,38 +468,59 @@ contract RegistryCoordinatorUnitTests_RegisterOperator is RegistryCoordinatorUni emit QuorumIndexUpdate(defaultOperatorId, uint8(newQuorumNumbers[0]), 0); cheats.roll(nextRegistrationBlockNumber); cheats.prank(defaultOperator); - registryCoordinator.registerOperator(newQuorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + newQuorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); - uint256 quorumBitmap = BitmapUtils.orderedBytesArrayToBitmap(quorumNumbers) | BitmapUtils.orderedBytesArrayToBitmap(newQuorumNumbers); + uint256 quorumBitmap = BitmapUtils.orderedBytesArrayToBitmap(quorumNumbers) + | BitmapUtils.orderedBytesArrayToBitmap(newQuorumNumbers); assertEq(registryCoordinator.getOperatorId(defaultOperator), defaultOperatorId); assertEq( keccak256(abi.encode(registryCoordinator.getOperator(defaultOperator))), - keccak256(abi.encode(IRegistryCoordinator.OperatorInfo({ - operatorId: defaultOperatorId, - status: IRegistryCoordinator.OperatorStatus.REGISTERED - }))) + keccak256( + abi.encode( + IRegistryCoordinator.OperatorInfo({ + operatorId: defaultOperatorId, + status: IRegistryCoordinator.OperatorStatus.REGISTERED + }) + ) + ) ); assertEq(registryCoordinator.getCurrentQuorumBitmap(defaultOperatorId), quorumBitmap); assertEq( - keccak256(abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0))), - keccak256(abi.encode(IRegistryCoordinator.QuorumBitmapUpdate({ - quorumBitmap: uint192(BitmapUtils.orderedBytesArrayToBitmap(quorumNumbers)), - updateBlockNumber: uint32(registrationBlockNumber), - nextUpdateBlockNumber: uint32(nextRegistrationBlockNumber) - }))) + keccak256( + abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0)) + ), + keccak256( + abi.encode( + IRegistryCoordinator.QuorumBitmapUpdate({ + quorumBitmap: uint192(BitmapUtils.orderedBytesArrayToBitmap(quorumNumbers)), + updateBlockNumber: uint32(registrationBlockNumber), + nextUpdateBlockNumber: uint32(nextRegistrationBlockNumber) + }) + ) + ) ); assertEq( - keccak256(abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 1))), - keccak256(abi.encode(IRegistryCoordinator.QuorumBitmapUpdate({ - quorumBitmap: uint192(quorumBitmap), - updateBlockNumber: uint32(nextRegistrationBlockNumber), - nextUpdateBlockNumber: 0 - }))) + keccak256( + abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 1)) + ), + keccak256( + abi.encode( + IRegistryCoordinator.QuorumBitmapUpdate({ + quorumBitmap: uint192(quorumBitmap), + updateBlockNumber: uint32(nextRegistrationBlockNumber), + nextUpdateBlockNumber: 0 + }) + ) + ) ); } - function test_registerOperator_revert_overFilledQuorum(uint256 pseudoRandomNumber) public { + function test_registerOperator_revert_overFilledQuorum( + uint256 pseudoRandomNumber + ) public { uint32 numOperators = defaultMaxOperatorCount; uint32 registrationBlockNumber = 200; ISignatureUtils.SignatureWithSaltAndExpiry memory emptySig; @@ -473,15 +532,17 @@ contract RegistryCoordinatorUnitTests_RegisterOperator is RegistryCoordinatorUni cheats.roll(registrationBlockNumber); - for (uint i = 0; i < numOperators; i++) { - BN254.G1Point memory pubKey = BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, i))); + for (uint256 i = 0; i < numOperators; i++) { + BN254.G1Point memory pubKey = + BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, i))); address operator = _incrementAddress(defaultOperator, i); _registerOperatorWithCoordinator(operator, quorumBitmap, pubKey); } address operatorToRegister = _incrementAddress(defaultOperator, numOperators); - BN254.G1Point memory operatorToRegisterPubKey = BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, numOperators))); + BN254.G1Point memory operatorToRegisterPubKey = + BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, numOperators))); blsApkRegistry.setBLSPublicKey(operatorToRegister, operatorToRegisterPubKey); @@ -489,7 +550,9 @@ contract RegistryCoordinatorUnitTests_RegisterOperator is RegistryCoordinatorUni cheats.prank(operatorToRegister); cheats.expectRevert(bytes4(keccak256("MaxQuorumsReached()"))); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); } function test_registerOperator_revert_operatorAlreadyRegisteredForQuorum() public { @@ -504,12 +567,16 @@ contract RegistryCoordinatorUnitTests_RegisterOperator is RegistryCoordinatorUni cheats.prank(defaultOperator); cheats.roll(registrationBlockNumber); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); cheats.prank(defaultOperator); cheats.roll(nextRegistrationBlockNumber); cheats.expectRevert(bytes4(keccak256("AlreadyRegisteredForQuorums()"))); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); } // tests for the internal `_registerOperator` function: @@ -518,7 +585,9 @@ contract RegistryCoordinatorUnitTests_RegisterOperator is RegistryCoordinatorUni ISignatureUtils.SignatureWithSaltAndExpiry memory emptySig; cheats.expectRevert(bytes4(keccak256("BitmapEmpty()"))); - registryCoordinator._registerOperatorExternal(defaultOperator, defaultOperatorId, emptyQuorumNumbers, defaultSocket, emptySig); + registryCoordinator._registerOperatorExternal( + defaultOperator, defaultOperatorId, emptyQuorumNumbers, defaultSocket, emptySig + ); } function test_registerOperatorInternal_revert_nonexistentQuorum() public { @@ -528,7 +597,9 @@ contract RegistryCoordinatorUnitTests_RegisterOperator is RegistryCoordinatorUni quorumNumbersTooLarge[0] = 0xC0; cheats.expectRevert(BitmapUtils.BitmapValueTooLarge.selector); - registryCoordinator._registerOperatorExternal(defaultOperator, defaultOperatorId, quorumNumbersTooLarge, defaultSocket, emptySig); + registryCoordinator._registerOperatorExternal( + defaultOperator, defaultOperatorId, quorumNumbersTooLarge, defaultSocket, emptySig + ); } function test_registerOperatorInternal_revert_operatorAlreadyRegisteredForQuorum() public { @@ -537,10 +608,14 @@ contract RegistryCoordinatorUnitTests_RegisterOperator is RegistryCoordinatorUni quorumNumbers[0] = bytes1(defaultQuorumNumber); _setOperatorWeight(defaultOperator, uint8(quorumNumbers[0]), defaultStake); - registryCoordinator._registerOperatorExternal(defaultOperator, defaultOperatorId, quorumNumbers, defaultSocket, emptySig); + registryCoordinator._registerOperatorExternal( + defaultOperator, defaultOperatorId, quorumNumbers, defaultSocket, emptySig + ); cheats.expectRevert(bytes4(keccak256("AlreadyRegisteredForQuorums()"))); - registryCoordinator._registerOperatorExternal(defaultOperator, defaultOperatorId, quorumNumbers, defaultSocket, emptySig); + registryCoordinator._registerOperatorExternal( + defaultOperator, defaultOperatorId, quorumNumbers, defaultSocket, emptySig + ); } function test_registerOperatorInternal() public { @@ -559,32 +634,46 @@ contract RegistryCoordinatorUnitTests_RegisterOperator is RegistryCoordinatorUni cheats.expectEmit(true, true, true, true, address(indexRegistry)); emit QuorumIndexUpdate(defaultOperatorId, defaultQuorumNumber, 0); - registryCoordinator._registerOperatorExternal(defaultOperator, defaultOperatorId, quorumNumbers, defaultSocket, emptySig); + registryCoordinator._registerOperatorExternal( + defaultOperator, defaultOperatorId, quorumNumbers, defaultSocket, emptySig + ); uint256 quorumBitmap = BitmapUtils.orderedBytesArrayToBitmap(quorumNumbers); assertEq(registryCoordinator.getOperatorId(defaultOperator), defaultOperatorId); assertEq( keccak256(abi.encode(registryCoordinator.getOperator(defaultOperator))), - keccak256(abi.encode(IRegistryCoordinator.OperatorInfo({ - operatorId: defaultOperatorId, - status: IRegistryCoordinator.OperatorStatus.REGISTERED - }))) + keccak256( + abi.encode( + IRegistryCoordinator.OperatorInfo({ + operatorId: defaultOperatorId, + status: IRegistryCoordinator.OperatorStatus.REGISTERED + }) + ) + ) ); assertEq(registryCoordinator.getCurrentQuorumBitmap(defaultOperatorId), quorumBitmap); assertEq( - keccak256(abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0))), - keccak256(abi.encode(IRegistryCoordinator.QuorumBitmapUpdate({ - quorumBitmap: uint192(quorumBitmap), - updateBlockNumber: uint32(block.number), - nextUpdateBlockNumber: 0 - }))) + keccak256( + abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0)) + ), + keccak256( + abi.encode( + IRegistryCoordinator.QuorumBitmapUpdate({ + quorumBitmap: uint192(quorumBitmap), + updateBlockNumber: uint32(block.number), + nextUpdateBlockNumber: 0 + }) + ) + ) ); } } // @dev note that this contract also contains tests for the `getQuorumBitmapIndicesAtBlockNumber` and `getQuorumBitmapAtBlockNumberByIndex` view fncs -contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is RegistryCoordinatorUnitTests { +contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is + RegistryCoordinatorUnitTests +{ function test_deregisterOperator_revert_paused() public { bytes memory quorumNumbers = new bytes(1); quorumNumbers[0] = bytes1(defaultQuorumNumber); @@ -641,7 +730,9 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist cheats.roll(registrationBlockNumber); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); uint256 quorumBitmap = BitmapUtils.orderedBytesArrayToBitmap(quorumNumbers); @@ -659,25 +750,37 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist assertEq( keccak256(abi.encode(registryCoordinator.getOperator(defaultOperator))), - keccak256(abi.encode(IRegistryCoordinator.OperatorInfo({ - operatorId: defaultOperatorId, - status: IRegistryCoordinator.OperatorStatus.DEREGISTERED - }))) + keccak256( + abi.encode( + IRegistryCoordinator.OperatorInfo({ + operatorId: defaultOperatorId, + status: IRegistryCoordinator.OperatorStatus.DEREGISTERED + }) + ) + ) ); assertEq(registryCoordinator.getCurrentQuorumBitmap(defaultOperatorId), 0); assertEq( - keccak256(abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0))), - keccak256(abi.encode(IRegistryCoordinator.QuorumBitmapUpdate({ - quorumBitmap: uint192(quorumBitmap), - updateBlockNumber: registrationBlockNumber, - nextUpdateBlockNumber: deregistrationBlockNumber - }))) + keccak256( + abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0)) + ), + keccak256( + abi.encode( + IRegistryCoordinator.QuorumBitmapUpdate({ + quorumBitmap: uint192(quorumBitmap), + updateBlockNumber: registrationBlockNumber, + nextUpdateBlockNumber: deregistrationBlockNumber + }) + ) + ) ); } // @notice verifies that an operator who was registered for a fuzzed set of quorums can be deregistered // @dev deregisters the operator from *all* quorums for which they we registered. - function testFuzz_deregisterOperator_fuzzedQuorumAndSingleOperator(uint256 quorumBitmap) public { + function testFuzz_deregisterOperator_fuzzedQuorumAndSingleOperator( + uint256 quorumBitmap + ) public { ISignatureUtils.SignatureWithSaltAndExpiry memory emptySig; uint32 registrationBlockNumber = 100; uint32 deregistrationBlockNumber = 200; @@ -687,7 +790,7 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist cheats.assume(quorumBitmap != 0); bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmap); - for (uint i = 0; i < quorumNumbers.length; i++) { + for (uint256 i = 0; i < quorumNumbers.length; i++) { _setOperatorWeight(defaultOperator, uint8(quorumNumbers[i]), defaultStake); } @@ -695,11 +798,13 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist cheats.roll(registrationBlockNumber); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); cheats.expectEmit(true, true, true, true, address(blsApkRegistry)); emit OperatorRemovedFromQuorums(defaultOperator, defaultOperatorId, quorumNumbers); - for (uint i = 0; i < quorumNumbers.length; i++) { + for (uint256 i = 0; i < quorumNumbers.length; i++) { cheats.expectEmit(true, true, true, true, address(stakeRegistry)); emit OperatorStakeUpdate(defaultOperatorId, uint8(quorumNumbers[i]), 0); } @@ -714,23 +819,34 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist assertEq( keccak256(abi.encode(registryCoordinator.getOperator(defaultOperator))), - keccak256(abi.encode(IRegistryCoordinator.OperatorInfo({ - operatorId: defaultOperatorId, - status: IRegistryCoordinator.OperatorStatus.DEREGISTERED - }))) + keccak256( + abi.encode( + IRegistryCoordinator.OperatorInfo({ + operatorId: defaultOperatorId, + status: IRegistryCoordinator.OperatorStatus.DEREGISTERED + }) + ) + ) ); assertEq(registryCoordinator.getCurrentQuorumBitmap(defaultOperatorId), 0); assertEq( - keccak256(abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0))), - keccak256(abi.encode(IRegistryCoordinator.QuorumBitmapUpdate({ - quorumBitmap: uint192(quorumBitmap), - updateBlockNumber: registrationBlockNumber, - nextUpdateBlockNumber: deregistrationBlockNumber - }))) + keccak256( + abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0)) + ), + keccak256( + abi.encode( + IRegistryCoordinator.QuorumBitmapUpdate({ + quorumBitmap: uint192(quorumBitmap), + updateBlockNumber: registrationBlockNumber, + nextUpdateBlockNumber: deregistrationBlockNumber + }) + ) + ) ); } // @notice verifies that an operator who was registered for a fuzzed set of quorums can be deregistered from a subset of those quorums // @dev deregisters the operator from a fuzzed subset of the quorums for which they we registered. + function testFuzz_deregisterOperator_singleOperator_partialDeregistration( uint256 registrationQuorumBitmap, uint256 deregistrationQuorumBitmap @@ -745,9 +861,10 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist // filter the other fuzzed input to a subset of the first fuzzed input deregistrationQuorumBitmap = deregistrationQuorumBitmap & registrationQuorumBitmap; cheats.assume(deregistrationQuorumBitmap != 0); - bytes memory registrationquorumNumbers = BitmapUtils.bitmapToBytesArray(registrationQuorumBitmap); + bytes memory registrationquorumNumbers = + BitmapUtils.bitmapToBytesArray(registrationQuorumBitmap); - for (uint i = 0; i < registrationquorumNumbers.length; i++) { + for (uint256 i = 0; i < registrationquorumNumbers.length; i++) { _setOperatorWeight(defaultOperator, uint8(registrationquorumNumbers[i]), defaultStake); } @@ -755,13 +872,18 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist cheats.roll(registrationBlockNumber); - registryCoordinator.registerOperator(registrationquorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + registrationquorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); - bytes memory deregistrationquorumNumbers = BitmapUtils.bitmapToBytesArray(deregistrationQuorumBitmap); + bytes memory deregistrationquorumNumbers = + BitmapUtils.bitmapToBytesArray(deregistrationQuorumBitmap); cheats.expectEmit(true, true, true, true, address(blsApkRegistry)); - emit OperatorRemovedFromQuorums(defaultOperator, defaultOperatorId, deregistrationquorumNumbers); - for (uint i = 0; i < deregistrationquorumNumbers.length; i++) { + emit OperatorRemovedFromQuorums( + defaultOperator, defaultOperatorId, deregistrationquorumNumbers + ); + for (uint256 i = 0; i < deregistrationquorumNumbers.length; i++) { cheats.expectEmit(true, true, true, true, address(stakeRegistry)); emit OperatorStakeUpdate(defaultOperatorId, uint8(deregistrationquorumNumbers[i]), 0); } @@ -778,47 +900,74 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist if (deregistrationQuorumBitmap == registrationQuorumBitmap) { assertEq( keccak256(abi.encode(registryCoordinator.getOperator(defaultOperator))), - keccak256(abi.encode(IRegistryCoordinator.OperatorInfo({ - operatorId: defaultOperatorId, - status: IRegistryCoordinator.OperatorStatus.DEREGISTERED - }))) + keccak256( + abi.encode( + IRegistryCoordinator.OperatorInfo({ + operatorId: defaultOperatorId, + status: IRegistryCoordinator.OperatorStatus.DEREGISTERED + }) + ) + ) ); } else { assertEq( keccak256(abi.encode(registryCoordinator.getOperator(defaultOperator))), - keccak256(abi.encode(IRegistryCoordinator.OperatorInfo({ - operatorId: defaultOperatorId, - status: IRegistryCoordinator.OperatorStatus.REGISTERED - }))) + keccak256( + abi.encode( + IRegistryCoordinator.OperatorInfo({ + operatorId: defaultOperatorId, + status: IRegistryCoordinator.OperatorStatus.REGISTERED + }) + ) + ) ); } // ensure that the operator's current quorum bitmap matches the expectation - uint256 expectedQuorumBitmap = BitmapUtils.minus(registrationQuorumBitmap, deregistrationQuorumBitmap); - assertEq(registryCoordinator.getCurrentQuorumBitmap(defaultOperatorId), expectedQuorumBitmap); + uint256 expectedQuorumBitmap = + BitmapUtils.minus(registrationQuorumBitmap, deregistrationQuorumBitmap); + assertEq( + registryCoordinator.getCurrentQuorumBitmap(defaultOperatorId), expectedQuorumBitmap + ); // check that the quorum bitmap history is as expected assertEq( - keccak256(abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0))), - keccak256(abi.encode(IRegistryCoordinator.QuorumBitmapUpdate({ - quorumBitmap: uint192(registrationQuorumBitmap), - updateBlockNumber: registrationBlockNumber, - nextUpdateBlockNumber: deregistrationBlockNumber - }))) + keccak256( + abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0)) + ), + keccak256( + abi.encode( + IRegistryCoordinator.QuorumBitmapUpdate({ + quorumBitmap: uint192(registrationQuorumBitmap), + updateBlockNumber: registrationBlockNumber, + nextUpdateBlockNumber: deregistrationBlockNumber + }) + ) + ) ); // note: there will be no second entry in the operator's bitmap history in the event that the operator has totally deregistered if (deregistrationQuorumBitmap != registrationQuorumBitmap) { assertEq( - keccak256(abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 1))), - keccak256(abi.encode(IRegistryCoordinator.QuorumBitmapUpdate({ - quorumBitmap: uint192(expectedQuorumBitmap), - updateBlockNumber: deregistrationBlockNumber, - nextUpdateBlockNumber: 0 - }))) + keccak256( + abi.encode( + registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 1) + ) + ), + keccak256( + abi.encode( + IRegistryCoordinator.QuorumBitmapUpdate({ + quorumBitmap: uint192(expectedQuorumBitmap), + updateBlockNumber: deregistrationBlockNumber, + nextUpdateBlockNumber: 0 + }) + ) + ) ); } } // @notice registers the max number of operators with fuzzed bitmaps and then deregisters a pseudorandom operator (from all of their quorums) - function testFuzz_deregisterOperator_manyOperators(uint256 pseudoRandomNumber) public { + function testFuzz_deregisterOperator_manyOperators( + uint256 pseudoRandomNumber + ) public { uint32 numOperators = defaultMaxOperatorCount; uint32 registrationBlockNumber = 100; @@ -826,17 +975,20 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist // pad quorumBitmap with 1 until it has numOperators elements uint256[] memory quorumBitmaps = new uint256[](numOperators); - for (uint i = 0; i < numOperators; i++) { + for (uint256 i = 0; i < numOperators; i++) { // limit to maxQuorumsToRegisterFor quorums via mask so we don't run out of gas, make them all register for quorum 0 as well - quorumBitmaps[i] = uint256(keccak256(abi.encodePacked("quorumBitmap", pseudoRandomNumber, i))) & (1 << maxQuorumsToRegisterFor - 1) | 1; + quorumBitmaps[i] = uint256( + keccak256(abi.encodePacked("quorumBitmap", pseudoRandomNumber, i)) + ) & (1 << maxQuorumsToRegisterFor - 1) | 1; } cheats.roll(registrationBlockNumber); bytes32[] memory lastOperatorInQuorum = new bytes32[](numQuorums); - for (uint i = 0; i < numOperators; i++) { + for (uint256 i = 0; i < numOperators; i++) { emit log_named_uint("i", i); - BN254.G1Point memory pubKey = BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, i))); + BN254.G1Point memory pubKey = + BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, i))); bytes32 operatorId = BN254.hashG1Point(pubKey); address operator = _incrementAddress(defaultOperator, i); @@ -844,29 +996,37 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist // for each quorum the operator is in, save the operatorId bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmaps[i]); - for (uint j = 0; j < quorumNumbers.length; j++) { + for (uint256 j = 0; j < quorumNumbers.length; j++) { lastOperatorInQuorum[uint8(quorumNumbers[j])] = operatorId; } } uint256 indexOfOperatorToDeregister = pseudoRandomNumber % numOperators; - address operatorToDeregister = _incrementAddress(defaultOperator, indexOfOperatorToDeregister); - BN254.G1Point memory operatorToDeregisterPubKey = BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, indexOfOperatorToDeregister))); + address operatorToDeregister = + _incrementAddress(defaultOperator, indexOfOperatorToDeregister); + BN254.G1Point memory operatorToDeregisterPubKey = BN254.hashToG1( + keccak256(abi.encodePacked(pseudoRandomNumber, indexOfOperatorToDeregister)) + ); bytes32 operatorToDeregisterId = BN254.hashG1Point(operatorToDeregisterPubKey); uint256 operatorToDeregisterQuorumBitmap = quorumBitmaps[indexOfOperatorToDeregister]; - bytes memory operatorToDeregisterQuorumNumbers = BitmapUtils.bitmapToBytesArray(operatorToDeregisterQuorumBitmap); + bytes memory operatorToDeregisterQuorumNumbers = + BitmapUtils.bitmapToBytesArray(operatorToDeregisterQuorumBitmap); bytes32[] memory operatorIdsToSwap = new bytes32[](operatorToDeregisterQuorumNumbers.length); - for (uint i = 0; i < operatorToDeregisterQuorumNumbers.length; i++) { + for (uint256 i = 0; i < operatorToDeregisterQuorumNumbers.length; i++) { operatorIdsToSwap[i] = lastOperatorInQuorum[uint8(operatorToDeregisterQuorumNumbers[i])]; } cheats.expectEmit(true, true, true, true, address(blsApkRegistry)); - emit OperatorRemovedFromQuorums(operatorToDeregister, operatorToDeregisterId, operatorToDeregisterQuorumNumbers); + emit OperatorRemovedFromQuorums( + operatorToDeregister, operatorToDeregisterId, operatorToDeregisterQuorumNumbers + ); - for (uint i = 0; i < operatorToDeregisterQuorumNumbers.length; i++) { + for (uint256 i = 0; i < operatorToDeregisterQuorumNumbers.length; i++) { cheats.expectEmit(true, true, true, true, address(stakeRegistry)); - emit OperatorStakeUpdate(operatorToDeregisterId, uint8(operatorToDeregisterQuorumNumbers[i]), 0); + emit OperatorStakeUpdate( + operatorToDeregisterId, uint8(operatorToDeregisterQuorumNumbers[i]), 0 + ); } cheats.roll(deregistrationBlockNumber); @@ -876,19 +1036,31 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist assertEq( keccak256(abi.encode(registryCoordinator.getOperator(operatorToDeregister))), - keccak256(abi.encode(IRegistryCoordinator.OperatorInfo({ - operatorId: operatorToDeregisterId, - status: IRegistryCoordinator.OperatorStatus.DEREGISTERED - }))) + keccak256( + abi.encode( + IRegistryCoordinator.OperatorInfo({ + operatorId: operatorToDeregisterId, + status: IRegistryCoordinator.OperatorStatus.DEREGISTERED + }) + ) + ) ); assertEq(registryCoordinator.getCurrentQuorumBitmap(defaultOperatorId), 0); assertEq( - keccak256(abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(operatorToDeregisterId, 0))), - keccak256(abi.encode(IRegistryCoordinator.QuorumBitmapUpdate({ - quorumBitmap: uint192(operatorToDeregisterQuorumBitmap), - updateBlockNumber: registrationBlockNumber, - nextUpdateBlockNumber: deregistrationBlockNumber - }))) + keccak256( + abi.encode( + registryCoordinator.getQuorumBitmapUpdateByIndex(operatorToDeregisterId, 0) + ) + ), + keccak256( + abi.encode( + IRegistryCoordinator.QuorumBitmapUpdate({ + quorumBitmap: uint192(operatorToDeregisterQuorumBitmap), + updateBlockNumber: registrationBlockNumber, + nextUpdateBlockNumber: deregistrationBlockNumber + }) + ) + ) ); } @@ -911,34 +1083,52 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0); // re-register the operator - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); // check success of registration uint256 quorumBitmap = BitmapUtils.orderedBytesArrayToBitmap(quorumNumbers); assertEq(registryCoordinator.getOperatorId(defaultOperator), defaultOperatorId, "1"); assertEq( keccak256(abi.encode(registryCoordinator.getOperator(defaultOperator))), - keccak256(abi.encode(IRegistryCoordinator.OperatorInfo({ - operatorId: defaultOperatorId, - status: IRegistryCoordinator.OperatorStatus.REGISTERED - }))), + keccak256( + abi.encode( + IRegistryCoordinator.OperatorInfo({ + operatorId: defaultOperatorId, + status: IRegistryCoordinator.OperatorStatus.REGISTERED + }) + ) + ), "2" ); assertEq(registryCoordinator.getCurrentQuorumBitmap(defaultOperatorId), quorumBitmap, "3"); // check that previous entry in bitmap history was not changed assertEq( - keccak256(abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0))), + keccak256( + abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0)) + ), keccak256(abi.encode(previousQuorumBitmapUpdate)), "4" ); // check that new entry in bitmap history is as expected - uint historyLength = registryCoordinator.getQuorumBitmapHistoryLength(defaultOperatorId); + uint256 historyLength = registryCoordinator.getQuorumBitmapHistoryLength(defaultOperatorId); assertEq( - keccak256(abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, historyLength - 1))), - keccak256(abi.encode(IRegistryCoordinator.QuorumBitmapUpdate({ - quorumBitmap: uint192(quorumBitmap), - updateBlockNumber: uint32(reregistrationBlockNumber), - nextUpdateBlockNumber: 0 - }))), + keccak256( + abi.encode( + registryCoordinator.getQuorumBitmapUpdateByIndex( + defaultOperatorId, historyLength - 1 + ) + ) + ), + keccak256( + abi.encode( + IRegistryCoordinator.QuorumBitmapUpdate({ + quorumBitmap: uint192(quorumBitmap), + updateBlockNumber: uint32(reregistrationBlockNumber), + nextUpdateBlockNumber: 0 + }) + ) + ), "5" ); } @@ -956,7 +1146,9 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist cheats.roll(registrationBlockNumber); cheats.startPrank(defaultOperator); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); bytes memory emptyQuorumNumbers = new bytes(0); @@ -983,7 +1175,9 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist cheats.roll(registrationBlockNumber); cheats.startPrank(defaultOperator); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); bytes memory incorrectQuorum = new bytes(1); incorrectQuorum[0] = bytes1(defaultQuorumNumber + 1); @@ -1010,7 +1204,9 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist cheats.prank(defaultOperator); cheats.roll(registrationBlockNumber); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); cheats.prank(ejector); registryCoordinator.ejectOperator(defaultOperator, quorumNumbers); @@ -1018,7 +1214,9 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist cheats.prank(defaultOperator); cheats.roll(reregistrationBlockNumber); cheats.expectRevert(bytes4(keccak256("CannotReregisterYet()"))); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); } function test_reregisterOperator_reregistrationDelay() public { @@ -1038,7 +1236,9 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist cheats.prank(defaultOperator); cheats.roll(registrationBlockNumber); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); cheats.prank(ejector); registryCoordinator.ejectOperator(defaultOperator, quorumNumbers); @@ -1046,7 +1246,9 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist cheats.prank(defaultOperator); cheats.roll(reregistrationBlockNumber); cheats.warp(block.timestamp + reregistrationDelay + 1); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); } // note: this is not possible to test, because there is no route to getting the operator registered for nonexistent quorums @@ -1066,68 +1268,101 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist // filter the other fuzzed input to a subset of the first fuzzed input deregistrationQuorumBitmap = deregistrationQuorumBitmap & registrationQuorumBitmap; cheats.assume(deregistrationQuorumBitmap != 0); - bytes memory registrationquorumNumbers = BitmapUtils.bitmapToBytesArray(registrationQuorumBitmap); + bytes memory registrationquorumNumbers = + BitmapUtils.bitmapToBytesArray(registrationQuorumBitmap); - for (uint i = 0; i < registrationquorumNumbers.length; i++) { + for (uint256 i = 0; i < registrationquorumNumbers.length; i++) { _setOperatorWeight(defaultOperator, uint8(registrationquorumNumbers[i]), defaultStake); } cheats.roll(registrationBlockNumber); cheats.startPrank(defaultOperator); - registryCoordinator.registerOperator(registrationquorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + registrationquorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); - bytes memory deregistrationquorumNumbers = BitmapUtils.bitmapToBytesArray(deregistrationQuorumBitmap); + bytes memory deregistrationquorumNumbers = + BitmapUtils.bitmapToBytesArray(deregistrationQuorumBitmap); cheats.expectEmit(true, true, true, true, address(blsApkRegistry)); - emit OperatorRemovedFromQuorums(defaultOperator, defaultOperatorId, deregistrationquorumNumbers); - for (uint i = 0; i < deregistrationquorumNumbers.length; i++) { + emit OperatorRemovedFromQuorums( + defaultOperator, defaultOperatorId, deregistrationquorumNumbers + ); + for (uint256 i = 0; i < deregistrationquorumNumbers.length; i++) { cheats.expectEmit(true, true, true, true, address(stakeRegistry)); emit OperatorStakeUpdate(defaultOperatorId, uint8(deregistrationquorumNumbers[i]), 0); } cheats.roll(deregistrationBlockNumber); - registryCoordinator._deregisterOperatorExternal(defaultOperator, deregistrationquorumNumbers); + registryCoordinator._deregisterOperatorExternal( + defaultOperator, deregistrationquorumNumbers + ); // check that the operator is marked as 'degregistered' only if deregistered from *all* quorums if (deregistrationQuorumBitmap == registrationQuorumBitmap) { assertEq( keccak256(abi.encode(registryCoordinator.getOperator(defaultOperator))), - keccak256(abi.encode(IRegistryCoordinator.OperatorInfo({ - operatorId: defaultOperatorId, - status: IRegistryCoordinator.OperatorStatus.DEREGISTERED - }))) + keccak256( + abi.encode( + IRegistryCoordinator.OperatorInfo({ + operatorId: defaultOperatorId, + status: IRegistryCoordinator.OperatorStatus.DEREGISTERED + }) + ) + ) ); } else { assertEq( keccak256(abi.encode(registryCoordinator.getOperator(defaultOperator))), - keccak256(abi.encode(IRegistryCoordinator.OperatorInfo({ - operatorId: defaultOperatorId, - status: IRegistryCoordinator.OperatorStatus.REGISTERED - }))) + keccak256( + abi.encode( + IRegistryCoordinator.OperatorInfo({ + operatorId: defaultOperatorId, + status: IRegistryCoordinator.OperatorStatus.REGISTERED + }) + ) + ) ); } // ensure that the operator's current quorum bitmap matches the expectation - uint256 expectedQuorumBitmap = BitmapUtils.minus(registrationQuorumBitmap, deregistrationQuorumBitmap); - assertEq(registryCoordinator.getCurrentQuorumBitmap(defaultOperatorId), expectedQuorumBitmap); + uint256 expectedQuorumBitmap = + BitmapUtils.minus(registrationQuorumBitmap, deregistrationQuorumBitmap); + assertEq( + registryCoordinator.getCurrentQuorumBitmap(defaultOperatorId), expectedQuorumBitmap + ); // check that the quorum bitmap history is as expected assertEq( - keccak256(abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0))), - keccak256(abi.encode(IRegistryCoordinator.QuorumBitmapUpdate({ - quorumBitmap: uint192(registrationQuorumBitmap), - updateBlockNumber: registrationBlockNumber, - nextUpdateBlockNumber: deregistrationBlockNumber - }))) + keccak256( + abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0)) + ), + keccak256( + abi.encode( + IRegistryCoordinator.QuorumBitmapUpdate({ + quorumBitmap: uint192(registrationQuorumBitmap), + updateBlockNumber: registrationBlockNumber, + nextUpdateBlockNumber: deregistrationBlockNumber + }) + ) + ) ); // note: there will be no second entry in the operator's bitmap history in the event that the operator has totally deregistered if (deregistrationQuorumBitmap != registrationQuorumBitmap) { assertEq( - keccak256(abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 1))), - keccak256(abi.encode(IRegistryCoordinator.QuorumBitmapUpdate({ - quorumBitmap: uint192(expectedQuorumBitmap), - updateBlockNumber: deregistrationBlockNumber, - nextUpdateBlockNumber: 0 - }))) + keccak256( + abi.encode( + registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 1) + ) + ), + keccak256( + abi.encode( + IRegistryCoordinator.QuorumBitmapUpdate({ + quorumBitmap: uint192(expectedQuorumBitmap), + updateBlockNumber: deregistrationBlockNumber, + nextUpdateBlockNumber: 0 + }) + ) + ) ); } } @@ -1141,7 +1376,9 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist _setOperatorWeight(defaultOperator, uint8(quorumNumbers[0]), defaultStake); cheats.prank(defaultOperator); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); cheats.expectEmit(true, true, true, true, address(blsApkRegistry)); emit OperatorRemovedFromQuorums(defaultOperator, defaultOperatorId, quorumNumbers); @@ -1156,10 +1393,14 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist // make sure the operator is deregistered assertEq( keccak256(abi.encode(registryCoordinator.getOperator(defaultOperator))), - keccak256(abi.encode(IRegistryCoordinator.OperatorInfo({ - operatorId: defaultOperatorId, - status: IRegistryCoordinator.OperatorStatus.DEREGISTERED - }))) + keccak256( + abi.encode( + IRegistryCoordinator.OperatorInfo({ + operatorId: defaultOperatorId, + status: IRegistryCoordinator.OperatorStatus.DEREGISTERED + }) + ) + ) ); // make sure the operator is not in any quorums assertEq(registryCoordinator.getCurrentQuorumBitmap(defaultOperatorId), 0); @@ -1172,12 +1413,14 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist quorumNumbers[1] = bytes1(defaultQuorumNumber + 1); ISignatureUtils.SignatureWithSaltAndExpiry memory emptySig; - for (uint i = 0; i < quorumNumbers.length; i++) { + for (uint256 i = 0; i < quorumNumbers.length; i++) { _setOperatorWeight(defaultOperator, uint8(quorumNumbers[i]), defaultStake); } cheats.prank(defaultOperator); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); // eject from only first quorum bytes memory quorumNumbersToEject = new bytes(1); @@ -1195,16 +1438,21 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist // make sure the operator is registered assertEq( keccak256(abi.encode(registryCoordinator.getOperator(defaultOperator))), - keccak256(abi.encode(IRegistryCoordinator.OperatorInfo({ - operatorId: defaultOperatorId, - status: IRegistryCoordinator.OperatorStatus.REGISTERED - }))) + keccak256( + abi.encode( + IRegistryCoordinator.OperatorInfo({ + operatorId: defaultOperatorId, + status: IRegistryCoordinator.OperatorStatus.REGISTERED + }) + ) + ) ); // make sure the operator is properly removed from the quorums assertEq( registryCoordinator.getCurrentQuorumBitmap(defaultOperatorId), // quorumsRegisteredFor & ~quorumsEjectedFrom - BitmapUtils.orderedBytesArrayToBitmap(quorumNumbers) & ~BitmapUtils.orderedBytesArrayToBitmap(quorumNumbersToEject) + BitmapUtils.orderedBytesArrayToBitmap(quorumNumbers) + & ~BitmapUtils.orderedBytesArrayToBitmap(quorumNumbersToEject) ); } @@ -1216,7 +1464,9 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist _setOperatorWeight(defaultOperator, uint8(quorumNumbers[0]), defaultStake); cheats.prank(defaultOperator); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); cheats.expectRevert(bytes4(keccak256("OnlyEjector()"))); cheats.prank(defaultOperator); @@ -1226,7 +1476,9 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist function test_getQuorumBitmapIndicesAtBlockNumber_revert_notRegistered() public { uint32 blockNumber; bytes32[] memory operatorIds = new bytes32[](1); - cheats.expectRevert("RegistryCoordinator.getQuorumBitmapIndexAtBlockNumber: no bitmap update found for operatorId"); + cheats.expectRevert( + "RegistryCoordinator.getQuorumBitmapIndexAtBlockNumber: no bitmap update found for operatorId" + ); registryCoordinator.getQuorumBitmapIndicesAtBlockNumber(blockNumber, operatorIds); } @@ -1240,23 +1492,37 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist _setOperatorWeight(defaultOperator, uint8(quorumNumbers[0]), defaultStake); cheats.roll(registrationBlockNumber); cheats.startPrank(defaultOperator); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); uint32 blockNumber = 0; bytes32[] memory operatorIds = new bytes32[](1); operatorIds[0] = defaultOperatorId; uint32[] memory returnArray; - cheats.expectRevert("RegistryCoordinator.getQuorumBitmapIndexAtBlockNumber: no bitmap update found for operatorId"); + cheats.expectRevert( + "RegistryCoordinator.getQuorumBitmapIndexAtBlockNumber: no bitmap update found for operatorId" + ); registryCoordinator.getQuorumBitmapIndicesAtBlockNumber(blockNumber, operatorIds); blockNumber = registrationBlockNumber; - returnArray = registryCoordinator.getQuorumBitmapIndicesAtBlockNumber(blockNumber, operatorIds); - assertEq(returnArray[0], 0, "defaultOperator bitmap index at blockNumber registrationBlockNumber was not 0"); + returnArray = + registryCoordinator.getQuorumBitmapIndicesAtBlockNumber(blockNumber, operatorIds); + assertEq( + returnArray[0], + 0, + "defaultOperator bitmap index at blockNumber registrationBlockNumber was not 0" + ); blockNumber = registrationBlockNumber + 1; - returnArray = registryCoordinator.getQuorumBitmapIndicesAtBlockNumber(blockNumber, operatorIds); - assertEq(returnArray[0], 0, "defaultOperator bitmap index at blockNumber registrationBlockNumber + 1 was not 0"); + returnArray = + registryCoordinator.getQuorumBitmapIndicesAtBlockNumber(blockNumber, operatorIds); + assertEq( + returnArray[0], + 0, + "defaultOperator bitmap index at blockNumber registrationBlockNumber + 1 was not 0" + ); } // @notice tests for correct reversion and return values in the event that an operator registers and later deregisters @@ -1269,24 +1535,46 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist operatorIds[0] = defaultOperatorId; uint32[] memory returnArray; - cheats.expectRevert("RegistryCoordinator.getQuorumBitmapIndexAtBlockNumber: no bitmap update found for operatorId"); + cheats.expectRevert( + "RegistryCoordinator.getQuorumBitmapIndexAtBlockNumber: no bitmap update found for operatorId" + ); registryCoordinator.getQuorumBitmapIndicesAtBlockNumber(blockNumber, operatorIds); blockNumber = registrationBlockNumber; - returnArray = registryCoordinator.getQuorumBitmapIndicesAtBlockNumber(blockNumber, operatorIds); - assertEq(returnArray[0], 0, "defaultOperator bitmap index at blockNumber registrationBlockNumber was not 0"); + returnArray = + registryCoordinator.getQuorumBitmapIndicesAtBlockNumber(blockNumber, operatorIds); + assertEq( + returnArray[0], + 0, + "defaultOperator bitmap index at blockNumber registrationBlockNumber was not 0" + ); blockNumber = registrationBlockNumber + 1; - returnArray = registryCoordinator.getQuorumBitmapIndicesAtBlockNumber(blockNumber, operatorIds); - assertEq(returnArray[0], 0, "defaultOperator bitmap index at blockNumber registrationBlockNumber + 1 was not 0"); + returnArray = + registryCoordinator.getQuorumBitmapIndicesAtBlockNumber(blockNumber, operatorIds); + assertEq( + returnArray[0], + 0, + "defaultOperator bitmap index at blockNumber registrationBlockNumber + 1 was not 0" + ); blockNumber = deregistrationBlockNumber; - returnArray = registryCoordinator.getQuorumBitmapIndicesAtBlockNumber(blockNumber, operatorIds); - assertEq(returnArray[0], 1, "defaultOperator bitmap index at blockNumber deregistrationBlockNumber was not 1"); + returnArray = + registryCoordinator.getQuorumBitmapIndicesAtBlockNumber(blockNumber, operatorIds); + assertEq( + returnArray[0], + 1, + "defaultOperator bitmap index at blockNumber deregistrationBlockNumber was not 1" + ); blockNumber = deregistrationBlockNumber + 1; - returnArray = registryCoordinator.getQuorumBitmapIndicesAtBlockNumber(blockNumber, operatorIds); - assertEq(returnArray[0], 1, "defaultOperator bitmap index at blockNumber deregistrationBlockNumber + 1 was not 1"); + returnArray = + registryCoordinator.getQuorumBitmapIndicesAtBlockNumber(blockNumber, operatorIds); + assertEq( + returnArray[0], + 1, + "defaultOperator bitmap index at blockNumber deregistrationBlockNumber + 1 was not 1" + ); } // @notice tests for correct reversion and return values in the event that an operator registers and later deregisters @@ -1303,39 +1591,64 @@ contract RegistryCoordinatorUnitTests_DeregisterOperator_EjectOperator is Regist // try an incorrect blockNumber input and confirm reversion cheats.expectRevert(QuorumBitmapHistoryLib.BitmapUpdateIsAfterBlockNumber.selector); - uint192 returnVal = registryCoordinator.getQuorumBitmapAtBlockNumberByIndex(operatorId, blockNumber, index); + uint192 returnVal = + registryCoordinator.getQuorumBitmapAtBlockNumberByIndex(operatorId, blockNumber, index); blockNumber = registrationBlockNumber; - returnVal = registryCoordinator.getQuorumBitmapAtBlockNumberByIndex(operatorId, blockNumber, index); - assertEq(returnVal, defaultQuorumBitmap, "defaultOperator bitmap index at blockNumber registrationBlockNumber was not defaultQuorumBitmap"); + returnVal = + registryCoordinator.getQuorumBitmapAtBlockNumberByIndex(operatorId, blockNumber, index); + assertEq( + returnVal, + defaultQuorumBitmap, + "defaultOperator bitmap index at blockNumber registrationBlockNumber was not defaultQuorumBitmap" + ); blockNumber = registrationBlockNumber + 1; - returnVal = registryCoordinator.getQuorumBitmapAtBlockNumberByIndex(operatorId, blockNumber, index); - assertEq(returnVal, defaultQuorumBitmap, "defaultOperator bitmap index at blockNumber registrationBlockNumber + 1 was not defaultQuorumBitmap"); + returnVal = + registryCoordinator.getQuorumBitmapAtBlockNumberByIndex(operatorId, blockNumber, index); + assertEq( + returnVal, + defaultQuorumBitmap, + "defaultOperator bitmap index at blockNumber registrationBlockNumber + 1 was not defaultQuorumBitmap" + ); // try an incorrect index input and confirm reversion index = 1; cheats.expectRevert(QuorumBitmapHistoryLib.BitmapUpdateIsAfterBlockNumber.selector); - returnVal = registryCoordinator.getQuorumBitmapAtBlockNumberByIndex(operatorId, blockNumber, index); + returnVal = + registryCoordinator.getQuorumBitmapAtBlockNumberByIndex(operatorId, blockNumber, index); blockNumber = deregistrationBlockNumber; - returnVal = registryCoordinator.getQuorumBitmapAtBlockNumberByIndex(operatorId, blockNumber, index); - assertEq(returnVal, emptyBitmap, "defaultOperator bitmap index at blockNumber deregistrationBlockNumber was not emptyBitmap"); + returnVal = + registryCoordinator.getQuorumBitmapAtBlockNumberByIndex(operatorId, blockNumber, index); + assertEq( + returnVal, + emptyBitmap, + "defaultOperator bitmap index at blockNumber deregistrationBlockNumber was not emptyBitmap" + ); blockNumber = deregistrationBlockNumber + 1; - returnVal = registryCoordinator.getQuorumBitmapAtBlockNumberByIndex(operatorId, blockNumber, index); - assertEq(returnVal, emptyBitmap, "defaultOperator bitmap index at blockNumber deregistrationBlockNumber + 1 was not emptyBitmap"); + returnVal = + registryCoordinator.getQuorumBitmapAtBlockNumberByIndex(operatorId, blockNumber, index); + assertEq( + returnVal, + emptyBitmap, + "defaultOperator bitmap index at blockNumber deregistrationBlockNumber + 1 was not emptyBitmap" + ); // try an incorrect index input and confirm reversion index = 0; cheats.expectRevert(QuorumBitmapHistoryLib.NextBitmapUpdateIsBeforeBlockNumber.selector); - returnVal = registryCoordinator.getQuorumBitmapAtBlockNumberByIndex(operatorId, blockNumber, index); + returnVal = + registryCoordinator.getQuorumBitmapAtBlockNumberByIndex(operatorId, blockNumber, index); } } contract RegistryCoordinatorUnitTests_RegisterOperatorWithChurn is RegistryCoordinatorUnitTests { // @notice registers an operator for a single quorum, with a fuzzed pubkey, churning out another operator from the quorum - function testFuzz_registerOperatorWithChurn(uint256 pseudoRandomNumber) public { + function testFuzz_registerOperatorWithChurn( + uint256 pseudoRandomNumber + ) public { uint32 numOperators = defaultMaxOperatorCount; uint32 kickRegistrationBlockNumber = 100; uint32 registrationBlockNumber = 200; @@ -1347,23 +1660,27 @@ contract RegistryCoordinatorUnitTests_RegisterOperatorWithChurn is RegistryCoord cheats.roll(kickRegistrationBlockNumber); - for (uint i = 0; i < numOperators - 1; i++) { - BN254.G1Point memory pubKey = BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, i))); + for (uint256 i = 0; i < numOperators - 1; i++) { + BN254.G1Point memory pubKey = + BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, i))); address operator = _incrementAddress(defaultOperator, i); _registerOperatorWithCoordinator(operator, quorumBitmap, pubKey); } address operatorToRegister = _incrementAddress(defaultOperator, numOperators); - BN254.G1Point memory operatorToRegisterPubKey = BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, numOperators))); + BN254.G1Point memory operatorToRegisterPubKey = + BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, numOperators))); bytes32 operatorToRegisterId = BN254.hashG1Point(operatorToRegisterPubKey); bytes32 operatorToKickId; address operatorToKick; // register last operator before kick - IRegistryCoordinator.OperatorKickParam[] memory operatorKickParams = new IRegistryCoordinator.OperatorKickParam[](1); + IRegistryCoordinator.OperatorKickParam[] memory operatorKickParams = + new IRegistryCoordinator.OperatorKickParam[](1); { - BN254.G1Point memory pubKey = BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, numOperators - 1))); + BN254.G1Point memory pubKey = + BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, numOperators - 1))); operatorToKickId = BN254.hashG1Point(pubKey); operatorToKick = _incrementAddress(defaultOperator, numOperators - 1); @@ -1397,11 +1714,12 @@ contract RegistryCoordinatorUnitTests_RegisterOperatorWithChurn is RegistryCoord cheats.expectEmit(true, true, true, true, address(indexRegistry)); emit QuorumIndexUpdate(operatorToRegisterId, defaultQuorumNumber, numOperators); - cheats.expectEmit(true, true, true, true, address(registryCoordinator)); emit OperatorDeregistered(operatorKickParams[0].operator, operatorToKickId); cheats.expectEmit(true, true, true, true, address(blsApkRegistry)); - emit OperatorRemovedFromQuorums(operatorKickParams[0].operator, operatorToKickId, quorumNumbers); + emit OperatorRemovedFromQuorums( + operatorKickParams[0].operator, operatorToKickId, quorumNumbers + ); cheats.expectEmit(true, true, true, true, address(stakeRegistry)); emit OperatorStakeUpdate(operatorToKickId, defaultQuorumNumber, 0); cheats.expectEmit(true, true, true, true, address(indexRegistry)); @@ -1410,7 +1728,13 @@ contract RegistryCoordinatorUnitTests_RegisterOperatorWithChurn is RegistryCoord { ISignatureUtils.SignatureWithSaltAndExpiry memory emptyAVSRegSig; ISignatureUtils.SignatureWithSaltAndExpiry memory signatureWithExpiry = - _signOperatorChurnApproval(operatorToRegister, operatorToRegisterId, operatorKickParams, defaultSalt, block.timestamp + 10); + _signOperatorChurnApproval( + operatorToRegister, + operatorToRegisterId, + operatorKickParams, + defaultSalt, + block.timestamp + 10 + ); cheats.prank(operatorToRegister); uint256 gasBefore = gasleft(); registryCoordinator.registerOperatorWithChurn( @@ -1427,29 +1751,45 @@ contract RegistryCoordinatorUnitTests_RegisterOperatorWithChurn is RegistryCoord assertEq( keccak256(abi.encode(registryCoordinator.getOperator(operatorToRegister))), - keccak256(abi.encode(IRegistryCoordinator.OperatorInfo({ - operatorId: operatorToRegisterId, - status: IRegistryCoordinator.OperatorStatus.REGISTERED - }))) + keccak256( + abi.encode( + IRegistryCoordinator.OperatorInfo({ + operatorId: operatorToRegisterId, + status: IRegistryCoordinator.OperatorStatus.REGISTERED + }) + ) + ) ); assertEq( keccak256(abi.encode(registryCoordinator.getOperator(operatorToKick))), - keccak256(abi.encode(IRegistryCoordinator.OperatorInfo({ - operatorId: operatorToKickId, - status: IRegistryCoordinator.OperatorStatus.DEREGISTERED - }))) + keccak256( + abi.encode( + IRegistryCoordinator.OperatorInfo({ + operatorId: operatorToKickId, + status: IRegistryCoordinator.OperatorStatus.DEREGISTERED + }) + ) + ) ); assertEq( - keccak256(abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(operatorToKickId, 0))), - keccak256(abi.encode(IRegistryCoordinator.QuorumBitmapUpdate({ - quorumBitmap: uint192(quorumBitmap), - updateBlockNumber: kickRegistrationBlockNumber, - nextUpdateBlockNumber: registrationBlockNumber - }))) + keccak256( + abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(operatorToKickId, 0)) + ), + keccak256( + abi.encode( + IRegistryCoordinator.QuorumBitmapUpdate({ + quorumBitmap: uint192(quorumBitmap), + updateBlockNumber: kickRegistrationBlockNumber, + nextUpdateBlockNumber: registrationBlockNumber + }) + ) + ) ); } - function test_registerOperatorWithChurn_revert_lessThanKickBIPsOfOperatorStake(uint256 pseudoRandomNumber) public { + function test_registerOperatorWithChurn_revert_lessThanKickBIPsOfOperatorStake( + uint256 pseudoRandomNumber + ) public { bytes memory quorumNumbers = new bytes(1); quorumNumbers[0] = bytes1(defaultQuorumNumber); ISignatureUtils.SignatureWithSaltAndExpiry memory emptyAVSRegSig; @@ -1465,7 +1805,13 @@ contract RegistryCoordinatorUnitTests_RegisterOperatorWithChurn is RegistryCoord cheats.roll(registrationBlockNumber); ISignatureUtils.SignatureWithSaltAndExpiry memory signatureWithExpiry = - _signOperatorChurnApproval(operatorToRegister, operatorToRegisterId, operatorKickParams, defaultSalt, block.timestamp + 10); + _signOperatorChurnApproval( + operatorToRegister, + operatorToRegisterId, + operatorKickParams, + defaultSalt, + block.timestamp + 10 + ); cheats.prank(operatorToRegister); cheats.expectRevert(bytes4(keccak256("InsufficientStakeForChurn()"))); registryCoordinator.registerOperatorWithChurn( @@ -1478,7 +1824,9 @@ contract RegistryCoordinatorUnitTests_RegisterOperatorWithChurn is RegistryCoord ); } - function test_registerOperatorWithChurn_revert_lessThanKickBIPsOfTotalStake(uint256 pseudoRandomNumber) public { + function test_registerOperatorWithChurn_revert_lessThanKickBIPsOfTotalStake( + uint256 pseudoRandomNumber + ) public { bytes memory quorumNumbers = new bytes(1); quorumNumbers[0] = bytes1(defaultQuorumNumber); ISignatureUtils.SignatureWithSaltAndExpiry memory emptyAVSRegSig; @@ -1488,16 +1836,27 @@ contract RegistryCoordinatorUnitTests_RegisterOperatorWithChurn is RegistryCoord address operatorToRegister, BN254.G1Point memory operatorToRegisterPubKey, IRegistryCoordinator.OperatorKickParam[] memory operatorKickParams - ) = _test_registerOperatorWithChurn_SetUp(pseudoRandomNumber, quorumNumbers, operatorToKickStake); + ) = _test_registerOperatorWithChurn_SetUp( + pseudoRandomNumber, quorumNumbers, operatorToKickStake + ); bytes32 operatorToRegisterId = BN254.hashG1Point(operatorToRegisterPubKey); - // set the stake of the operator to register to the defaultKickBIPsOfOperatorStake multiple of the operatorToKickStake - _setOperatorWeight(operatorToRegister, defaultQuorumNumber, operatorToKickStake * defaultKickBIPsOfOperatorStake / 10000 + 1); + _setOperatorWeight( + operatorToRegister, + defaultQuorumNumber, + operatorToKickStake * defaultKickBIPsOfOperatorStake / 10_000 + 1 + ); cheats.roll(registrationBlockNumber); ISignatureUtils.SignatureWithSaltAndExpiry memory signatureWithExpiry = - _signOperatorChurnApproval(operatorToRegister, operatorToRegisterId, operatorKickParams, defaultSalt, block.timestamp + 10); + _signOperatorChurnApproval( + operatorToRegister, + operatorToRegisterId, + operatorKickParams, + defaultSalt, + block.timestamp + 10 + ); cheats.prank(operatorToRegister); cheats.expectRevert(bytes4(keccak256("CannotKickOperatorAboveThreshold()"))); registryCoordinator.registerOperatorWithChurn( @@ -1510,7 +1869,9 @@ contract RegistryCoordinatorUnitTests_RegisterOperatorWithChurn is RegistryCoord ); } - function test_registerOperatorWithChurn_revert_invalidChurnApproverSignature(uint256 pseudoRandomNumber) public { + function test_registerOperatorWithChurn_revert_invalidChurnApproverSignature( + uint256 pseudoRandomNumber + ) public { bytes memory quorumNumbers = new bytes(1); quorumNumbers[0] = bytes1(defaultQuorumNumber); ISignatureUtils.SignatureWithSaltAndExpiry memory emptyAVSRegSig; @@ -1542,7 +1903,9 @@ contract RegistryCoordinatorUnitTests_RegisterOperatorWithChurn is RegistryCoord ); } - function test_registerOperatorWithChurn_revert_expiredChurnApproverSignature(uint256 pseudoRandomNumber) public { + function test_registerOperatorWithChurn_revert_expiredChurnApproverSignature( + uint256 pseudoRandomNumber + ) public { bytes memory quorumNumbers = new bytes(1); quorumNumbers[0] = bytes1(defaultQuorumNumber); ISignatureUtils.SignatureWithSaltAndExpiry memory emptyAVSRegSig; @@ -1559,7 +1922,13 @@ contract RegistryCoordinatorUnitTests_RegisterOperatorWithChurn is RegistryCoord cheats.roll(registrationBlockNumber); ISignatureUtils.SignatureWithSaltAndExpiry memory signatureWithSaltAndExpiry = - _signOperatorChurnApproval(operatorToRegister, operatorToRegisterId, operatorKickParams, defaultSalt, block.timestamp - 1); + _signOperatorChurnApproval( + operatorToRegister, + operatorToRegisterId, + operatorKickParams, + defaultSalt, + block.timestamp - 1 + ); cheats.prank(operatorToRegister); cheats.expectRevert(bytes4(keccak256("SignatureExpired()"))); registryCoordinator.registerOperatorWithChurn( @@ -1595,7 +1964,9 @@ contract RegistryCoordinatorUnitTests_UpdateOperators is RegistryCoordinatorUnit _setOperatorWeight(defaultOperator, uint8(quorumNumbers[0]), defaultStake); cheats.startPrank(defaultOperator); cheats.roll(registrationBlockNumber); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); address[] memory operatorsToUpdate = new address[](1); operatorsToUpdate[0] = defaultOperator; @@ -1605,7 +1976,10 @@ contract RegistryCoordinatorUnitTests_UpdateOperators is RegistryCoordinatorUnit // @notice tests the `updateOperators` function with a single registered operator as input // @dev also sets up return data from the StakeRegistry - function testFuzz_updateOperators_singleOperator(uint192 registrationBitmap, uint192 mockReturnData) public { + function testFuzz_updateOperators_singleOperator( + uint192 registrationBitmap, + uint192 mockReturnData + ) public { // filter fuzzed inputs to only valid inputs cheats.assume(registrationBitmap != 0); mockReturnData = (mockReturnData & registrationBitmap); @@ -1620,7 +1994,9 @@ contract RegistryCoordinatorUnitTests_UpdateOperators is RegistryCoordinatorUnit } cheats.startPrank(defaultOperator); cheats.roll(registrationBlockNumber); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); address[] memory operatorsToUpdate = new address[](1); operatorsToUpdate[0] = defaultOperator; @@ -1647,7 +2023,9 @@ contract RegistryCoordinatorUnitTests_UpdateOperators is RegistryCoordinatorUnit operatorsToUpdate[0] = defaultOperator; // force a staticcall to the `updateOperators` function -- this should *pass* because the call should be a strict no-op! - (bool success, ) = address(registryCoordinator).staticcall(abi.encodeWithSignature("updateOperators(address[])", operatorsToUpdate)); + (bool success,) = address(registryCoordinator).staticcall( + abi.encodeWithSignature("updateOperators(address[])", operatorsToUpdate) + ); require(success, "staticcall failed!"); } @@ -1657,7 +2035,7 @@ contract RegistryCoordinatorUnitTests_UpdateOperators is RegistryCoordinatorUnit address[][] memory operatorsToUpdate = new address[][](1); address[] memory operatorArray = new address[](1); - operatorArray[0] = defaultOperator; + operatorArray[0] = defaultOperator; operatorsToUpdate[0] = operatorArray; bytes memory quorumNumbers = new bytes(1); quorumNumbers[0] = bytes1(defaultQuorumNumber); @@ -1689,7 +2067,7 @@ contract RegistryCoordinatorUnitTests_UpdateOperators is RegistryCoordinatorUnit function test_updateOperatorsForQuorum_revert_incorrectNumberOfOperators() public { address[][] memory operatorsToUpdate = new address[][](1); address[] memory operatorArray = new address[](1); - operatorArray[0] = defaultOperator; + operatorArray[0] = defaultOperator; operatorsToUpdate[0] = operatorArray; bytes memory quorumNumbers = new bytes(1); quorumNumbers[0] = bytes1(defaultQuorumNumber); @@ -1707,12 +2085,14 @@ contract RegistryCoordinatorUnitTests_UpdateOperators is RegistryCoordinatorUnit _setOperatorWeight(defaultOperator, uint8(quorumNumbers[0]), defaultStake); cheats.startPrank(defaultOperator); cheats.roll(registrationBlockNumber); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); address[][] memory operatorsToUpdate = new address[][](1); address[] memory operatorArray = new address[](1); // use an unregistered operator address as input - operatorArray[0] = _incrementAddress(defaultOperator, 1); + operatorArray[0] = _incrementAddress(defaultOperator, 1); operatorsToUpdate[0] = operatorArray; cheats.expectRevert(bytes4(keccak256("NotRegisteredForQuorum()"))); @@ -1720,7 +2100,9 @@ contract RegistryCoordinatorUnitTests_UpdateOperators is RegistryCoordinatorUnit } // note: there is not an explicit check for duplicates, as checking for explicit ordering covers this - function test_updateOperatorsForQuorum_revert_duplicateOperator(uint256 pseudoRandomNumber) public { + function test_updateOperatorsForQuorum_revert_duplicateOperator( + uint256 pseudoRandomNumber + ) public { // register 2 operators uint32 numOperators = 2; uint32 registrationBlockNumber = 200; @@ -1728,8 +2110,9 @@ contract RegistryCoordinatorUnitTests_UpdateOperators is RegistryCoordinatorUnit quorumNumbers[0] = bytes1(defaultQuorumNumber); uint256 quorumBitmap = BitmapUtils.orderedBytesArrayToBitmap(quorumNumbers); cheats.roll(registrationBlockNumber); - for (uint i = 0; i < numOperators; i++) { - BN254.G1Point memory pubKey = BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, i))); + for (uint256 i = 0; i < numOperators; i++) { + BN254.G1Point memory pubKey = + BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, i))); address operator = _incrementAddress(defaultOperator, i); _registerOperatorWithCoordinator(operator, quorumBitmap, pubKey); @@ -1738,8 +2121,8 @@ contract RegistryCoordinatorUnitTests_UpdateOperators is RegistryCoordinatorUnit address[][] memory operatorsToUpdate = new address[][](1); address[] memory operatorArray = new address[](2); // use the same operator address twice as input - operatorArray[0] = defaultOperator; - operatorArray[1] = defaultOperator; + operatorArray[0] = defaultOperator; + operatorArray[1] = defaultOperator; operatorsToUpdate[0] = operatorArray; // note: there is not an explicit check for duplicates, as checking for explicit ordering covers this @@ -1747,7 +2130,9 @@ contract RegistryCoordinatorUnitTests_UpdateOperators is RegistryCoordinatorUnit registryCoordinator.updateOperatorsForQuorum(operatorsToUpdate, quorumNumbers); } - function test_updateOperatorsForQuorum_revert_incorrectListOrder(uint256 pseudoRandomNumber) public { + function test_updateOperatorsForQuorum_revert_incorrectListOrder( + uint256 pseudoRandomNumber + ) public { // register 2 operators uint32 numOperators = 2; uint32 registrationBlockNumber = 200; @@ -1755,8 +2140,9 @@ contract RegistryCoordinatorUnitTests_UpdateOperators is RegistryCoordinatorUnit quorumNumbers[0] = bytes1(defaultQuorumNumber); uint256 quorumBitmap = BitmapUtils.orderedBytesArrayToBitmap(quorumNumbers); cheats.roll(registrationBlockNumber); - for (uint i = 0; i < numOperators; i++) { - BN254.G1Point memory pubKey = BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, i))); + for (uint256 i = 0; i < numOperators; i++) { + BN254.G1Point memory pubKey = + BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, i))); address operator = _incrementAddress(defaultOperator, i); _registerOperatorWithCoordinator(operator, quorumBitmap, pubKey); @@ -1765,8 +2151,8 @@ contract RegistryCoordinatorUnitTests_UpdateOperators is RegistryCoordinatorUnit address[][] memory operatorsToUpdate = new address[][](1); address[] memory operatorArray = new address[](2); // order the operator addresses in descending order, instead of ascending order - operatorArray[0] = _incrementAddress(defaultOperator, 1); - operatorArray[1] = defaultOperator; + operatorArray[0] = _incrementAddress(defaultOperator, 1); + operatorArray[1] = defaultOperator; operatorsToUpdate[0] = operatorArray; cheats.expectRevert(bytes4(keccak256("NotSorted()"))); @@ -1782,25 +2168,33 @@ contract RegistryCoordinatorUnitTests_UpdateOperators is RegistryCoordinatorUnit _setOperatorWeight(defaultOperator, uint8(quorumNumbers[0]), defaultStake); cheats.startPrank(defaultOperator); cheats.roll(registrationBlockNumber); - registryCoordinator.registerOperator(quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig); + registryCoordinator.registerOperator( + quorumNumbers, defaultSocket, pubkeyRegistrationParams, emptySig + ); address[][] memory operatorsToUpdate = new address[][](1); address[] memory operatorArray = new address[](1); - operatorArray[0] = defaultOperator; + operatorArray[0] = defaultOperator; operatorsToUpdate[0] = operatorArray; - uint256 quorumUpdateBlockNumberBefore = registryCoordinator.quorumUpdateBlockNumber(defaultQuorumNumber); + uint256 quorumUpdateBlockNumberBefore = + registryCoordinator.quorumUpdateBlockNumber(defaultQuorumNumber); require(quorumUpdateBlockNumberBefore != block.number, "bad test setup!"); cheats.expectEmit(true, true, true, true, address(registryCoordinator)); emit QuorumBlockNumberUpdated(defaultQuorumNumber, block.number); registryCoordinator.updateOperatorsForQuorum(operatorsToUpdate, quorumNumbers); - uint256 quorumUpdateBlockNumberAfter = registryCoordinator.quorumUpdateBlockNumber(defaultQuorumNumber); - assertEq(quorumUpdateBlockNumberAfter, block.number, "quorumUpdateBlockNumber not set correctly"); + uint256 quorumUpdateBlockNumberAfter = + registryCoordinator.quorumUpdateBlockNumber(defaultQuorumNumber); + assertEq( + quorumUpdateBlockNumberAfter, block.number, "quorumUpdateBlockNumber not set correctly" + ); } - function test_updateOperatorsForQuorum_twoOperators(uint256 pseudoRandomNumber) public { + function test_updateOperatorsForQuorum_twoOperators( + uint256 pseudoRandomNumber + ) public { // register 2 operators uint32 numOperators = 2; uint32 registrationBlockNumber = 200; @@ -1808,8 +2202,9 @@ contract RegistryCoordinatorUnitTests_UpdateOperators is RegistryCoordinatorUnit quorumNumbers[0] = bytes1(defaultQuorumNumber); uint256 quorumBitmap = BitmapUtils.orderedBytesArrayToBitmap(quorumNumbers); cheats.roll(registrationBlockNumber); - for (uint i = 0; i < numOperators; i++) { - BN254.G1Point memory pubKey = BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, i))); + for (uint256 i = 0; i < numOperators; i++) { + BN254.G1Point memory pubKey = + BN254.hashToG1(keccak256(abi.encodePacked(pseudoRandomNumber, i))); address operator = _incrementAddress(defaultOperator, i); _registerOperatorWithCoordinator(operator, quorumBitmap, pubKey); @@ -1818,52 +2213,74 @@ contract RegistryCoordinatorUnitTests_UpdateOperators is RegistryCoordinatorUnit address[][] memory operatorsToUpdate = new address[][](1); address[] memory operatorArray = new address[](2); // order the operator addresses in descending order, instead of ascending order - operatorArray[0] = defaultOperator; - operatorArray[1] = _incrementAddress(defaultOperator, 1); + operatorArray[0] = defaultOperator; + operatorArray[1] = _incrementAddress(defaultOperator, 1); operatorsToUpdate[0] = operatorArray; - uint256 quorumUpdateBlockNumberBefore = registryCoordinator.quorumUpdateBlockNumber(defaultQuorumNumber); + uint256 quorumUpdateBlockNumberBefore = + registryCoordinator.quorumUpdateBlockNumber(defaultQuorumNumber); require(quorumUpdateBlockNumberBefore != block.number, "bad test setup!"); cheats.expectEmit(true, true, true, true, address(registryCoordinator)); emit QuorumBlockNumberUpdated(defaultQuorumNumber, block.number); registryCoordinator.updateOperatorsForQuorum(operatorsToUpdate, quorumNumbers); - uint256 quorumUpdateBlockNumberAfter = registryCoordinator.quorumUpdateBlockNumber(defaultQuorumNumber); - assertEq(quorumUpdateBlockNumberAfter, block.number, "quorumUpdateBlockNumber not set correctly"); + uint256 quorumUpdateBlockNumberAfter = + registryCoordinator.quorumUpdateBlockNumber(defaultQuorumNumber); + assertEq( + quorumUpdateBlockNumberAfter, block.number, "quorumUpdateBlockNumber not set correctly" + ); } // @notice tests that the internal `_updateOperatorBitmap` function works as expected, for fuzzed inputs - function testFuzz_updateOperatorBitmapInternal_noPreviousEntries(uint192 newBitmap) public { + function testFuzz_updateOperatorBitmapInternal_noPreviousEntries( + uint192 newBitmap + ) public { registryCoordinator._updateOperatorBitmapExternal(defaultOperatorId, newBitmap); assertEq( - keccak256(abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0))), - keccak256(abi.encode(IRegistryCoordinator.QuorumBitmapUpdate({ - quorumBitmap: uint192(newBitmap), - updateBlockNumber: uint32(block.number), - nextUpdateBlockNumber: 0 - }))) + keccak256( + abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0)) + ), + keccak256( + abi.encode( + IRegistryCoordinator.QuorumBitmapUpdate({ + quorumBitmap: uint192(newBitmap), + updateBlockNumber: uint32(block.number), + nextUpdateBlockNumber: 0 + }) + ) + ) ); } // @notice tests that the internal `_updateOperatorBitmap` function works as expected, for fuzzed inputs - function testFuzz_updateOperatorBitmapInternal_previousEntryInCurrentBlock(uint192 newBitmap) public { + function testFuzz_updateOperatorBitmapInternal_previousEntryInCurrentBlock( + uint192 newBitmap + ) public { uint192 pastBitmap = 1; testFuzz_updateOperatorBitmapInternal_noPreviousEntries(pastBitmap); registryCoordinator._updateOperatorBitmapExternal(defaultOperatorId, newBitmap); assertEq( - keccak256(abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0))), - keccak256(abi.encode(IRegistryCoordinator.QuorumBitmapUpdate({ - quorumBitmap: uint192(newBitmap), - updateBlockNumber: uint32(block.number), - nextUpdateBlockNumber: 0 - }))) + keccak256( + abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0)) + ), + keccak256( + abi.encode( + IRegistryCoordinator.QuorumBitmapUpdate({ + quorumBitmap: uint192(newBitmap), + updateBlockNumber: uint32(block.number), + nextUpdateBlockNumber: 0 + }) + ) + ) ); } // @notice tests that the internal `_updateOperatorBitmap` function works as expected, for fuzzed inputs - function testFuzz_updateOperatorBitmapInternal_previousEntryInPastBlock(uint192 newBitmap) public { + function testFuzz_updateOperatorBitmapInternal_previousEntryInPastBlock( + uint192 newBitmap + ) public { uint192 pastBitmap = 1; testFuzz_updateOperatorBitmapInternal_noPreviousEntries(pastBitmap); @@ -1873,20 +2290,32 @@ contract RegistryCoordinatorUnitTests_UpdateOperators is RegistryCoordinatorUnit registryCoordinator._updateOperatorBitmapExternal(defaultOperatorId, newBitmap); assertEq( - keccak256(abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0))), - keccak256(abi.encode(IRegistryCoordinator.QuorumBitmapUpdate({ - quorumBitmap: uint192(pastBitmap), - updateBlockNumber: uint32(previousBlockNumber), - nextUpdateBlockNumber: uint32(block.number) - }))) + keccak256( + abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 0)) + ), + keccak256( + abi.encode( + IRegistryCoordinator.QuorumBitmapUpdate({ + quorumBitmap: uint192(pastBitmap), + updateBlockNumber: uint32(previousBlockNumber), + nextUpdateBlockNumber: uint32(block.number) + }) + ) + ) ); assertEq( - keccak256(abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 1))), - keccak256(abi.encode(IRegistryCoordinator.QuorumBitmapUpdate({ - quorumBitmap: uint192(newBitmap), - updateBlockNumber: uint32(block.number), - nextUpdateBlockNumber: 0 - }))) + keccak256( + abi.encode(registryCoordinator.getQuorumBitmapUpdateByIndex(defaultOperatorId, 1)) + ), + keccak256( + abi.encode( + IRegistryCoordinator.QuorumBitmapUpdate({ + quorumBitmap: uint192(newBitmap), + updateBlockNumber: uint32(block.number), + nextUpdateBlockNumber: 0 + }) + ) + ) ); } } @@ -1895,7 +2324,9 @@ contract RegistryCoordinatorUnitTests_BeforeMigration is RegistryCoordinatorUnit function test_registerALMHook_Reverts() public { cheats.prank(address(registryCoordinator.allocationManager())); cheats.expectRevert(); - registryCoordinator.registerOperator(defaultOperator, new uint32[](0), abi.encode(defaultSocket, pubkeyRegistrationParams)); + registryCoordinator.registerOperator( + defaultOperator, new uint32[](0), abi.encode(defaultSocket, pubkeyRegistrationParams) + ); } function test_deregisterALMHook_Reverts() public { @@ -1909,17 +2340,17 @@ contract RegistryCoordinatorUnitTests_BeforeMigration is RegistryCoordinatorUnit function test_CreateTotalDelegatedStakeQuorum() public { _deployMockEigenLayerAndAVS(0); // Set up test params - IRegistryCoordinator.OperatorSetParam memory operatorSetParams = IRegistryCoordinator.OperatorSetParam({ + IRegistryCoordinator.OperatorSetParam memory operatorSetParams = IRegistryCoordinator + .OperatorSetParam({ maxOperatorCount: 10, kickBIPsOfOperatorStake: 0, kickBIPsOfTotalStake: 0 }); uint96 minimumStake = 100; - IStakeRegistry.StrategyParams[] memory strategyParams = new IStakeRegistry.StrategyParams[](1); - strategyParams[0] = IStakeRegistry.StrategyParams({ - strategy: IStrategy(address(0x1)), - multiplier: 1000 - }); + IStakeRegistry.StrategyParams[] memory strategyParams = + new IStakeRegistry.StrategyParams[](1); + strategyParams[0] = + IStakeRegistry.StrategyParams({strategy: IStrategy(address(0x1)), multiplier: 1000}); // Get initial quorum count uint8 initialQuorumCount = registryCoordinator.quorumCount(); @@ -1927,16 +2358,15 @@ contract RegistryCoordinatorUnitTests_BeforeMigration is RegistryCoordinatorUnit // Create quorum with total delegated stake type cheats.prank(registryCoordinatorOwner); registryCoordinator.createTotalDelegatedStakeQuorum( - operatorSetParams, - minimumStake, - strategyParams + operatorSetParams, minimumStake, strategyParams ); // Verify quorum was created assertEq(registryCoordinator.quorumCount(), initialQuorumCount + 1); // Verify quorum params were set correctly - IRegistryCoordinator.OperatorSetParam memory storedParams = registryCoordinator.getOperatorSetParams(initialQuorumCount); + IRegistryCoordinator.OperatorSetParam memory storedParams = + registryCoordinator.getOperatorSetParams(initialQuorumCount); assertEq(storedParams.maxOperatorCount, operatorSetParams.maxOperatorCount); assertEq(storedParams.kickBIPsOfOperatorStake, operatorSetParams.kickBIPsOfOperatorStake); assertEq(storedParams.kickBIPsOfTotalStake, operatorSetParams.kickBIPsOfTotalStake); @@ -1944,27 +2374,24 @@ contract RegistryCoordinatorUnitTests_BeforeMigration is RegistryCoordinatorUnit function test_CreateSlashableStakeQuorum_Reverts() public { _deployMockEigenLayerAndAVS(0); - IRegistryCoordinator.OperatorSetParam memory operatorSetParams = IRegistryCoordinator.OperatorSetParam({ + IRegistryCoordinator.OperatorSetParam memory operatorSetParams = IRegistryCoordinator + .OperatorSetParam({ maxOperatorCount: 10, kickBIPsOfOperatorStake: 0, kickBIPsOfTotalStake: 0 }); uint96 minimumStake = 100; - IStakeRegistry.StrategyParams[] memory strategyParams = new IStakeRegistry.StrategyParams[](1); - strategyParams[0] = IStakeRegistry.StrategyParams({ - strategy: IStrategy(address(0x1)), - multiplier: 1000 - }); + IStakeRegistry.StrategyParams[] memory strategyParams = + new IStakeRegistry.StrategyParams[](1); + strategyParams[0] = + IStakeRegistry.StrategyParams({strategy: IStrategy(address(0x1)), multiplier: 1000}); uint32 lookAheadPeriod = 100; // Attempt to create quorum with slashable stake type before enabling operator sets cheats.prank(registryCoordinatorOwner); cheats.expectRevert(); registryCoordinator.createSlashableStakeQuorum( - operatorSetParams, - minimumStake, - strategyParams, - lookAheadPeriod + operatorSetParams, minimumStake, strategyParams, lookAheadPeriod ); } @@ -1990,25 +2417,14 @@ contract RegistryCoordinatorUnitTests_AfterMigration is RegistryCoordinatorUnitT address operatorToRegister = address(420); - ISignatureUtils.SignatureWithSaltAndExpiry memory emptySignature = ISignatureUtils.SignatureWithSaltAndExpiry({ - signature: new bytes(0), - salt: bytes32(0), - expiry: 0 - }); + ISignatureUtils.SignatureWithSaltAndExpiry memory emptySignature = ISignatureUtils + .SignatureWithSaltAndExpiry({signature: new bytes(0), salt: bytes32(0), expiry: 0}); - IBLSApkRegistry.PubkeyRegistrationParams memory operatorRegisterApkParams = IBLSApkRegistry.PubkeyRegistrationParams({ - pubkeyRegistrationSignature: BN254.G1Point({ - X: 0, - Y: 0 - }), - pubkeyG1: BN254.G1Point({ - X: 0, - Y: 0 - }), - pubkeyG2: BN254.G2Point({ - X: [uint256(0), uint256(0)], - Y: [uint256(0), uint256(0)] - }) + IBLSApkRegistry.PubkeyRegistrationParams memory operatorRegisterApkParams = IBLSApkRegistry + .PubkeyRegistrationParams({ + pubkeyRegistrationSignature: BN254.G1Point({X: 0, Y: 0}), + pubkeyG1: BN254.G1Point({X: 0, Y: 0}), + pubkeyG2: BN254.G2Point({X: [uint256(0), uint256(0)], Y: [uint256(0), uint256(0)]}) }); string memory socket = "socket"; @@ -2035,8 +2451,13 @@ contract RegistryCoordinatorUnitTests_AfterMigration is RegistryCoordinatorUnitT assertEq(bitmap, 0, "Operator bitmap should be empty after deregistration"); // Verify operator status is NEVER_REGISTERED - IRegistryCoordinator.OperatorStatus status = registryCoordinator.getOperatorStatus(operatorToRegister); - assertEq(uint8(status), uint8(IRegistryCoordinator.OperatorStatus.NEVER_REGISTERED), "Operator status should be NEVER_REGISTERED"); + IRegistryCoordinator.OperatorStatus status = + registryCoordinator.getOperatorStatus(operatorToRegister); + assertEq( + uint8(status), + uint8(IRegistryCoordinator.OperatorStatus.NEVER_REGISTERED), + "Operator status should be NEVER_REGISTERED" + ); } function test_M2_Register_Reverts() public { @@ -2050,10 +2471,7 @@ contract RegistryCoordinatorUnitTests_AfterMigration is RegistryCoordinatorUnitT cheats.expectRevert(); registryCoordinator.registerOperator( - quorumNumbers, - defaultSocket, - params, - operatorSignature + quorumNumbers, defaultSocket, params, operatorSignature ); } @@ -2066,26 +2484,23 @@ contract RegistryCoordinatorUnitTests_AfterMigration is RegistryCoordinatorUnitT registryCoordinator.enableOperatorSets(); // Create quorum params - IRegistryCoordinator.OperatorSetParam memory operatorSetParams = IRegistryCoordinator.OperatorSetParam({ + IRegistryCoordinator.OperatorSetParam memory operatorSetParams = IRegistryCoordinator + .OperatorSetParam({ maxOperatorCount: 10, kickBIPsOfOperatorStake: 1000, kickBIPsOfTotalStake: 100 }); uint96 minimumStake = 100; - IStakeRegistry.StrategyParams[] memory strategyParams = new IStakeRegistry.StrategyParams[](1); - strategyParams[0] = IStakeRegistry.StrategyParams({ - strategy: IStrategy(address(1)), - multiplier: 1 - }); + IStakeRegistry.StrategyParams[] memory strategyParams = + new IStakeRegistry.StrategyParams[](1); + strategyParams[0] = + IStakeRegistry.StrategyParams({strategy: IStrategy(address(1)), multiplier: 1}); uint32 lookAheadPeriod = 100; // Create slashable stake quorum cheats.prank(registryCoordinatorOwner); registryCoordinator.createSlashableStakeQuorum( - operatorSetParams, - minimumStake, - strategyParams, - lookAheadPeriod + operatorSetParams, minimumStake, strategyParams, lookAheadPeriod ); } @@ -2098,24 +2513,22 @@ contract RegistryCoordinatorUnitTests_AfterMigration is RegistryCoordinatorUnitT registryCoordinator.enableOperatorSets(); // Create quorum params - IRegistryCoordinator.OperatorSetParam memory operatorSetParams = IRegistryCoordinator.OperatorSetParam({ + IRegistryCoordinator.OperatorSetParam memory operatorSetParams = IRegistryCoordinator + .OperatorSetParam({ maxOperatorCount: 10, kickBIPsOfOperatorStake: 1000, kickBIPsOfTotalStake: 100 }); uint96 minimumStake = 100; - IStakeRegistry.StrategyParams[] memory strategyParams = new IStakeRegistry.StrategyParams[](1); - strategyParams[0] = IStakeRegistry.StrategyParams({ - strategy: IStrategy(address(1)), - multiplier: 10000 - }); + IStakeRegistry.StrategyParams[] memory strategyParams = + new IStakeRegistry.StrategyParams[](1); + strategyParams[0] = + IStakeRegistry.StrategyParams({strategy: IStrategy(address(1)), multiplier: 10_000}); // Create total delegated stake quorum cheats.prank(registryCoordinatorOwner); registryCoordinator.createTotalDelegatedStakeQuorum( - operatorSetParams, - minimumStake, - strategyParams + operatorSetParams, minimumStake, strategyParams ); } @@ -2128,27 +2541,22 @@ contract RegistryCoordinatorUnitTests_AfterMigration is RegistryCoordinatorUnitT registryCoordinator.enableOperatorSets(); // Create quorum params - IRegistryCoordinator.OperatorSetParam memory operatorSetParams = IRegistryCoordinator.OperatorSetParam({ + IRegistryCoordinator.OperatorSetParam memory operatorSetParams = IRegistryCoordinator + .OperatorSetParam({ maxOperatorCount: 10, kickBIPsOfOperatorStake: 1000, kickBIPsOfTotalStake: 100 }); uint96 minimumStake = 100; - IStakeRegistry.StrategyParams[] memory strategyParams = new IStakeRegistry.StrategyParams[](1); - strategyParams[0] = IStakeRegistry.StrategyParams({ - strategy: IStrategy(address(1)), - multiplier: 10000 - }); + IStakeRegistry.StrategyParams[] memory strategyParams = + new IStakeRegistry.StrategyParams[](1); + strategyParams[0] = + IStakeRegistry.StrategyParams({strategy: IStrategy(address(1)), multiplier: 10_000}); // Create total delegated stake quorum cheats.prank(registryCoordinatorOwner); - registryCoordinator.createTotalDelegatedStakeQuorum( - operatorSetParams, - 0, - strategyParams - ); - + registryCoordinator.createTotalDelegatedStakeQuorum(operatorSetParams, 0, strategyParams); uint32[] memory operatorSetIds = new uint32[](1); operatorSetIds[0] = 0; @@ -2175,26 +2583,22 @@ contract RegistryCoordinatorUnitTests_AfterMigration is RegistryCoordinatorUnitT registryCoordinator.enableOperatorSets(); // Create quorum params - IRegistryCoordinator.OperatorSetParam memory operatorSetParams = IRegistryCoordinator.OperatorSetParam({ + IRegistryCoordinator.OperatorSetParam memory operatorSetParams = IRegistryCoordinator + .OperatorSetParam({ maxOperatorCount: 10, kickBIPsOfOperatorStake: 1000, kickBIPsOfTotalStake: 100 }); uint96 minimumStake = 100; - IStakeRegistry.StrategyParams[] memory strategyParams = new IStakeRegistry.StrategyParams[](1); - strategyParams[0] = IStakeRegistry.StrategyParams({ - strategy: IStrategy(address(1)), - multiplier: 10000 - }); + IStakeRegistry.StrategyParams[] memory strategyParams = + new IStakeRegistry.StrategyParams[](1); + strategyParams[0] = + IStakeRegistry.StrategyParams({strategy: IStrategy(address(1)), multiplier: 10_000}); // Create total delegated stake quorum cheats.prank(registryCoordinatorOwner); - registryCoordinator.createTotalDelegatedStakeQuorum( - operatorSetParams, - 0, - strategyParams - ); + registryCoordinator.createTotalDelegatedStakeQuorum(operatorSetParams, 0, strategyParams); uint32[] memory operatorSetIds = new uint32[](1); operatorSetIds[0] = 0; @@ -2208,21 +2612,16 @@ contract RegistryCoordinatorUnitTests_AfterMigration is RegistryCoordinatorUnitT // pubkeySignature: defaultPubKeySignature // }); - IRegistryCoordinator.OperatorKickParam[] memory operatorKickParams = new IRegistryCoordinator.OperatorKickParam[](1); - operatorKickParams[0] = IRegistryCoordinator.OperatorKickParam({ - operator: address(0x1), - quorumNumber: 0 - }); + IRegistryCoordinator.OperatorKickParam[] memory operatorKickParams = + new IRegistryCoordinator.OperatorKickParam[](1); + operatorKickParams[0] = + IRegistryCoordinator.OperatorKickParam({operator: address(0x1), quorumNumber: 0}); ISignatureUtils.SignatureWithSaltAndExpiry memory churnApproverSignature; ISignatureUtils.SignatureWithSaltAndExpiry memory operatorSignature; bytes memory registerParams = abi.encode( - socket, - params, - operatorKickParams, - churnApproverSignature, - operatorSignature + socket, params, operatorKickParams, churnApproverSignature, operatorSignature ); // Prank as allocation manager and call register hook @@ -2234,24 +2633,22 @@ contract RegistryCoordinatorUnitTests_AfterMigration is RegistryCoordinatorUnitT vm.skip(true); _deployMockEigenLayerAndAVS(0); - IRegistryCoordinator.OperatorSetParam memory operatorSetParams = IRegistryCoordinator.OperatorSetParam({ + IRegistryCoordinator.OperatorSetParam memory operatorSetParams = IRegistryCoordinator + .OperatorSetParam({ maxOperatorCount: defaultMaxOperatorCount, kickBIPsOfOperatorStake: defaultKickBIPsOfOperatorStake, kickBIPsOfTotalStake: defaultKickBIPsOfTotalStake }); uint96 minimumStake = 100; - IStakeRegistry.StrategyParams[] memory strategyParams = new IStakeRegistry.StrategyParams[](1); - strategyParams[0] = IStakeRegistry.StrategyParams({ - strategy: IStrategy(address(1)), - multiplier: 10000 - }); + IStakeRegistry.StrategyParams[] memory strategyParams = + new IStakeRegistry.StrategyParams[](1); + strategyParams[0] = + IStakeRegistry.StrategyParams({strategy: IStrategy(address(1)), multiplier: 10_000}); cheats.prank(registryCoordinatorOwner); registryCoordinator.createTotalDelegatedStakeQuorum( - operatorSetParams, - minimumStake, - strategyParams + operatorSetParams, minimumStake, strategyParams ); uint256 quorumBitmap = 0; @@ -2260,33 +2657,28 @@ contract RegistryCoordinatorUnitTests_AfterMigration is RegistryCoordinatorUnitT } function test_deregisterHook() public { - _deployMockEigenLayerAndAVS(0); // Enable operator sets first cheats.prank(registryCoordinatorOwner); registryCoordinator.enableOperatorSets(); // Create quorum params - IRegistryCoordinator.OperatorSetParam memory operatorSetParams = IRegistryCoordinator.OperatorSetParam({ + IRegistryCoordinator.OperatorSetParam memory operatorSetParams = IRegistryCoordinator + .OperatorSetParam({ maxOperatorCount: 10, kickBIPsOfOperatorStake: 1000, kickBIPsOfTotalStake: 100 }); uint96 minimumStake = 100; - IStakeRegistry.StrategyParams[] memory strategyParams = new IStakeRegistry.StrategyParams[](1); - strategyParams[0] = IStakeRegistry.StrategyParams({ - strategy: IStrategy(address(1)), - multiplier: 10000 - }); + IStakeRegistry.StrategyParams[] memory strategyParams = + new IStakeRegistry.StrategyParams[](1); + strategyParams[0] = + IStakeRegistry.StrategyParams({strategy: IStrategy(address(1)), multiplier: 10_000}); // Create total delegated stake quorum cheats.prank(registryCoordinatorOwner); - registryCoordinator.createTotalDelegatedStakeQuorum( - operatorSetParams, - 0, - strategyParams - ); + registryCoordinator.createTotalDelegatedStakeQuorum(operatorSetParams, 0, strategyParams); // Prank as allocation manager and call register hook uint32[] memory operatorSetIds = new uint32[](1); @@ -2303,7 +2695,6 @@ contract RegistryCoordinatorUnitTests_AfterMigration is RegistryCoordinatorUnitT bytes memory data = abi.encode(socket, params); - cheats.startPrank(address(registryCoordinator.allocationManager())); registryCoordinator.registerOperator(defaultOperator, operatorSetIds, data); @@ -2313,34 +2704,28 @@ contract RegistryCoordinatorUnitTests_AfterMigration is RegistryCoordinatorUnitT } function test_registerHook_Reverts_WhenNotALM() public { - _deployMockEigenLayerAndAVS(0); // Enable operator sets first cheats.prank(registryCoordinatorOwner); registryCoordinator.enableOperatorSets(); // Create quorum params - IRegistryCoordinator.OperatorSetParam memory operatorSetParams = IRegistryCoordinator.OperatorSetParam({ + IRegistryCoordinator.OperatorSetParam memory operatorSetParams = IRegistryCoordinator + .OperatorSetParam({ maxOperatorCount: 10, kickBIPsOfOperatorStake: 1000, kickBIPsOfTotalStake: 100 }); uint96 minimumStake = 100; - IStakeRegistry.StrategyParams[] memory strategyParams = new IStakeRegistry.StrategyParams[](1); - strategyParams[0] = IStakeRegistry.StrategyParams({ - strategy: IStrategy(address(1)), - multiplier: 10000 - }); + IStakeRegistry.StrategyParams[] memory strategyParams = + new IStakeRegistry.StrategyParams[](1); + strategyParams[0] = + IStakeRegistry.StrategyParams({strategy: IStrategy(address(1)), multiplier: 10_000}); // Create total delegated stake quorum cheats.prank(registryCoordinatorOwner); - registryCoordinator.createTotalDelegatedStakeQuorum( - operatorSetParams, - 0, - strategyParams - ); - + registryCoordinator.createTotalDelegatedStakeQuorum(operatorSetParams, 0, strategyParams); uint32[] memory operatorSetIds = new uint32[](1); operatorSetIds[0] = 0; @@ -2361,33 +2746,28 @@ contract RegistryCoordinatorUnitTests_AfterMigration is RegistryCoordinatorUnitT } function test_deregisterHook_Reverts_WhenNotALM() public { - _deployMockEigenLayerAndAVS(0); // Enable operator sets first cheats.prank(registryCoordinatorOwner); registryCoordinator.enableOperatorSets(); // Create quorum params - IRegistryCoordinator.OperatorSetParam memory operatorSetParams = IRegistryCoordinator.OperatorSetParam({ + IRegistryCoordinator.OperatorSetParam memory operatorSetParams = IRegistryCoordinator + .OperatorSetParam({ maxOperatorCount: 10, kickBIPsOfOperatorStake: 1000, kickBIPsOfTotalStake: 100 }); uint96 minimumStake = 100; - IStakeRegistry.StrategyParams[] memory strategyParams = new IStakeRegistry.StrategyParams[](1); - strategyParams[0] = IStakeRegistry.StrategyParams({ - strategy: IStrategy(address(1)), - multiplier: 10000 - }); + IStakeRegistry.StrategyParams[] memory strategyParams = + new IStakeRegistry.StrategyParams[](1); + strategyParams[0] = + IStakeRegistry.StrategyParams({strategy: IStrategy(address(1)), multiplier: 10_000}); // Create total delegated stake quorum cheats.prank(registryCoordinatorOwner); - registryCoordinator.createTotalDelegatedStakeQuorum( - operatorSetParams, - 0, - strategyParams - ); + registryCoordinator.createTotalDelegatedStakeQuorum(operatorSetParams, 0, strategyParams); // Prank as allocation manager and call register hook uint32[] memory operatorSetIds = new uint32[](1); @@ -2404,14 +2784,12 @@ contract RegistryCoordinatorUnitTests_AfterMigration is RegistryCoordinatorUnitT bytes memory data = abi.encode(socket, params); - cheats.prank(address(registryCoordinator.allocationManager())); registryCoordinator.registerOperator(defaultOperator, operatorSetIds, data); cheats.stopPrank(); cheats.expectRevert(); registryCoordinator.deregisterOperator(defaultOperator, operatorSetIds); - } function test_DeregisterHook_Reverts_WhenM2Quorum() public { @@ -2421,5 +2799,4 @@ contract RegistryCoordinatorUnitTests_AfterMigration is RegistryCoordinatorUnitT function test_registerHook_Reverts_WhenM2Quorum() public { vm.skip(true); } - } diff --git a/test/unit/ServiceManagerBase.t.sol b/test/unit/ServiceManagerBase.t.sol index 572998ca..74f9e848 100644 --- a/test/unit/ServiceManagerBase.t.sol +++ b/test/unit/ServiceManagerBase.t.sol @@ -8,7 +8,8 @@ import { IRewardsCoordinatorTypes, IERC20 } from "eigenlayer-contracts/src/contracts/core/RewardsCoordinator.sol"; -import {PermissionController} from "eigenlayer-contracts/src/contracts/permissions/PermissionController.sol"; +import {PermissionController} from + "eigenlayer-contracts/src/contracts/permissions/PermissionController.sol"; import {StrategyBase} from "eigenlayer-contracts/src/contracts/strategies/StrategyBase.sol"; import {IStrategyManager} from "eigenlayer-contracts/src/contracts/interfaces/IStrategyManager.sol"; import {IServiceManagerBaseEvents} from "../events/IServiceManagerBaseEvents.sol"; @@ -25,8 +26,10 @@ contract ServiceManagerBase_UnitTests is MockAVSDeployer, IServiceManagerBaseEve uint32 MAX_FUTURE_LENGTH = 28 days; uint32 GENESIS_REWARDS_TIMESTAMP = 1_712_188_800; uint256 MAX_REWARDS_AMOUNT = 1e38 - 1; - uint32 OPERATOR_SET_GENESIS_REWARDS_TIMESTAMP = 0; /// TODO: what values should these have - uint32 OPERATOR_SET_MAX_RETROACTIVE_LENGTH = 0; /// TODO: What values these should have + uint32 OPERATOR_SET_GENESIS_REWARDS_TIMESTAMP = 0; + /// TODO: what values should these have + uint32 OPERATOR_SET_MAX_RETROACTIVE_LENGTH = 0; + /// TODO: What values these should have /// @notice Delay in timestamp before a posted root can be claimed against uint32 activationDelay = 7 days; @@ -47,7 +50,9 @@ contract ServiceManagerBase_UnitTests is MockAVSDeployer, IServiceManagerBaseEve // mapping to setting fuzzed inputs mapping(address => bool) public addressIsExcludedFromFuzzedInputs; - modifier filterFuzzedAddressInputs(address fuzzedAddress) { + modifier filterFuzzedAddressInputs( + address fuzzedAddress + ) { cheats.assume(!addressIsExcludedFromFuzzedInputs[fuzzedAddress]); _; } @@ -99,7 +104,10 @@ contract ServiceManagerBase_UnitTests is MockAVSDeployer, IServiceManagerBaseEve address(serviceManagerImplementation), address(proxyAdmin), abi.encodeWithSelector( - ServiceManagerMock.initialize.selector, serviceManager.owner(), msg.sender, msg.sender + ServiceManagerMock.initialize.selector, + serviceManager.owner(), + msg.sender, + msg.sender ) ) ) @@ -150,7 +158,8 @@ contract ServiceManagerBase_UnitTests is MockAVSDeployer, IServiceManagerBaseEve IERC20 token3 = new ERC20PresetFixedSupply( "pepe wif avs", "MOCK3", mockTokenInitialSupply, address(this) ); - strategyImplementation = new StrategyBase(IStrategyManager(address(strategyManagerMock)), pauserRegistry); + strategyImplementation = + new StrategyBase(IStrategyManager(address(strategyManagerMock)), pauserRegistry); strategyMock1 = StrategyBase( address( new TransparentUpgradeableProxy( @@ -200,7 +209,9 @@ contract ServiceManagerBase_UnitTests is MockAVSDeployer, IServiceManagerBaseEve } /// @dev Sort to ensure that the array is in ascending order for strategies - function _sortArrayAsc(IStrategy[] memory arr) internal pure returns (IStrategy[] memory) { + function _sortArrayAsc( + IStrategy[] memory arr + ) internal pure returns (IStrategy[] memory) { uint256 l = arr.length; for (uint256 i = 0; i < l; i++) { for (uint256 j = i + 1; j < l; j++) { @@ -218,10 +229,9 @@ contract ServiceManagerBase_UnitTests is MockAVSDeployer, IServiceManagerBaseEve return timestamp1 > timestamp2 ? timestamp1 : timestamp2; } - function testFuzz_createAVSRewardsSubmission_Revert_WhenNotOwner(address caller) - public - filterFuzzedAddressInputs(caller) - { + function testFuzz_createAVSRewardsSubmission_Revert_WhenNotOwner( + address caller + ) public filterFuzzedAddressInputs(caller) { cheats.assume(caller != rewardsInitiator); IRewardsCoordinator.RewardsSubmission[] memory rewardsSubmissions; @@ -289,15 +299,14 @@ contract ServiceManagerBase_UnitTests is MockAVSDeployer, IServiceManagerBaseEve rewardToken.approve(address(serviceManager), amount); // 4. call createAVSRewardsSubmission() with expected event emitted - uint256 rewardsInitiatorBalanceBefore = - rewardToken.balanceOf(address(rewardsInitiator)); - uint256 rewardsCoordinatorBalanceBefore = - rewardToken.balanceOf(address(rewardsCoordinator)); + uint256 rewardsInitiatorBalanceBefore = rewardToken.balanceOf(address(rewardsInitiator)); + uint256 rewardsCoordinatorBalanceBefore = rewardToken.balanceOf(address(rewardsCoordinator)); rewardToken.approve(address(rewardsCoordinator), amount); uint256 currSubmissionNonce = rewardsCoordinator.submissionNonce(address(serviceManager)); - bytes32 avsSubmissionHash = - keccak256(abi.encode(address(serviceManager), currSubmissionNonce, rewardsSubmissions[0])); + bytes32 avsSubmissionHash = keccak256( + abi.encode(address(serviceManager), currSubmissionNonce, rewardsSubmissions[0]) + ); cheats.expectEmit(true, true, true, true, address(rewardsCoordinator)); emit AVSRewardsSubmissionCreated( @@ -307,7 +316,9 @@ contract ServiceManagerBase_UnitTests is MockAVSDeployer, IServiceManagerBaseEve cheats.stopPrank(); assertTrue( - rewardsCoordinator.isAVSRewardsSubmissionHash(address(serviceManager), avsSubmissionHash), + rewardsCoordinator.isAVSRewardsSubmissionHash( + address(serviceManager), avsSubmissionHash + ), "reward submission hash not submitted" ); assertEq( @@ -342,8 +353,7 @@ contract ServiceManagerBase_UnitTests is MockAVSDeployer, IServiceManagerBaseEve uint256 startSubmissionNonce = rewardsCoordinator.submissionNonce(address(serviceManager)); _deployMockRewardTokens(rewardsInitiator, numSubmissions); - uint256[] memory avsBalancesBefore = - _getBalanceForTokens(rewardTokens, rewardsInitiator); + uint256[] memory avsBalancesBefore = _getBalanceForTokens(rewardTokens, rewardsInitiator); uint256[] memory rewardsCoordinatorBalancesBefore = _getBalanceForTokens(rewardTokens, address(rewardsCoordinator)); uint256[] memory amounts = new uint256[](numSubmissions); @@ -367,7 +377,8 @@ contract ServiceManagerBase_UnitTests is MockAVSDeployer, IServiceManagerBaseEve startTimestamp = startTimestamp - (startTimestamp % CALCULATION_INTERVAL_SECONDS); // 2. Create reward submission input param - IRewardsCoordinatorTypes.RewardsSubmission memory rewardsSubmission = IRewardsCoordinatorTypes.RewardsSubmission({ + IRewardsCoordinatorTypes.RewardsSubmission memory rewardsSubmission = + IRewardsCoordinatorTypes.RewardsSubmission({ strategiesAndMultipliers: defaultStrategyAndMultipliers, token: rewardTokens[i], amount: amounts[i], @@ -439,8 +450,7 @@ contract ServiceManagerBase_UnitTests is MockAVSDeployer, IServiceManagerBaseEve cheats.prank(rewardsInitiator); rewardToken.approve(address(serviceManager), mockTokenInitialSupply); uint256 avsBalanceBefore = rewardToken.balanceOf(rewardsInitiator); - uint256 rewardsCoordinatorBalanceBefore = - rewardToken.balanceOf(address(rewardsCoordinator)); + uint256 rewardsCoordinatorBalanceBefore = rewardToken.balanceOf(address(rewardsCoordinator)); uint256 totalAmount = 0; uint256[] memory amounts = new uint256[](numSubmissions); @@ -465,7 +475,8 @@ contract ServiceManagerBase_UnitTests is MockAVSDeployer, IServiceManagerBaseEve startTimestamp = startTimestamp - (startTimestamp % CALCULATION_INTERVAL_SECONDS); // 2. Create reward submission input param - IRewardsCoordinatorTypes.RewardsSubmission memory rewardsSubmission = IRewardsCoordinatorTypes.RewardsSubmission({ + IRewardsCoordinatorTypes.RewardsSubmission memory rewardsSubmission = + IRewardsCoordinatorTypes.RewardsSubmission({ strategiesAndMultipliers: defaultStrategyAndMultipliers, token: rewardToken, amount: amounts[i], @@ -532,4 +543,4 @@ contract ServiceManagerBase_UnitTests is MockAVSDeployer, IServiceManagerBaseEve cheats.prank(caller); serviceManager.setRewardsInitiator(newRewardsInitiator); } -} \ No newline at end of file +} diff --git a/test/unit/ServiceManagerRouter.t.sol b/test/unit/ServiceManagerRouter.t.sol index 2e3d1e94..cb44d6f6 100644 --- a/test/unit/ServiceManagerRouter.t.sol +++ b/test/unit/ServiceManagerRouter.t.sol @@ -49,17 +49,20 @@ contract ServiceManagerRouter_UnitTests is MockAVSDeployer { } function test_getOperatorRestakedStrategies_noStrats() public { - address[] memory strategies = router.getOperatorRestakedStrategies(address(dummyServiceManager), defaultOperator); + address[] memory strategies = + router.getOperatorRestakedStrategies(address(dummyServiceManager), defaultOperator); assertEq(strategies.length, 0); } function test_getOperatorRestakedStrategies_multipleStrats() public { - address[] memory strategies = router.getOperatorRestakedStrategies(address(serviceManager), defaultOperator); + address[] memory strategies = + router.getOperatorRestakedStrategies(address(serviceManager), defaultOperator); assertEq(strategies.length, 192); } function test_getOperatorRestakedStrategies_badImplementation() public { - address[] memory strategies = router.getOperatorRestakedStrategies(address(emptyContract), defaultOperator); + address[] memory strategies = + router.getOperatorRestakedStrategies(address(emptyContract), defaultOperator); assertEq(strategies.length, 1); assertEq(strategies[0], badReturn); } diff --git a/test/unit/StakeRegistryUnit.t.sol b/test/unit/StakeRegistryUnit.t.sol index aefb220e..ef479d7e 100644 --- a/test/unit/StakeRegistryUnit.t.sol +++ b/test/unit/StakeRegistryUnit.t.sol @@ -33,7 +33,9 @@ contract StakeRegistryUnitTests is MockAVSDeployer, IStakeRegistryEvents { uint256 gasUsed; - modifier fuzzOnlyInitializedQuorums(uint8 quorumNumber) { + modifier fuzzOnlyInitializedQuorums( + uint8 quorumNumber + ) { cheats.assume(initializedQuorumBitmap.isSet(quorumNumber)); _; } @@ -54,7 +56,11 @@ contract StakeRegistryUnitTests is MockAVSDeployer, IStakeRegistryEvents { ); stakeRegistryImplementation = new StakeRegistryHarness( - IRegistryCoordinator(address(registryCoordinator)), delegationMock, avsDirectoryMock, allocationManager, serviceManager + IRegistryCoordinator(address(registryCoordinator)), + delegationMock, + avsDirectoryMock, + allocationManager, + serviceManager ); stakeRegistry = StakeRegistryHarness( @@ -88,7 +94,9 @@ contract StakeRegistryUnitTests is MockAVSDeployer, IStakeRegistryEvents { * @dev Initialize a new quorum with `minimumStake` * The new quorum's number is sequential, starting with `nextQuorum` */ - function _initializeQuorum(uint96 minimumStake) internal { + function _initializeQuorum( + uint96 minimumStake + ) internal { uint8 quorumNumber = nextQuorum; IStakeRegistry.StrategyParams[] memory strategyParams = @@ -389,7 +397,9 @@ contract StakeRegistryUnitTests is MockAVSDeployer, IStakeRegistryEvents { /// @notice Given a fuzzed bitmap input, returns a bitmap and array of quorum numbers /// that are guaranteed to be initialized. - function _fuzz_getQuorums(uint192 fuzzy_Bitmap) internal view returns (uint192, bytes memory) { + function _fuzz_getQuorums( + uint192 fuzzy_Bitmap + ) internal view returns (uint192, bytes memory) { fuzzy_Bitmap &= initializedQuorumBitmap; cheats.assume(!fuzzy_Bitmap.isEmpty()); @@ -399,7 +409,9 @@ contract StakeRegistryUnitTests is MockAVSDeployer, IStakeRegistryEvents { /// @notice Returns a list of initialized quorums ending in a non-initialized quorum /// @param rand is used to determine how many legitimate quorums to insert, so we can /// check this works for lists of varying lengths - function _fuzz_getInvalidQuorums(bytes32 rand) internal returns (bytes memory) { + function _fuzz_getInvalidQuorums( + bytes32 rand + ) internal returns (bytes memory) { uint256 length = _randUint({rand: rand, min: 1, max: initializedQuorumBytes.length + 1}); bytes memory invalidQuorums = new bytes(length); @@ -431,11 +443,9 @@ contract StakeRegistryUnitTests is MockAVSDeployer, IStakeRegistryEvents { } /// @dev Return the minimum stakes required for a list of quorums - function _getMinimumStakes(bytes memory quorumNumbers) - internal - view - returns (uint96[] memory) - { + function _getMinimumStakes( + bytes memory quorumNumbers + ) internal view returns (uint96[] memory) { uint96[] memory minimumStakes = new uint96[](quorumNumbers.length); for (uint256 i = 0; i < quorumNumbers.length; i++) { @@ -463,11 +473,9 @@ contract StakeRegistryUnitTests is MockAVSDeployer, IStakeRegistryEvents { } /// @dev Return the most recent total stake update history entries - function _getLatestTotalStakeUpdates(bytes memory quorumNumbers) - internal - view - returns (IStakeRegistry.StakeUpdate[] memory) - { + function _getLatestTotalStakeUpdates( + bytes memory quorumNumbers + ) internal view returns (IStakeRegistry.StakeUpdate[] memory) { IStakeRegistry.StakeUpdate[] memory stakeUpdates = new IStakeRegistry.StakeUpdate[](quorumNumbers.length); @@ -500,11 +508,9 @@ contract StakeRegistryUnitTests is MockAVSDeployer, IStakeRegistryEvents { } /// @dev Return the lengths of the total stake update history - function _getTotalStakeHistoryLengths(bytes memory quorumNumbers) - internal - view - returns (uint256[] memory) - { + function _getTotalStakeHistoryLengths( + bytes memory quorumNumbers + ) internal view returns (uint256[] memory) { uint256[] memory historyLengths = new uint256[](quorumNumbers.length); for (uint256 i = 0; i < quorumNumbers.length; i++) { @@ -554,7 +560,9 @@ contract StakeRegistryUnitTests is MockAVSDeployer, IStakeRegistryEvents { } /// @dev Sort to ensure that the array is in desscending order for removeStrategies - function _sortArrayDesc(uint256[] memory arr) internal pure returns (uint256[] memory) { + function _sortArrayDesc( + uint256[] memory arr + ) internal pure returns (uint256[] memory) { uint256 l = arr.length; for (uint256 i = 0; i < l; i++) { for (uint256 j = i + 1; j < l; j++) { @@ -616,6 +624,7 @@ contract StakeRegistryUnitTests_Config is StakeRegistryUnitTests { cheats.prank(address(registryCoordinator)); stakeRegistry.initializeDelegatedStakeQuorum(quorumNumber, minimumStake, strategyParams); } + event StakeTypeSet(StakeType newStakeType); function test_initializeDelegatedStakeQuorum() public { @@ -631,11 +640,7 @@ contract StakeRegistryUnitTests_Config is StakeRegistryUnitTests { cheats.prank(address(registryCoordinator)); cheats.expectEmit(true, true, true, true); emit StakeTypeSet(StakeType.TOTAL_DELEGATED); - stakeRegistry.initializeDelegatedStakeQuorum( - quorumNumber, - minimumStake, - strategyParams - ); + stakeRegistry.initializeDelegatedStakeQuorum(quorumNumber, minimumStake, strategyParams); StakeType stakeType = stakeRegistry.stakeTypePerQuorum(quorumNumber); assertEq(uint8(stakeType), uint8(StakeType.TOTAL_DELEGATED), "invalid stake type"); @@ -655,10 +660,7 @@ contract StakeRegistryUnitTests_Config is StakeRegistryUnitTests { cheats.expectEmit(true, true, true, true); emit StakeTypeSet(StakeType.TOTAL_SLASHABLE); stakeRegistry.initializeSlashableStakeQuorum( - quorumNumber, - minimumStake, - 7 days, - strategyParams + quorumNumber, minimumStake, 7 days, strategyParams ); StakeType stakeType = stakeRegistry.stakeTypePerQuorum(quorumNumber); @@ -984,10 +986,9 @@ contract StakeRegistryUnitTests_Config is StakeRegistryUnitTests { stakeRegistry.modifyStrategyParams(quorumNumber, strategyIndices, newMultipliers); } - function testFuzz_modifyStrategyParams_Revert_WhenEmptyArray(uint8 quorumNumber) - public - fuzzOnlyInitializedQuorums(quorumNumber) - { + function testFuzz_modifyStrategyParams_Revert_WhenEmptyArray( + uint8 quorumNumber + ) public fuzzOnlyInitializedQuorums(quorumNumber) { uint256[] memory strategyIndices = new uint256[](0); uint96[] memory newMultipliers = new uint96[](0); cheats.expectRevert(IStakeRegistryErrors.InputArrayLengthZero.selector); @@ -1065,7 +1066,9 @@ contract StakeRegistryUnitTests_Register is StakeRegistryUnitTests { stakeRegistry.registerOperator(operator, operatorId, initializedQuorumBytes); } - function testFuzz_Revert_WhenQuorumDoesNotExist(bytes32 rand) public { + function testFuzz_Revert_WhenQuorumDoesNotExist( + bytes32 rand + ) public { RegisterSetup memory setup = _fuzz_setupRegisterOperator(initializedQuorumBitmap, 0); // Get a list of valid quorums ending in an invalid quorum number @@ -1078,10 +1081,9 @@ contract StakeRegistryUnitTests_Register is StakeRegistryUnitTests { /// @dev Attempt to register for all quorums, selecting one quorum to attempt with /// insufficient stake - function testFuzz_registerOperator_Revert_WhenInsufficientStake(uint8 failingQuorum) - public - fuzzOnlyInitializedQuorums(failingQuorum) - { + function testFuzz_registerOperator_Revert_WhenInsufficientStake( + uint8 failingQuorum + ) public fuzzOnlyInitializedQuorums(failingQuorum) { (address operator, bytes32 operatorId) = _selectNewOperator(); bytes memory quorumNumbers = initializedQuorumBytes; uint96[] memory minimumStakes = _getMinimumStakes(quorumNumbers); @@ -1415,7 +1417,9 @@ contract StakeRegistryUnitTests_Deregister is StakeRegistryUnitTests { stakeRegistry.deregisterOperator(setup.operatorId, setup.quorumsToRemove); } - function testFuzz_deregisterOperator_Revert_WhenQuorumDoesNotExist(bytes32 rand) public { + function testFuzz_deregisterOperator_Revert_WhenQuorumDoesNotExist( + bytes32 rand + ) public { // Create a new operator registered for all quorums DeregisterSetup memory setup = _fuzz_setupDeregisterOperator({ registeredFor: initializedQuorumBitmap, @@ -1777,7 +1781,9 @@ contract StakeRegistryUnitTests_StakeUpdates is StakeRegistryUnitTests { stakeRegistry.updateOperatorStake(setup.operator, setup.operatorId, setup.quorumNumbers); } - function testFuzz_updateOperatorStake_Revert_WhenQuorumDoesNotExist(bytes32 rand) public { + function testFuzz_updateOperatorStake_Revert_WhenQuorumDoesNotExist( + bytes32 rand + ) public { // Create a new operator registered for all quorums UpdateSetup memory setup = _fuzz_setupUpdateOperatorStake({registeredFor: initializedQuorumBitmap, fuzzy_Delta: 0}); @@ -1798,7 +1804,9 @@ contract StakeRegistryUnitTests_StakeUpdates is StakeRegistryUnitTests { * updateOperatorStake should then update the operator's stake using the new weight - we test * what happens when the operator remains at/above minimum stake, vs dipping below */ - function testFuzz_updateOperatorStake_SingleOperator_SingleBlock(int8 stakeDelta) public { + function testFuzz_updateOperatorStake_SingleOperator_SingleBlock( + int8 stakeDelta + ) public { UpdateSetup memory setup = _fuzz_setupUpdateOperatorStake({ registeredFor: initializedQuorumBitmap, fuzzy_Delta: stakeDelta @@ -2183,7 +2191,9 @@ contract StakeRegistryUnitTests_weightOfOperatorForQuorum is StakeRegistryUnitTe } cheats.prank(address(registryCoordinator)); uint8 quorumNumber = nextQuorum; - stakeRegistry.initializeDelegatedStakeQuorum(quorumNumber, 0, /* minimumStake */ strategyParams); + stakeRegistry.initializeDelegatedStakeQuorum( + quorumNumber, 0, /* minimumStake */ strategyParams + ); // set the operator shares for (uint256 i = 0; i < strategyParams.length; i++) { @@ -2230,7 +2240,9 @@ contract StakeRegistryUnitTests_weightOfOperatorForQuorum is StakeRegistryUnitTe // create a valid quorum cheats.prank(address(registryCoordinator)); uint8 quorumNumber = nextQuorum; - stakeRegistry.initializeDelegatedStakeQuorum(quorumNumber, 0, /* minimumStake */ strategyParams); + stakeRegistry.initializeDelegatedStakeQuorum( + quorumNumber, 0, /* minimumStake */ strategyParams + ); // set the operator shares for (uint256 i = 0; i < strategyParams.length; i++) { diff --git a/test/unit/UpgradeableProxyLib.sol b/test/unit/UpgradeableProxyLib.sol index 15fd49d8..0f0986f5 100644 --- a/test/unit/UpgradeableProxyLib.sol +++ b/test/unit/UpgradeableProxyLib.sol @@ -1,12 +1,12 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; + import {Vm} from "forge-std/Vm.sol"; import {ProxyAdmin} from "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol"; import {TransparentUpgradeableProxy} from "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol"; -contract EmptyContract { -} +contract EmptyContract {} library UpgradeableProxyLib { bytes32 internal constant IMPLEMENTATION_SLOT = @@ -14,33 +14,39 @@ library UpgradeableProxyLib { bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; Vm internal constant vm = Vm(address(uint160(uint256(keccak256("hevm cheat code"))))); + function deployProxyAdmin() internal returns (address) { return address(new ProxyAdmin()); } + function setUpEmptyProxy( address admin ) internal returns (address) { address emptyContract = address(new EmptyContract()); return address(new TransparentUpgradeableProxy(emptyContract, admin, "")); } + function upgrade(address proxy, address impl) internal { ProxyAdmin admin = getProxyAdmin(proxy); admin.upgrade(TransparentUpgradeableProxy(payable(proxy)), impl); } + function upgradeAndCall(address proxy, address impl, bytes memory initData) internal { ProxyAdmin admin = getProxyAdmin(proxy); admin.upgradeAndCall(TransparentUpgradeableProxy(payable(proxy)), impl, initData); } + function getImplementation( address proxy ) internal view returns (address) { bytes32 value = vm.load(proxy, IMPLEMENTATION_SLOT); return address(uint160(uint256(value))); } + function getProxyAdmin( address proxy ) internal view returns (ProxyAdmin) { bytes32 value = vm.load(proxy, ADMIN_SLOT); return ProxyAdmin(address(uint160(uint256(value)))); } -} \ No newline at end of file +} diff --git a/test/unit/Utils.sol b/test/unit/Utils.sol index 6e085215..463d8a3b 100644 --- a/test/unit/Utils.sol +++ b/test/unit/Utils.sol @@ -6,16 +6,15 @@ import "eigenlayer-contracts/src/contracts/strategies/StrategyBase.sol"; contract Utils { address constant dummyAdmin = address(uint160(uint256(keccak256("DummyAdmin")))); - function deployNewStrategy(IERC20 token, IStrategyManager strategyManager, IPauserRegistry pauserRegistry, address admin) public returns (StrategyBase) { + function deployNewStrategy( + IERC20 token, + IStrategyManager strategyManager, + IPauserRegistry pauserRegistry, + address admin + ) public returns (StrategyBase) { StrategyBase newStrategy = new StrategyBase(strategyManager, pauserRegistry); newStrategy = StrategyBase( - address( - new TransparentUpgradeableProxy( - address(newStrategy), - address(admin), - "" - ) - ) + address(new TransparentUpgradeableProxy(address(newStrategy), address(admin), "")) ); newStrategy.initialize(token); return newStrategy; diff --git a/test/utils/BLSMockAVSDeployer.sol b/test/utils/BLSMockAVSDeployer.sol index 7923fca4..84890944 100644 --- a/test/utils/BLSMockAVSDeployer.sol +++ b/test/utils/BLSMockAVSDeployer.sol @@ -16,55 +16,73 @@ contract BLSMockAVSDeployer is MockAVSDeployer { BN254.G2Point oneHundredQuorumApkG2; BN254.G1Point sigma; - function _setUpBLSMockAVSDeployer() virtual public { + function _setUpBLSMockAVSDeployer() public virtual { _deployMockEigenLayerAndAVS(); _setAggregatePublicKeysAndSignature(); } - function _setUpBLSMockAVSDeployer(uint8 numQuorumsToAdd) virtual public { + function _setUpBLSMockAVSDeployer( + uint8 numQuorumsToAdd + ) public virtual { _deployMockEigenLayerAndAVS(numQuorumsToAdd); _setAggregatePublicKeysAndSignature(); } function _setAggregatePublicKeysAndSignature() internal { // aggSignerPrivKey*g2 - aggSignerApkG2.X[1] = 19101821850089705274637533855249918363070101489527618151493230256975900223847; - aggSignerApkG2.X[0] = 5334410886741819556325359147377682006012228123419628681352847439302316235957; - aggSignerApkG2.Y[1] = 354176189041917478648604979334478067325821134838555150300539079146482658331; - aggSignerApkG2.Y[0] = 4185483097059047421902184823581361466320657066600218863748375739772335928910; + aggSignerApkG2.X[1] = + 19_101_821_850_089_705_274_637_533_855_249_918_363_070_101_489_527_618_151_493_230_256_975_900_223_847; + aggSignerApkG2.X[0] = + 5_334_410_886_741_819_556_325_359_147_377_682_006_012_228_123_419_628_681_352_847_439_302_316_235_957; + aggSignerApkG2.Y[1] = + 354_176_189_041_917_478_648_604_979_334_478_067_325_821_134_838_555_150_300_539_079_146_482_658_331; + aggSignerApkG2.Y[0] = + 4_185_483_097_059_047_421_902_184_823_581_361_466_320_657_066_600_218_863_748_375_739_772_335_928_910; // 100*aggSignerPrivKey*g2 - oneHundredQuorumApkG2.X[1] = 6187649255575786743153792867265230878737103598736372524337965086852090105771; - oneHundredQuorumApkG2.X[0] = 5334877400925935887383922877430837542135722474116902175395820705628447222839; - oneHundredQuorumApkG2.Y[1] = 4668116328019846503695710811760363536142902258271850958815598072072236299223; - oneHundredQuorumApkG2.Y[0] = 21446056442597180561077194011672151329458819211586246807143487001691968661015; + oneHundredQuorumApkG2.X[1] = + 6_187_649_255_575_786_743_153_792_867_265_230_878_737_103_598_736_372_524_337_965_086_852_090_105_771; + oneHundredQuorumApkG2.X[0] = + 5_334_877_400_925_935_887_383_922_877_430_837_542_135_722_474_116_902_175_395_820_705_628_447_222_839; + oneHundredQuorumApkG2.Y[1] = + 4_668_116_328_019_846_503_695_710_811_760_363_536_142_902_258_271_850_958_815_598_072_072_236_299_223; + oneHundredQuorumApkG2.Y[0] = + 21_446_056_442_597_180_561_077_194_011_672_151_329_458_819_211_586_246_807_143_487_001_691_968_661_015; sigma = BN254.hashToG1(msgHash).scalar_mul(aggSignerPrivKey); } - - function _generateSignerAndNonSignerPrivateKeys(uint256 pseudoRandomNumber, uint256 numSigners, uint256 numNonSigners) internal view returns (uint256[] memory, uint256[] memory) { + function _generateSignerAndNonSignerPrivateKeys( + uint256 pseudoRandomNumber, + uint256 numSigners, + uint256 numNonSigners + ) internal view returns (uint256[] memory, uint256[] memory) { uint256[] memory signerPrivateKeys = new uint256[](numSigners); // generate numSigners numbers that add up to aggSignerPrivKey mod BN254.FR_MODULUS uint256 sum = 0; - for (uint i = 0; i < numSigners - 1; i++) { - signerPrivateKeys[i] = uint256(keccak256(abi.encodePacked("signerPrivateKey", pseudoRandomNumber, i))) % BN254.FR_MODULUS; + for (uint256 i = 0; i < numSigners - 1; i++) { + signerPrivateKeys[i] = uint256( + keccak256(abi.encodePacked("signerPrivateKey", pseudoRandomNumber, i)) + ) % BN254.FR_MODULUS; sum = addmod(sum, signerPrivateKeys[i], BN254.FR_MODULUS); } // signer private keys need to add to aggSignerPrivKey - signerPrivateKeys[numSigners - 1] = addmod(aggSignerPrivKey, BN254.FR_MODULUS - sum % BN254.FR_MODULUS, BN254.FR_MODULUS); + signerPrivateKeys[numSigners - 1] = + addmod(aggSignerPrivKey, BN254.FR_MODULUS - sum % BN254.FR_MODULUS, BN254.FR_MODULUS); uint256[] memory nonSignerPrivateKeys = new uint256[](numNonSigners); - for (uint i = 0; i < numNonSigners; i++) { - nonSignerPrivateKeys[i] = uint256(keccak256(abi.encodePacked("nonSignerPrivateKey", pseudoRandomNumber, i))) % BN254.FR_MODULUS; + for (uint256 i = 0; i < numNonSigners; i++) { + nonSignerPrivateKeys[i] = uint256( + keccak256(abi.encodePacked("nonSignerPrivateKey", pseudoRandomNumber, i)) + ) % BN254.FR_MODULUS; } // Sort nonSignerPrivateKeys in order of ascending pubkeyHash // Uses insertion sort to sort array in place - for (uint i = 1; i < nonSignerPrivateKeys.length; i++) { - uint privateKey = nonSignerPrivateKeys[i]; + for (uint256 i = 1; i < nonSignerPrivateKeys.length; i++) { + uint256 privateKey = nonSignerPrivateKeys[i]; bytes32 pubkeyHash = _toPubkeyHash(privateKey); - uint j = i; + uint256 j = i; // Move elements of nonSignerPrivateKeys[0..i-1] that are greater than the current key // to one position ahead of their current position @@ -78,8 +96,15 @@ contract BLSMockAVSDeployer is MockAVSDeployer { return (signerPrivateKeys, nonSignerPrivateKeys); } - function _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom(uint256 pseudoRandomNumber, uint256 numNonSigners, uint256 quorumBitmap) internal returns(uint32, BLSSignatureChecker.NonSignerStakesAndSignature memory) { - (uint256[] memory signerPrivateKeys, uint256[] memory nonSignerPrivateKeys) = _generateSignerAndNonSignerPrivateKeys(pseudoRandomNumber, maxOperatorsToRegister - numNonSigners, numNonSigners); + function _registerSignatoriesAndGetNonSignerStakeAndSignatureRandom( + uint256 pseudoRandomNumber, + uint256 numNonSigners, + uint256 quorumBitmap + ) internal returns (uint32, BLSSignatureChecker.NonSignerStakesAndSignature memory) { + (uint256[] memory signerPrivateKeys, uint256[] memory nonSignerPrivateKeys) = + _generateSignerAndNonSignerPrivateKeys( + pseudoRandomNumber, maxOperatorsToRegister - numNonSigners, numNonSigners + ); bytes memory quorumNumbers = BitmapUtils.bitmapToBytesArray(quorumBitmap); // randomly combine signer and non-signer private keys @@ -94,15 +119,17 @@ contract BLSMockAVSDeployer is MockAVSDeployer { { uint256 signerIndex = 0; uint256 nonSignerIndex = 0; - for (uint i = 0; i < maxOperatorsToRegister; i++) { + for (uint256 i = 0; i < maxOperatorsToRegister; i++) { uint256 randomSeed = uint256(keccak256(abi.encodePacked("privKeyCombination", i))); if (randomSeed % 2 == 0 && signerIndex < signerPrivateKeys.length) { privateKeys[i] = signerPrivateKeys[signerIndex]; signerIndex++; } else if (nonSignerIndex < nonSignerPrivateKeys.length) { privateKeys[i] = nonSignerPrivateKeys[nonSignerIndex]; - nonSignerStakesAndSignature.nonSignerPubkeys[nonSignerIndex] = BN254.generatorG1().scalar_mul(privateKeys[i]); - nonSignerOperatorIds[nonSignerIndex] = nonSignerStakesAndSignature.nonSignerPubkeys[nonSignerIndex].hashG1Point(); + nonSignerStakesAndSignature.nonSignerPubkeys[nonSignerIndex] = + BN254.generatorG1().scalar_mul(privateKeys[i]); + nonSignerOperatorIds[nonSignerIndex] = + nonSignerStakesAndSignature.nonSignerPubkeys[nonSignerIndex].hashG1Point(); nonSignerIndex++; } else { privateKeys[i] = signerPrivateKeys[signerIndex]; @@ -113,39 +140,43 @@ contract BLSMockAVSDeployer is MockAVSDeployer { pubkeys[i] = BN254.generatorG1().scalar_mul(privateKeys[i]); // add the public key to each quorum - for (uint j = 0; j < nonSignerStakesAndSignature.quorumApks.length; j++) { - nonSignerStakesAndSignature.quorumApks[j] = nonSignerStakesAndSignature.quorumApks[j].plus(pubkeys[i]); + for (uint256 j = 0; j < nonSignerStakesAndSignature.quorumApks.length; j++) { + nonSignerStakesAndSignature.quorumApks[j] = + nonSignerStakesAndSignature.quorumApks[j].plus(pubkeys[i]); } } } // register all operators for the first quorum - for (uint i = 0; i < maxOperatorsToRegister; i++) { + for (uint256 i = 0; i < maxOperatorsToRegister; i++) { cheats.roll(registrationBlockNumber + blocksBetweenRegistrations * i); _registerOperatorWithCoordinator(operators[i], quorumBitmap, pubkeys[i], defaultStake); } - uint32 referenceBlockNumber = registrationBlockNumber + blocksBetweenRegistrations * uint32(maxOperatorsToRegister) + 1; + uint32 referenceBlockNumber = registrationBlockNumber + + blocksBetweenRegistrations * uint32(maxOperatorsToRegister) + 1; cheats.roll(referenceBlockNumber + 100); - OperatorStateRetriever.CheckSignaturesIndices memory checkSignaturesIndices = operatorStateRetriever.getCheckSignaturesIndices( - registryCoordinator, - referenceBlockNumber, - quorumNumbers, - nonSignerOperatorIds + OperatorStateRetriever.CheckSignaturesIndices memory checkSignaturesIndices = + operatorStateRetriever.getCheckSignaturesIndices( + registryCoordinator, referenceBlockNumber, quorumNumbers, nonSignerOperatorIds ); - nonSignerStakesAndSignature.nonSignerQuorumBitmapIndices = checkSignaturesIndices.nonSignerQuorumBitmapIndices; + nonSignerStakesAndSignature.nonSignerQuorumBitmapIndices = + checkSignaturesIndices.nonSignerQuorumBitmapIndices; nonSignerStakesAndSignature.apkG2 = aggSignerApkG2; nonSignerStakesAndSignature.sigma = sigma; nonSignerStakesAndSignature.quorumApkIndices = checkSignaturesIndices.quorumApkIndices; nonSignerStakesAndSignature.totalStakeIndices = checkSignaturesIndices.totalStakeIndices; - nonSignerStakesAndSignature.nonSignerStakeIndices = checkSignaturesIndices.nonSignerStakeIndices; + nonSignerStakesAndSignature.nonSignerStakeIndices = + checkSignaturesIndices.nonSignerStakeIndices; return (referenceBlockNumber, nonSignerStakesAndSignature); } - function _toPubkeyHash(uint privKey) internal view returns (bytes32) { + function _toPubkeyHash( + uint256 privKey + ) internal view returns (bytes32) { return BN254.generatorG1().scalar_mul(privKey).hashG1Point(); } } diff --git a/test/utils/CoreDeployLib.sol b/test/utils/CoreDeployLib.sol index d88f6ff6..d25dd95a 100644 --- a/test/utils/CoreDeployLib.sol +++ b/test/utils/CoreDeployLib.sol @@ -268,4 +268,4 @@ // return result; // } -// } \ No newline at end of file +// } diff --git a/test/utils/MockAVSDeployer.sol b/test/utils/MockAVSDeployer.sol index a0ef478e..15e6d425 100644 --- a/test/utils/MockAVSDeployer.sol +++ b/test/utils/MockAVSDeployer.sol @@ -35,7 +35,8 @@ import {RewardsCoordinatorMock} from "../mocks/RewardsCoordinatorMock.sol"; import {PermissionControllerMock} from "../mocks/PermissionControllerMock.sol"; import {RewardsCoordinator} from "eigenlayer-contracts/src/contracts/core/RewardsCoordinator.sol"; -import {PermissionController} from "eigenlayer-contracts/src/contracts/permissions/PermissionController.sol"; +import {PermissionController} from + "eigenlayer-contracts/src/contracts/permissions/PermissionController.sol"; import {AllocationManager} from "eigenlayer-contracts/src/contracts/core/AllocationManager.sol"; import {IRewardsCoordinator} from "eigenlayer-contracts/src/contracts/interfaces/IRewardsCoordinator.sol"; @@ -137,7 +138,9 @@ contract MockAVSDeployer is Test { _deployMockEigenLayerAndAVS(numQuorums); } - function _deployMockEigenLayerAndAVS(uint8 numQuorumsToAdd) internal { + function _deployMockEigenLayerAndAVS( + uint8 numQuorumsToAdd + ) internal { emptyContract = new EmptyContract(); defaultOperatorId = defaultPubKey.hashG1Point(); @@ -205,8 +208,13 @@ contract MockAVSDeployer is Test { cheats.startPrank(proxyAdminOwner); - stakeRegistryImplementation = - new StakeRegistryHarness(IRegistryCoordinator(registryCoordinator), delegationMock, avsDirectory, allocationManagerMock, serviceManager); + stakeRegistryImplementation = new StakeRegistryHarness( + IRegistryCoordinator(registryCoordinator), + delegationMock, + avsDirectory, + allocationManagerMock, + serviceManager + ); proxyAdmin.upgrade( TransparentUpgradeableProxy(payable(address(stakeRegistry))), address(stakeRegistryImplementation) @@ -241,7 +249,7 @@ contract MockAVSDeployer is Test { pauserRegistry, permissionControllerMock, uint32(7 days), // DEALLOCATION_DELAY - uint32(1 days) // ALLOCATION_CONFIGURATION_DELAY + uint32(1 days) // ALLOCATION_CONFIGURATION_DELAY ); proxyAdmin.upgrade( TransparentUpgradeableProxy(payable(address(allocationManager))), @@ -273,7 +281,12 @@ contract MockAVSDeployer is Test { } registryCoordinatorImplementation = new RegistryCoordinatorHarness( - serviceManager, stakeRegistry, blsApkRegistry, indexRegistry, allocationManagerMock, pauserRegistry + serviceManager, + stakeRegistry, + blsApkRegistry, + indexRegistry, + allocationManagerMock, + pauserRegistry ); { delete operatorSetParams; @@ -314,7 +327,8 @@ contract MockAVSDeployer is Test { quorumStakeTypes, // _stakeTypes slashableStakeQuorumLookAheadPeriods // _lookAheadPeriods ) - )); + ) + ); } operatorStateRetriever = new OperatorStateRetriever(); @@ -410,10 +424,9 @@ contract MockAVSDeployer is Test { ); } - function _registerRandomOperators(uint256 pseudoRandomNumber) - internal - returns (OperatorMetadata[] memory, uint256[][] memory) - { + function _registerRandomOperators( + uint256 pseudoRandomNumber + ) internal returns (OperatorMetadata[] memory, uint256[][] memory) { OperatorMetadata[] memory operatorMetadatas = new OperatorMetadata[](maxOperatorsToRegister); for (uint256 i = 0; i < operatorMetadatas.length; i++) { // limit to 16 quorums so we don't run out of gas, make them all register for quorum 0 as well diff --git a/test/utils/Operators.sol b/test/utils/Operators.sol index 266ed8d8..05a2ad78 100644 --- a/test/utils/Operators.sol +++ b/test/utils/Operators.sol @@ -12,19 +12,26 @@ contract Operators is Test { operatorConfigJson = vm.readFile("./src/test/test-data/operators.json"); } - function operatorPrefix(uint256 index) public pure returns(string memory) { + function operatorPrefix( + uint256 index + ) public pure returns (string memory) { return string.concat(".operators[", string.concat(vm.toString(index), "].")); } - function getNumOperators() public view returns(uint256) { + function getNumOperators() public view returns (uint256) { return stdJson.readUint(operatorConfigJson, ".numOperators"); } - function getOperatorAddress(uint256 index) public view returns(address) { - return stdJson.readAddress(operatorConfigJson, string.concat(operatorPrefix(index), "Address")); + function getOperatorAddress( + uint256 index + ) public view returns (address) { + return + stdJson.readAddress(operatorConfigJson, string.concat(operatorPrefix(index), "Address")); } - function getOperatorSchnorrSignature(uint256 index) public view returns(uint256, BN254.G1Point memory) { + function getOperatorSchnorrSignature( + uint256 index + ) public view returns (uint256, BN254.G1Point memory) { uint256 s = readUint(operatorConfigJson, index, "SField"); BN254.G1Point memory pubkey = BN254.G1Point({ X: readUint(operatorConfigJson, index, "RPoint.X"), @@ -33,11 +40,15 @@ contract Operators is Test { return (s, pubkey); } - function getOperatorSecretKey(uint256 index) public view returns(uint256) { + function getOperatorSecretKey( + uint256 index + ) public view returns (uint256) { return readUint(operatorConfigJson, index, "SecretKey"); } - function getOperatorPubkeyG1(uint256 index) public view returns(BN254.G1Point memory) { + function getOperatorPubkeyG1( + uint256 index + ) public view returns (BN254.G1Point memory) { BN254.G1Point memory pubkey = BN254.G1Point({ X: readUint(operatorConfigJson, index, "PubkeyG1.X"), Y: readUint(operatorConfigJson, index, "PubkeyG1.Y") @@ -45,7 +56,9 @@ contract Operators is Test { return pubkey; } - function getOperatorPubkeyG2(uint256 index) public view returns(BN254.G2Point memory) { + function getOperatorPubkeyG2( + uint256 index + ) public view returns (BN254.G2Point memory) { BN254.G2Point memory pubkey = BN254.G2Point({ X: [ readUint(operatorConfigJson, index, "PubkeyG2.X.A1"), @@ -59,11 +72,17 @@ contract Operators is Test { return pubkey; } - function readUint(string memory json, uint256 index, string memory key) public pure returns (uint256) { + function readUint( + string memory json, + uint256 index, + string memory key + ) public pure returns (uint256) { return stringToUint(stdJson.readString(json, string.concat(operatorPrefix(index), key))); } - function stringToUint(string memory s) public pure returns (uint256) { + function stringToUint( + string memory s + ) public pure returns (uint256) { bytes memory b = bytes(s); uint256 result = 0; for (uint256 i = 0; i < b.length; i++) { @@ -73,7 +92,10 @@ contract Operators is Test { } return result; } - function setOperatorJsonFilePath(string memory filepath) public { + + function setOperatorJsonFilePath( + string memory filepath + ) public { operatorConfigJson = vm.readFile(filepath); } } diff --git a/test/utils/Owners.sol b/test/utils/Owners.sol index cdb3add2..88155fa3 100644 --- a/test/utils/Owners.sol +++ b/test/utils/Owners.sol @@ -13,26 +13,30 @@ contract Owners is Test { ownersConfigJson = vm.readFile("./src/test/test-data/owners.json"); } - function ownerPrefix(uint256 index) public pure returns(string memory) { + function ownerPrefix( + uint256 index + ) public pure returns (string memory) { return string.concat(".owners[", string.concat(vm.toString(index), "].")); } - function getNumOperators() public view returns(uint256) { + function getNumOperators() public view returns (uint256) { return stdJson.readUint(ownersConfigJson, ".numOwners"); } - function getOwnerAddress(uint256 index) public view returns(address) { + function getOwnerAddress( + uint256 index + ) public view returns (address) { return stdJson.readAddress(ownersConfigJson, string.concat(ownerPrefix(index), "Address")); } - function getOwnerAddresses() public returns(address[] memory) { + function getOwnerAddresses() public returns (address[] memory) { for (uint256 i = 0; i < getNumOperators(); i++) { addresses.push(getOwnerAddress(i)); } return addresses; } - function getReputedOwnerAddresses() public returns(address[] memory) { + function getReputedOwnerAddresses() public returns (address[] memory) { resetOwnersConfigJson("reputedOwners.json"); for (uint256 i = 0; i < getNumOperators(); i++) { addresses.push(getOwnerAddress(i)); @@ -40,8 +44,9 @@ contract Owners is Test { return addresses; } - function resetOwnersConfigJson(string memory newConfig) public { + function resetOwnersConfigJson( + string memory newConfig + ) public { ownersConfigJson = vm.readFile(newConfig); } - } diff --git a/test/utils/ProofParsing.sol b/test/utils/ProofParsing.sol index 14ad89c6..cec8283f 100644 --- a/test/utils/ProofParsing.sol +++ b/test/utils/ProofParsing.sol @@ -5,8 +5,7 @@ import "../../src/libraries/BN254.sol"; import "forge-std/Test.sol"; import "forge-std/StdJson.sol"; - -contract ProofParsing is Test{ +contract ProofParsing is Test { string internal proofConfigJson; string prefix; @@ -16,184 +15,186 @@ contract ProofParsing is Test{ bytes32[46] validatorProof; bytes32[44] historicalSummaryProof; - - bytes32[7] executionPayloadProof; bytes32[4] timestampProofs; - bytes32 slotRoot; bytes32 executionPayloadRoot; - function setJSON(string memory path) public { + function setJSON( + string memory path + ) public { proofConfigJson = vm.readFile(path); } - function getSlot() public view returns(uint256) { + function getSlot() public view returns (uint256) { return stdJson.readUint(proofConfigJson, ".slot"); } - function getValidatorIndex() public view returns(uint256) { + function getValidatorIndex() public view returns (uint256) { return stdJson.readUint(proofConfigJson, ".validatorIndex"); } - function getValidatorPubkeyHash() public view returns(bytes32) { + function getValidatorPubkeyHash() public view returns (bytes32) { return stdJson.readBytes32(proofConfigJson, ".ValidatorFields[0]"); } - function getWithdrawalIndex() public view returns(uint256) { + function getWithdrawalIndex() public view returns (uint256) { return stdJson.readUint(proofConfigJson, ".withdrawalIndex"); } - function getBlockRootIndex() public view returns(uint256) { + function getBlockRootIndex() public view returns (uint256) { return stdJson.readUint(proofConfigJson, ".blockHeaderRootIndex"); } - function getHistoricalSummaryIndex() public view returns(uint256) { + function getHistoricalSummaryIndex() public view returns (uint256) { return stdJson.readUint(proofConfigJson, ".historicalSummaryIndex"); } - function getBeaconStateRoot() public view returns(bytes32) { + function getBeaconStateRoot() public view returns (bytes32) { return stdJson.readBytes32(proofConfigJson, ".beaconStateRoot"); } - function getBlockRoot() public view returns(bytes32) { + function getBlockRoot() public view returns (bytes32) { return stdJson.readBytes32(proofConfigJson, ".blockHeaderRoot"); } - function getSlotRoot() public view returns(bytes32) { + function getSlotRoot() public view returns (bytes32) { return stdJson.readBytes32(proofConfigJson, ".slotRoot"); } - function getBalanceRoot() public view returns(bytes32) { + function getBalanceRoot() public view returns (bytes32) { return stdJson.readBytes32(proofConfigJson, ".balanceRoot"); } - function getTimestampRoot() public view returns(bytes32) { + function getTimestampRoot() public view returns (bytes32) { return stdJson.readBytes32(proofConfigJson, ".timestampRoot"); } - function getExecutionPayloadRoot() public view returns(bytes32) { + function getExecutionPayloadRoot() public view returns (bytes32) { return stdJson.readBytes32(proofConfigJson, ".executionPayloadRoot"); } - function getLatestBlockRoot() public view returns(bytes32) { + function getLatestBlockRoot() public view returns (bytes32) { return stdJson.readBytes32(proofConfigJson, ".latestBlockHeaderRoot"); } - function getExecutionPayloadProof () public returns(bytes32[7] memory) { - for (uint i = 0; i < 7; i++) { + + function getExecutionPayloadProof() public returns (bytes32[7] memory) { + for (uint256 i = 0; i < 7; i++) { prefix = string.concat(".ExecutionPayloadProof[", string.concat(vm.toString(i), "]")); executionPayloadProof[i] = (stdJson.readBytes32(proofConfigJson, prefix)); } return executionPayloadProof; } - function getTimestampProof() public returns(bytes32[4] memory) { - for (uint i = 0; i < 4; i++) { + function getTimestampProof() public returns (bytes32[4] memory) { + for (uint256 i = 0; i < 4; i++) { prefix = string.concat(".TimestampProof[", string.concat(vm.toString(i), "]")); timestampProofs[i] = (stdJson.readBytes32(proofConfigJson, prefix)); } return timestampProofs; } - function getBlockHeaderProof() public returns(bytes32[18] memory) { - for (uint i = 0; i < 18; i++) { + function getBlockHeaderProof() public returns (bytes32[18] memory) { + for (uint256 i = 0; i < 18; i++) { prefix = string.concat(".BlockHeaderProof[", string.concat(vm.toString(i), "]")); blockHeaderProof[i] = (stdJson.readBytes32(proofConfigJson, prefix)); } return blockHeaderProof; } - function getSlotProof() public returns(bytes32[3] memory) { - for (uint i = 0; i < 3; i++) { + function getSlotProof() public returns (bytes32[3] memory) { + for (uint256 i = 0; i < 3; i++) { prefix = string.concat(".SlotProof[", string.concat(vm.toString(i), "]")); slotProof[i] = (stdJson.readBytes32(proofConfigJson, prefix)); } return slotProof; } - function getStateRootProof() public returns(bytes32[] memory) { + function getStateRootProof() public returns (bytes32[] memory) { bytes32[] memory stateRootProof = new bytes32[](3); - for (uint i = 0; i < 3; i++) { - prefix = string.concat(".StateRootAgainstLatestBlockHeaderProof[", string.concat(vm.toString(i), "]")); + for (uint256 i = 0; i < 3; i++) { + prefix = string.concat( + ".StateRootAgainstLatestBlockHeaderProof[", string.concat(vm.toString(i), "]") + ); stateRootProof[i] = (stdJson.readBytes32(proofConfigJson, prefix)); } return stateRootProof; } - function getWithdrawalProof() public returns(bytes32[9] memory) { - for (uint i = 0; i < 9; i++) { + function getWithdrawalProof() public returns (bytes32[9] memory) { + for (uint256 i = 0; i < 9; i++) { prefix = string.concat(".WithdrawalProof[", string.concat(vm.toString(i), "]")); withdrawalProof[i] = (stdJson.readBytes32(proofConfigJson, prefix)); } return withdrawalProof; } - function getValidatorProof() public returns(bytes32[46] memory) { - for (uint i = 0; i < 46; i++) { + function getValidatorProof() public returns (bytes32[46] memory) { + for (uint256 i = 0; i < 46; i++) { prefix = string.concat(".ValidatorProof[", string.concat(vm.toString(i), "]")); validatorProof[i] = (stdJson.readBytes32(proofConfigJson, prefix)); } return validatorProof; } - function getHistoricalSummaryProof() public returns(bytes32[44] memory) { - for (uint i = 0; i < 44; i++) { + function getHistoricalSummaryProof() public returns (bytes32[44] memory) { + for (uint256 i = 0; i < 44; i++) { prefix = string.concat(".HistoricalSummaryProof[", string.concat(vm.toString(i), "]")); historicalSummaryProof[i] = (stdJson.readBytes32(proofConfigJson, prefix)); } return historicalSummaryProof; } - function getWithdrawalFields() public returns(bytes32[] memory) { + function getWithdrawalFields() public returns (bytes32[] memory) { bytes32[] memory withdrawalFields = new bytes32[](4); - for (uint i = 0; i < 4; i++) { + for (uint256 i = 0; i < 4; i++) { prefix = string.concat(".WithdrawalFields[", string.concat(vm.toString(i), "]")); withdrawalFields[i] = (stdJson.readBytes32(proofConfigJson, prefix)); } - return withdrawalFields; - + return withdrawalFields; } - function getValidatorFields() public returns(bytes32[] memory) { + function getValidatorFields() public returns (bytes32[] memory) { bytes32[] memory validatorFields = new bytes32[](8); - for (uint i = 0; i < 8; i++) { + for (uint256 i = 0; i < 8; i++) { prefix = string.concat(".ValidatorFields[", string.concat(vm.toString(i), "]")); validatorFields[i] = (stdJson.readBytes32(proofConfigJson, prefix)); } return validatorFields; } - function getValidatorBalanceProof() public returns(bytes32[] memory) { + function getValidatorBalanceProof() public returns (bytes32[] memory) { bytes32[] memory validatorBalanceProof = new bytes32[](44); - for (uint i = 0; i < 44; i++) { + for (uint256 i = 0; i < 44; i++) { prefix = string.concat(".ValidatorBalanceProof[", string.concat(vm.toString(i), "]")); validatorBalanceProof[i] = (stdJson.readBytes32(proofConfigJson, prefix)); } return validatorBalanceProof; } - function getBalanceUpdateSlotProof() public returns(bytes32[] memory) { + function getBalanceUpdateSlotProof() public returns (bytes32[] memory) { bytes32[] memory balanceUpdateSlotProof = new bytes32[](5); - for (uint i = 0; i < 5; i++) { + for (uint256 i = 0; i < 5; i++) { prefix = string.concat(".slotProof[", string.concat(vm.toString(i), "]")); balanceUpdateSlotProof[i] = (stdJson.readBytes32(proofConfigJson, prefix)); } return balanceUpdateSlotProof; } - function getWithdrawalCredentialProof() public returns(bytes32[] memory) { + function getWithdrawalCredentialProof() public returns (bytes32[] memory) { bytes32[] memory withdrawalCredenitalProof = new bytes32[](46); - for (uint i = 0; i < 46; i++) { - prefix = string.concat(".WithdrawalCredentialProof[", string.concat(vm.toString(i), "]")); + for (uint256 i = 0; i < 46; i++) { + prefix = + string.concat(".WithdrawalCredentialProof[", string.concat(vm.toString(i), "]")); withdrawalCredenitalProof[i] = (stdJson.readBytes32(proofConfigJson, prefix)); } return withdrawalCredenitalProof; } - function getValidatorFieldsProof() public returns(bytes32[] memory) { + function getValidatorFieldsProof() public returns (bytes32[] memory) { bytes32[] memory validatorFieldsProof = new bytes32[](46); - for (uint i = 0; i < 46; i++) { + for (uint256 i = 0; i < 46; i++) { prefix = string.concat(".ValidatorFieldsProof[", string.concat(vm.toString(i), "]")); validatorFieldsProof[i] = (stdJson.readBytes32(proofConfigJson, prefix)); } diff --git a/test/utils/SignatureCompaction.sol b/test/utils/SignatureCompaction.sol index 0bb98a1c..eac87690 100644 --- a/test/utils/SignatureCompaction.sol +++ b/test/utils/SignatureCompaction.sol @@ -5,7 +5,8 @@ import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; //small library for dealing with efficiently-packed signatures, where parameters v,r,s are packed into vs and r (64 bytes instead of 65) library SignatureCompaction { - bytes32 internal constant HALF_CURVE_ORDER = 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0; + bytes32 internal constant HALF_CURVE_ORDER = + 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0; function ecrecoverPacked(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) { (address recovered, ECDSA.RecoverError err) = ECDSA.tryRecover(hash, r, vs); @@ -13,7 +14,11 @@ library SignatureCompaction { return recovered; } - function packSignature(bytes32 r, bytes32 s, uint8 v) internal pure returns (bytes32, bytes32) { + function packSignature( + bytes32 r, + bytes32 s, + uint8 v + ) internal pure returns (bytes32, bytes32) { require(s <= HALF_CURVE_ORDER, "malleable signature, s too high"); //v parity is a single bit, encoded as either v = 27 or v = 28 -- in order to recover the bit we subtract 27 bytes32 vs = bytes32(uint256(bytes32(uint256(v) - 27) << 255) | uint256(s));