From 26f8ad5e8953f503caec8a0ad24b5dd5f14d6f2d Mon Sep 17 00:00:00 2001 From: LHerskind <16536249+LHerskind@users.noreply.github.com> Date: Fri, 1 Aug 2025 08:00:25 +0000 Subject: [PATCH] chore: updated fmt settings foundry.toml --- l1-contracts/foundry.toml | 5 +- l1-contracts/script/InternalGov.s.sol | 48 +--- l1-contracts/script/StakingAssetHandler.s.sol | 3 +- l1-contracts/src/core/Rollup.sol | 150 ++-------- l1-contracts/src/core/RollupCore.sol | 77 +---- .../src/core/interfaces/IFeeJuicePortal.sol | 8 +- l1-contracts/src/core/interfaces/IRollup.sol | 35 +-- .../src/core/interfaces/IVerifier.sol | 5 +- .../core/interfaces/messagebridge/IInbox.sol | 15 +- .../core/interfaces/messagebridge/IOutbox.sol | 5 +- .../src/core/libraries/ConstantsGen.sol | 6 +- .../src/core/libraries/DataStructures.sol | 3 +- l1-contracts/src/core/libraries/Errors.sol | 3 +- .../src/core/libraries/StakingQueue.sol | 17 +- l1-contracts/src/core/libraries/TimeLib.sol | 8 +- .../libraries/compressed-data/BlockLog.sol | 21 +- .../compressed-data/StakingQueueConfig.sol | 27 +- .../core/libraries/compressed-data/Tips.sol | 36 +-- .../compressed-data/fees/FeeConfig.sol | 45 +-- .../compressed-data/fees/FeeStructs.sol | 24 +- .../src/core/libraries/crypto/Hash.sol | 7 +- .../src/core/libraries/crypto/MerkleLib.sol | 24 +- .../src/core/libraries/crypto/SampleLib.sol | 11 +- .../src/core/libraries/rollup/BlobLib.sol | 56 ++-- .../core/libraries/rollup/EpochProofLib.sol | 50 ++-- .../core/libraries/rollup/ExtRollupLib.sol | 12 +- .../core/libraries/rollup/ExtRollupLib2.sol | 5 +- .../core/libraries/rollup/ExtRollupLib3.sol | 6 +- .../src/core/libraries/rollup/FeeLib.sol | 79 ++---- .../core/libraries/rollup/InvalidateLib.sol | 24 +- .../src/core/libraries/rollup/ProposeLib.sol | 32 +-- .../src/core/libraries/rollup/RewardLib.sol | 27 +- .../src/core/libraries/rollup/STFLib.sol | 17 +- .../src/core/libraries/rollup/StakingLib.sol | 43 +-- .../rollup/ValidatorSelectionLib.sol | 72 ++--- .../src/core/messagebridge/FeeJuicePortal.sol | 6 +- l1-contracts/src/core/messagebridge/Inbox.sol | 40 +-- .../src/core/messagebridge/Outbox.sol | 16 +- .../src/core/reward-boost/RewardBooster.sol | 20 +- l1-contracts/src/core/slashing/Slasher.sol | 9 +- l1-contracts/src/governance/GSE.sol | 176 ++++-------- l1-contracts/src/governance/GSEPayload.sol | 11 +- l1-contracts/src/governance/Governance.sol | 127 ++------- l1-contracts/src/governance/Registry.sol | 12 +- .../src/governance/RewardDistributor.sol | 5 +- .../src/governance/interfaces/IEmpire.sol | 5 +- .../libraries/AddressSnapshotLib.sol | 30 +- .../libraries/CheckpointedUintLib.sol | 25 +- .../governance/libraries/ConfigurationLib.sol | 68 ++--- .../libraries/DepositDelegationLib.sol | 66 ++--- .../src/governance/libraries/Errors.sol | 8 +- .../src/governance/libraries/ProposalLib.sol | 3 +- .../src/governance/proposer/EmpireBase.sol | 87 ++---- .../proposer/GovernanceProposer.sol | 7 +- l1-contracts/src/mock/MockVerifier.sol | 7 +- l1-contracts/src/mock/StakingAssetHandler.sol | 48 +--- l1-contracts/src/mock/TestERC20.sol | 5 +- .../MockZKPassportVerifier.sol | 14 +- l1-contracts/src/periphery/SlashFactory.sol | 23 +- l1-contracts/src/periphery/SlashPayload.sol | 10 +- .../periphery/interfaces/ISlashFactory.sol | 12 +- .../src/shared/libraries/SignatureLib.sol | 26 +- l1-contracts/test/Inbox.t.sol | 36 +-- l1-contracts/test/MultiProof.t.sol | 53 +--- l1-contracts/test/Outbox.t.sol | 64 ++--- l1-contracts/test/Parity.t.sol | 6 +- l1-contracts/test/Rollup.t.sol | 143 +++------- l1-contracts/test/RollupGetters.t.sol | 22 +- l1-contracts/test/base/Base.sol | 4 +- l1-contracts/test/base/DecoderBase.sol | 22 +- l1-contracts/test/base/RollupBase.sol | 73 ++--- l1-contracts/test/benchmark/Multicall3.sol | 18 +- l1-contracts/test/benchmark/happy.t.sol | 45 +-- .../boosted_rewards/BoostRewardHelper.sol | 4 +- l1-contracts/test/builder/GseBuilder.sol | 18 +- l1-contracts/test/builder/RollupBuilder.sol | 47 +--- l1-contracts/test/compression/FeeConfig.t.sol | 25 +- .../test/compression/FeeStructs.t.sol | 14 +- .../test/compression/PreHeating.t.sol | 47 +--- .../test/compression/StakingQueueConfig.t.sol | 4 +- l1-contracts/test/compression/Tips.t.sol | 59 +--- l1-contracts/test/delegation/base.t.sol | 24 +- l1-contracts/test/delegation/minimal.t.sol | 56 +--- l1-contracts/test/external/ISwapRouter.sol | 20 +- .../fee_portal/depositToAztecPublic.t.sol | 11 +- .../test/fee_portal/distributeFees.t.sol | 4 +- .../test/fees/FeeModelTestPoints.t.sol | 34 +-- l1-contracts/test/fees/FeeRollup.t.sol | 89 ++---- l1-contracts/test/fees/MinimalFeeModel.sol | 28 +- l1-contracts/test/fees/MinimalFeeModel.t.sol | 19 +- .../test/governance/coin-issuer/mint.t.sol | 4 +- .../governance-proposer/constructor.t.sol | 10 +- .../governance-proposer/scenario/15123.t.sol | 30 +- .../governance-proposer/signal.t.sol | 69 ++--- .../submitRoundWinner.t.sol | 50 +--- .../governance-proposer/voteWithsig.t.sol | 92 ++---- .../governance/governance/TestPayloads.sol | 15 +- .../AddressSnapshotsBase.t.sol | 16 +- .../governance/address_snapshots/add.t.sol | 6 +- .../governance/address_snapshots/at.t.sol | 25 +- .../getAddressFromIndexAtTimestamp.t.sol | 51 +--- .../governance/address_snapshots/length.t.sol | 5 +- .../governance/address_snapshots/values.t.sol | 5 +- .../test/governance/governance/base.t.sol | 35 +-- .../governance/checkpointedUintLib/add.t.sol | 9 +- .../governance/checkpointedUintLib/base.t.sol | 4 +- .../checkpointedUintLib/powerAt.t.sol | 8 +- .../checkpointedUintLib/powerNow.t.sol | 4 +- .../governance/checkpointedUintLib/sub.t.sol | 13 +- .../test/governance/governance/deposit.t.sol | 20 +- .../governance/governance/dropProposal.t.sol | 77 ++--- .../test/governance/governance/execute.t.sol | 68 ++--- .../governance/finaliseWithdraw.t.sol | 25 +- .../governance/getProposalState.t.sol | 47 +--- .../governance/initiateWithdraw.t.sol | 10 +- .../governance/limitedDeposit.t.sol | 11 +- .../governance/proposallib/static.t.sol | 38 +-- .../proposallib/voteTabulation.t.sol | 60 +--- .../test/governance/governance/propose.t.sol | 11 +- .../governance/proposeWithLock.t.sol | 7 +- .../governance/scenarios/lockAndPass.t.sol | 7 +- .../governance/scenarios/noVoteAndExit.t.sol | 11 +- .../governance/updateConfiguration.t.sol | 265 ++++-------------- .../governance/updateGovernanceProposer.t.sol | 15 +- .../test/governance/governance/vote.t.sol | 16 +- .../test/governance/gse/gse/addRollup.t.sol | 18 +- l1-contracts/test/governance/gse/gse/base.sol | 4 +- .../test/governance/gse/gse/delegate.t.sol | 22 +- .../test/governance/gse/gse/deposit.t.sol | 52 ++-- .../governance/gse/gse/proposeWithLock.t.sol | 11 +- .../governance/gse/gse/setGovernance.t.sol | 8 +- .../test/governance/gse/gse/static.t.sol | 17 +- .../test/governance/gse/gse/vote.t.sol | 4 +- .../governance/gse/gse/voteWithBonus.t.sol | 13 +- .../test/governance/gse/gse/withdraw.t.sol | 38 +-- .../StakeDelegationLibWrapper.sol | 13 +- .../stakedelegationlib/decreaseBalance.t.sol | 10 +- .../gse/stakedelegationlib/delegate.t.sol | 26 +- .../stakedelegationlib/increaseBalance.t.sol | 10 +- .../gse/stakedelegationlib/usePower.t.sol | 4 +- .../test/governance/registry/addRollup.t.sol | 4 +- .../governance/reward-distributor/claim.t.sol | 4 +- .../test/governance/scenario/AddRollup.t.sol | 18 +- .../scenario/NewGovernanceProposerPayload.sol | 4 +- .../RegisterNewRollupVersionPayload.sol | 6 +- .../UpgradeGovernanceProposerTest.t.sol | 20 +- .../scenario/slashing/Slashing.t.sol | 67 ++--- l1-contracts/test/harnesses/InboxHarness.sol | 3 +- l1-contracts/test/harnesses/TestConstants.sol | 22 +- l1-contracts/test/ignition.t.sol | 25 +- l1-contracts/test/merkle/MerkleLib.t.sol | 5 +- l1-contracts/test/merkle/Naive.t.sol | 9 +- l1-contracts/test/merkle/TestUtil.sol | 13 +- .../test/merkle/UnbalancedMerkle.t.sol | 43 +-- .../test/merkle/helpers/MerkleLibHelper.sol | 13 +- l1-contracts/test/portals/TokenPortal.sol | 32 +-- l1-contracts/test/portals/TokenPortal.t.sol | 49 +--- l1-contracts/test/portals/UniswapPortal.sol | 13 +- l1-contracts/test/portals/UniswapPortal.t.sol | 102 ++----- l1-contracts/test/shouting.t.sol | 16 +- l1-contracts/test/staking/15050.t.sol | 24 +- l1-contracts/test/staking/base.t.sol | 3 +- l1-contracts/test/staking/deposit.t.sol | 9 +- .../test/staking/flushEntryQueue.t.sol | 83 ++---- .../test/staking/initiateWithdraw.t.sol | 14 +- l1-contracts/test/staking/move.t.sol | 32 +-- l1-contracts/test/staking/setSlasher.t.sol | 4 +- l1-contracts/test/staking/slash.t.sol | 23 +- .../staking/updateStakingQueueConfig.t.sol | 12 +- .../staking_asset_handler/addValidator.t.sol | 32 +-- .../test/staking_asset_handler/bind.t.sol | 4 +- .../merkle/merkle_tree_getters.sol | 5 +- .../staking_asset_handler/merkleCheck.t.sol | 3 +- .../reenterExitedValidator.t.sol | 14 +- .../setDepositsPerMint.t.sol | 9 +- .../setMintInterval.t.sol | 8 +- .../staking_asset_handler/setWithdrawer.t.sol | 4 +- .../zkpassport/ZKPassportBase.sol | 11 +- .../test/validator-selection/Sampling.t.sol | 12 +- .../ValidatorSelection.t.sol | 88 ++---- .../ValidatorSelectionBase.sol | 10 +- .../test/validator-selection/setupEpoch.t.sol | 90 ++---- .../validator-selection/setupSampleSeed.t.sol | 9 +- 183 files changed, 1435 insertions(+), 3786 deletions(-) diff --git a/l1-contracts/foundry.toml b/l1-contracts/foundry.toml index db96fb713189..cf8bdd11ae66 100644 --- a/l1-contracts/foundry.toml +++ b/l1-contracts/foundry.toml @@ -55,9 +55,12 @@ fs_permissions = [ no_match_contract="(ScreamAndShoutTest|UniswapPortalTest|MerkleCheck)" [fmt] -line_length = 100 +line_length = 120 tab_width = 2 variable_override_spacing=false +wrap_comments = true +number_underscore = "thousands" +override_spacing = false [rpc_endpoints] mainnet_fork="https://mainnet.infura.io/v3/9928b52099854248b3a096be07a6b23c" diff --git a/l1-contracts/script/InternalGov.s.sol b/l1-contracts/script/InternalGov.s.sol index c3ba84241fd4..73f13976b371 100644 --- a/l1-contracts/script/InternalGov.s.sol +++ b/l1-contracts/script/InternalGov.s.sol @@ -5,17 +5,14 @@ pragma solidity >=0.8.27; import {Test} from "forge-std/Test.sol"; import {Governance} from "@aztec/governance/Governance.sol"; -import { - Proposal, Configuration, ProposalState -} from "@aztec/governance/interfaces/IGovernance.sol"; +import {Proposal, Configuration, ProposalState} from "@aztec/governance/interfaces/IGovernance.sol"; import {TestERC20} from "@aztec/mock/TestERC20.sol"; import {GovernanceProposer} from "@aztec/governance/proposer/GovernanceProposer.sol"; import {IRollup} from "@aztec/core/interfaces/IRollup.sol"; import {IRegistry} from "@aztec/governance/interfaces/IRegistry.sol"; import {IValidatorSelection} from "@aztec/core/interfaces/IValidatorSelection.sol"; import {IPayload} from "@aztec/governance/interfaces/IPayload.sol"; -import {RegisterNewRollupVersionPayload} from - "../test/governance/scenario/RegisterNewRollupVersionPayload.sol"; +import {RegisterNewRollupVersionPayload} from "../test/governance/scenario/RegisterNewRollupVersionPayload.sol"; import {ProposalLib} from "@aztec/governance/libraries/ProposalLib.sol"; import {Ownable} from "@oz/access/Ownable.sol"; import {Fakerollup} from "../test/governance/governance-proposer/mocks/Fakerollup.sol"; @@ -33,12 +30,10 @@ contract GovScript is Test { address internal constant ME = address(0xf8d7d601759CBcfB78044bA7cA9B0c0D6301A54f); Governance public constant governance = Governance(0xEE63E102E35F24c34b9eA09B597ACFb491c94e78); - GovernanceProposer public constant governanceProposer = - GovernanceProposer(0xF4bf5dF1c3B2dd67A0525Fc600E98ca51143a67D); + GovernanceProposer public constant governanceProposer = GovernanceProposer(0xF4bf5dF1c3B2dd67A0525Fc600E98ca51143a67D); TestERC20 public constant stakingAsset = TestERC20(0x5C30c66847866A184ccb5197cBE31Fce7A92eB26); TestERC20 public constant feeAsset = TestERC20(0x487Ff89A8bDAEFeA2Ad10D3e23727ccdA8F845B9); - FeeAssetHandler public constant feeAssetHandler = - FeeAssetHandler(0x80d848Dc9F52DF56789e2d62Ce66F19555FF1019); + FeeAssetHandler public constant feeAssetHandler = FeeAssetHandler(0x80d848Dc9F52DF56789e2d62Ce66F19555FF1019); StakingAssetHandler public constant stakingAssetHandler = StakingAssetHandler(0xF739D03e98e23A7B65940848aBA8921fF3bAc4b2); IRegistry public constant registry = IRegistry(0x4d2cC1d5fb6BE65240e0bFC8154243e69c0Fb19E); @@ -81,12 +76,8 @@ contract GovScript is Test { emit log_named_address("\tOwner", Ownable(address(rollup)).owner()); emit log_named_uint("\tPending block number", rollup.getPendingBlockNumber()); emit log_named_uint("\tProven block number ", rollup.getProvenBlockNumber()); - emit log_named_uint( - "\tNumber of attestors ", IStaking(address(rollup)).getActiveAttesterCount() - ); - emit log_named_decimal_uint( - "\tMinimum stake", IStaking(address(rollup)).getActivationThreshold(), 18 - ); + emit log_named_uint("\tNumber of attestors ", IStaking(address(rollup)).getActiveAttesterCount()); + emit log_named_decimal_uint("\tMinimum stake", IStaking(address(rollup)).getActivationThreshold(), 18); emit log_named_address("# Governance", address(governance)); Configuration memory config = governance.getConfiguration(); @@ -126,8 +117,7 @@ contract GovScript is Test { for (uint256 i = lowerLimit; i <= currentRound; i++) { RoundAccounting memory r = governanceProposer.getRoundData(address(rollup), i); - uint256 signalCount = - governanceProposer.signalCount(address(rollup), i, r.payloadWithMostSignals); + uint256 signalCount = governanceProposer.signalCount(address(rollup), i, r.payloadWithMostSignals); emit log_named_uint("Proposal at round", i); emit log_named_uint("\tsignalCount", signalCount); @@ -160,9 +150,7 @@ contract GovScript is Test { emit log_named_decimal_uint("yeaCount ", proposal.summedBallot.yea, 18); emit log_named_decimal_uint("nayCount ", proposal.summedBallot.nay, 18); - Timestamp ts = Timestamp.wrap(block.timestamp) < pendingThrough - ? Timestamp.wrap(block.timestamp) - : pendingThrough; + Timestamp ts = Timestamp.wrap(block.timestamp) < pendingThrough ? Timestamp.wrap(block.timestamp) : pendingThrough; emit log_named_decimal_uint("power ", governance.powerAt(ME, ts), 18); } @@ -182,24 +170,19 @@ contract GovScript is Test { /* -------------------------------------------------------------------------- */ function fundRewardDistributor() public { - RewardDistributor rewardDistributor = - RewardDistributor(address(registry.getRewardDistributor())); + RewardDistributor rewardDistributor = RewardDistributor(address(registry.getRewardDistributor())); TestERC20 asset = TestERC20(address(rewardDistributor.ASSET())); IRollup canonicalRollup = IRollup(address(registry.getCanonicalRollup())); uint256 blockReward = canonicalRollup.getBlockReward(); - emit log_named_decimal_uint( - "Reward distributor balance", asset.balanceOf(address(rewardDistributor)), 18 - ); + emit log_named_decimal_uint("Reward distributor balance", asset.balanceOf(address(rewardDistributor)), 18); vm.startBroadcast(ME); - asset.mint(address(rewardDistributor), 200000 * blockReward); + asset.mint(address(rewardDistributor), 200_000 * blockReward); vm.stopBroadcast(); - emit log_named_decimal_uint( - "Reward distributor balance", asset.balanceOf(address(rewardDistributor)), 18 - ); + emit log_named_decimal_uint("Reward distributor balance", asset.balanceOf(address(rewardDistributor)), 18); } // This should only be called if we figure that we are minting too little fee asset @@ -266,9 +249,7 @@ contract GovScript is Test { Ownable(address(registry)).transferOwnership(address(governance)); vm.stopBroadcast(); assertEq(Ownable(address(registry)).owner(), address(governance)); - emit log_named_address( - "Passed ownership of registry to governance", Ownable(address(registry)).owner() - ); + emit log_named_address("Passed ownership of registry to governance", Ownable(address(registry)).owner()); } // Deposit enough funds to be able to pass a vote @@ -307,8 +288,7 @@ contract GovScript is Test { emit log_named_address("deploying payload to add instance", _instance); vm.startBroadcast(ME); - RegisterNewRollupVersionPayload payload = - new RegisterNewRollupVersionPayload(registry, IInstance(_instance)); + RegisterNewRollupVersionPayload payload = new RegisterNewRollupVersionPayload(registry, IInstance(_instance)); vm.stopBroadcast(); lookAtPayload(address(payload)); diff --git a/l1-contracts/script/StakingAssetHandler.s.sol b/l1-contracts/script/StakingAssetHandler.s.sol index ecf74d22e4fc..c016f891ddf7 100644 --- a/l1-contracts/script/StakingAssetHandler.s.sol +++ b/l1-contracts/script/StakingAssetHandler.s.sol @@ -11,8 +11,7 @@ import {IRollup} from "@aztec/core/interfaces/IRollup.sol"; import {IRegistry} from "@aztec/governance/interfaces/IRegistry.sol"; import {IValidatorSelection} from "@aztec/core/interfaces/IValidatorSelection.sol"; import {IPayload} from "@aztec/governance/interfaces/IPayload.sol"; -import {RegisterNewRollupVersionPayload} from - "../test/governance/scenario/RegisterNewRollupVersionPayload.sol"; +import {RegisterNewRollupVersionPayload} from "../test/governance/scenario/RegisterNewRollupVersionPayload.sol"; import {ProposalLib} from "@aztec/governance/libraries/ProposalLib.sol"; import {Ownable} from "@oz/access/Ownable.sol"; import {Fakerollup} from "../test/governance/governance-proposer/mocks/Fakerollup.sol"; diff --git a/l1-contracts/src/core/Rollup.sol b/l1-contracts/src/core/Rollup.sol index 96a87d150685..b592980302aa 100644 --- a/l1-contracts/src/core/Rollup.sol +++ b/l1-contracts/src/core/Rollup.sol @@ -14,24 +14,16 @@ import { FeeHeader, RollupConfigInput } from "@aztec/core/interfaces/IRollup.sol"; -import { - IStaking, AttesterConfig, Exit, AttesterView, Status -} from "@aztec/core/interfaces/IStaking.sol"; +import {IStaking, AttesterConfig, Exit, AttesterView, Status} from "@aztec/core/interfaces/IStaking.sol"; import {IValidatorSelection, IEmperor} from "@aztec/core/interfaces/IValidatorSelection.sol"; import {IVerifier} from "@aztec/core/interfaces/IVerifier.sol"; import {TempBlockLog, BlockLog} from "@aztec/core/libraries/compressed-data/BlockLog.sol"; -import { - FeeLib, FeeHeaderLib, FeeAssetValue, PriceLib -} from "@aztec/core/libraries/rollup/FeeLib.sol"; +import {FeeLib, FeeHeaderLib, FeeAssetValue, PriceLib} from "@aztec/core/libraries/rollup/FeeLib.sol"; import {ProposedHeader} from "@aztec/core/libraries/rollup/ProposedHeaderLib.sol"; import {StakingLib} from "@aztec/core/libraries/rollup/StakingLib.sol"; import {GSE} from "@aztec/governance/GSE.sol"; import {IRewardDistributor} from "@aztec/governance/interfaces/IRewardDistributor.sol"; -import { - CompressedSlot, - CompressedTimestamp, - CompressedTimeMath -} from "@aztec/shared/libraries/CompressedTimeMath.sol"; +import {CompressedSlot, CompressedTimestamp, CompressedTimeMath} from "@aztec/shared/libraries/CompressedTimeMath.sol"; import {ChainTipsLib, CompressedChainTips} from "./libraries/compressed-data/Tips.sol"; import {ProposeLib, ValidateHeaderArgs} from "./libraries/rollup/ProposeLib.sol"; import {RewardLib, RewardConfig} from "./libraries/rollup/RewardLib.sol"; @@ -79,17 +71,7 @@ contract Rollup is IStaking, IValidatorSelection, IRollup, RollupCore { address _governance, GenesisState memory _genesisState, RollupConfigInput memory _config - ) - RollupCore( - _feeAsset, - _stakingAsset, - _gse, - _epochProofVerifier, - _governance, - _genesisState, - _config - ) - {} + ) RollupCore(_feeAsset, _stakingAsset, _gse, _epochProofVerifier, _governance, _genesisState, _config) {} /** * @notice Validate a header for submission @@ -128,11 +110,7 @@ contract Rollup is IStaking, IValidatorSelection, IRollup, RollupCore { * @notice Get the validator set for the current epoch * @return The validator set for the current epoch */ - function getCurrentEpochCommittee() - external - override(IValidatorSelection) - returns (address[] memory) - { + function getCurrentEpochCommittee() external override(IValidatorSelection) returns (address[] memory) { return getEpochCommittee(getCurrentEpoch()); } @@ -143,11 +121,7 @@ contract Rollup is IStaking, IValidatorSelection, IRollup, RollupCore { * * @return The committee for the given timestamp */ - function getCommitteeAt(Timestamp _ts) - external - override(IValidatorSelection) - returns (address[] memory) - { + function getCommitteeAt(Timestamp _ts) external override(IValidatorSelection) returns (address[] memory) { return getEpochCommittee(getEpochAt(_ts)); } @@ -159,11 +133,7 @@ contract Rollup is IStaking, IValidatorSelection, IRollup, RollupCore { * @return The committee commitment for the given timestamp * @return The committee size for the given timestamp */ - function getCommitteeCommitmentAt(Timestamp _ts) - external - override(IValidatorSelection) - returns (bytes32, uint256) - { + function getCommitteeCommitmentAt(Timestamp _ts) external override(IValidatorSelection) returns (bytes32, uint256) { return ExtRollupLib2.getCommitteeCommitmentAt(getEpochAt(_ts)); } @@ -334,10 +304,7 @@ contract Rollup is IStaking, IValidatorSelection, IRollup, RollupCore { function getBlock(uint256 _blockNumber) external view override(IRollup) returns (BlockLog memory) { RollupStore storage rollupStore = STFLib.getStorage(); uint256 pendingBlockNumber = rollupStore.tips.getPendingBlockNumber(); - require( - _blockNumber <= pendingBlockNumber, - Errors.Rollup__InvalidBlockNumber(pendingBlockNumber, _blockNumber) - ); + require(_blockNumber <= pendingBlockNumber, Errors.Rollup__InvalidBlockNumber(pendingBlockNumber, _blockNumber)); // If the block is outside of the temp stored, will return default values (0) // for all that would have been in temp. @@ -357,21 +324,11 @@ contract Rollup is IStaking, IValidatorSelection, IRollup, RollupCore { }); } - function getFeeHeader(uint256 _blockNumber) - external - view - override(IRollup) - returns (FeeHeader memory) - { + function getFeeHeader(uint256 _blockNumber) external view override(IRollup) returns (FeeHeader memory) { return FeeHeaderLib.decompress(STFLib.getFeeHeader(_blockNumber)); } - function getBlobCommitmentsHash(uint256 _blockNumber) - external - view - override(IRollup) - returns (bytes32) - { + function getBlobCommitmentsHash(uint256 _blockNumber) external view override(IRollup) returns (bytes32) { return STFLib.getBlobCommitmentsHash(_blockNumber); } @@ -380,12 +337,7 @@ contract Rollup is IStaking, IValidatorSelection, IRollup, RollupCore { return STFLib.getBlobCommitmentsHash(rollupStore.tips.getPendingBlockNumber()); } - function getConfig(address _attester) - external - view - override(IStaking) - returns (AttesterConfig memory) - { + function getConfig(address _attester) external view override(IStaking) returns (AttesterConfig memory) { return StakingLib.getConfig(_attester); } @@ -397,12 +349,7 @@ contract Rollup is IStaking, IValidatorSelection, IRollup, RollupCore { return StakingLib.getStatus(_attester); } - function getAttesterView(address _attester) - external - view - override(IStaking) - returns (AttesterView memory) - { + function getAttesterView(address _attester) external view override(IStaking) returns (AttesterView memory) { return StakingLib.getAttesterView(_attester); } @@ -417,12 +364,7 @@ contract Rollup is IStaking, IValidatorSelection, IRollup, RollupCore { * * @return The sample seed for the given timestamp */ - function getSampleSeedAt(Timestamp _ts) - external - view - override(IValidatorSelection) - returns (uint256) - { + function getSampleSeedAt(Timestamp _ts) external view override(IValidatorSelection) returns (uint256) { return ExtRollupLib2.getSampleSeedAt(getEpochAt(_ts)); } @@ -462,12 +404,7 @@ contract Rollup is IStaking, IValidatorSelection, IRollup, RollupCore { * * @return The timestamp for the given slot */ - function getTimestampForSlot(Slot _slotNumber) - external - view - override(IValidatorSelection) - returns (Timestamp) - { + function getTimestampForSlot(Slot _slotNumber) external view override(IValidatorSelection) returns (Timestamp) { return _slotNumber.toTimestamp(); } @@ -489,30 +426,15 @@ contract Rollup is IStaking, IValidatorSelection, IRollup, RollupCore { * * @return The computed epoch */ - function getEpochAtSlot(Slot _slotNumber) - external - view - override(IValidatorSelection) - returns (Epoch) - { + function getEpochAtSlot(Slot _slotNumber) external view override(IValidatorSelection) returns (Epoch) { return _slotNumber.epochFromSlot(); } - function getSequencerRewards(address _sequencer) - external - view - override(IRollup) - returns (uint256) - { + function getSequencerRewards(address _sequencer) external view override(IRollup) returns (uint256) { return RewardLib.getSequencerRewards(_sequencer); } - function getCollectiveProverRewardsForEpoch(Epoch _epoch) - external - view - override(IRollup) - returns (uint256) - { + function getCollectiveProverRewardsForEpoch(Epoch _epoch) external view override(IRollup) returns (uint256) { return RewardLib.getCollectiveProverRewardsForEpoch(_epoch); } @@ -544,12 +466,7 @@ contract Rollup is IStaking, IValidatorSelection, IRollup, RollupCore { return RewardLib.getHasSubmitted(_epoch, _length, _prover); } - function getHasClaimed(address _prover, Epoch _epoch) - external - view - override(IRollup) - returns (bool) - { + function getHasClaimed(address _prover, Epoch _epoch) external view override(IRollup) returns (bool) { return RewardLib.getHasClaimed(_prover, _epoch); } @@ -557,12 +474,7 @@ contract Rollup is IStaking, IValidatorSelection, IRollup, RollupCore { return FeeLib.getProvingCostPerMana(); } - function getProvingCostPerManaInFeeAsset() - external - view - override(IRollup) - returns (FeeAssetValue) - { + function getProvingCostPerManaInFeeAsset() external view override(IRollup) returns (FeeAssetValue) { return FeeLib.getProvingCostPerMana().toFeeAsset(getFeeAssetPerEth()); } @@ -590,12 +502,7 @@ contract Rollup is IStaking, IValidatorSelection, IRollup, RollupCore { return RewardLib.getStorage().config.rewardDistributor; } - function getL1FeesAt(Timestamp _timestamp) - external - view - override(IRollup) - returns (L1FeeData memory) - { + function getL1FeesAt(Timestamp _timestamp) external view override(IRollup) returns (L1FeeData memory) { return FeeLib.getL1FeesAt(_timestamp); } @@ -624,11 +531,7 @@ contract Rollup is IStaking, IValidatorSelection, IRollup, RollupCore { * * @return The validator set for the given epoch */ - function getEpochCommittee(Epoch _epoch) - public - override(IValidatorSelection) - returns (address[] memory) - { + function getEpochCommittee(Epoch _epoch) public override(IValidatorSelection) returns (address[] memory) { return ExtRollupLib2.getCommitteeAt(_epoch); } @@ -675,12 +578,7 @@ contract Rollup is IStaking, IValidatorSelection, IRollup, RollupCore { * * @return The mana base fee */ - function getManaBaseFeeAt(Timestamp _timestamp, bool _inFeeAsset) - public - view - override(IRollup) - returns (uint256) - { + function getManaBaseFeeAt(Timestamp _timestamp, bool _inFeeAsset) public view override(IRollup) returns (uint256) { return FeeLib.summedBaseFee(getManaBaseFeeComponentsAt(_timestamp, _inFeeAsset)); } @@ -715,9 +613,7 @@ contract Rollup is IStaking, IValidatorSelection, IRollup, RollupCore { */ function archiveAt(uint256 _blockNumber) public view override(IRollup) returns (bytes32) { RollupStore storage rollupStore = STFLib.getStorage(); - return _blockNumber <= rollupStore.tips.getPendingBlockNumber() - ? rollupStore.archives[_blockNumber] - : bytes32(0); + return _blockNumber <= rollupStore.tips.getPendingBlockNumber() ? rollupStore.archives[_blockNumber] : bytes32(0); } /** diff --git a/l1-contracts/src/core/RollupCore.sol b/l1-contracts/src/core/RollupCore.sol index fb706de4cadd..e585785b901b 100644 --- a/l1-contracts/src/core/RollupCore.sol +++ b/l1-contracts/src/core/RollupCore.sol @@ -5,10 +5,7 @@ pragma solidity >=0.8.27; import {IFeeJuicePortal} from "@aztec/core/interfaces/IFeeJuicePortal.sol"; import { - IRollupCore, - RollupStore, - SubmitEpochRootProofArgs, - RollupConfigInput + IRollupCore, RollupStore, SubmitEpochRootProofArgs, RollupConfigInput } from "@aztec/core/interfaces/IRollup.sol"; import {IVerifier} from "@aztec/core/interfaces/IVerifier.sol"; import {IStakingCore} from "@aztec/core/interfaces/IStaking.sol"; @@ -35,10 +32,7 @@ import {IERC20} from "@oz/token/ERC20/IERC20.sol"; import {EIP712} from "@oz/utils/cryptography/EIP712.sol"; import {RewardLib, RewardConfig} from "@aztec/core/libraries/rollup/RewardLib.sol"; import {StakingQueueConfig} from "@aztec/core/libraries/compressed-data/StakingQueueConfig.sol"; -import { - FeeConfigLib, - CompressedFeeConfig -} from "@aztec/core/libraries/compressed-data/fees/FeeConfig.sol"; +import {FeeConfigLib, CompressedFeeConfig} from "@aztec/core/libraries/compressed-data/fees/FeeConfig.sol"; /** * @title Rollup @@ -47,13 +41,7 @@ import { * not giving a damn about gas costs. * @dev WARNING: This contract is VERY close to the size limit */ -contract RollupCore is - EIP712("Aztec Rollup", "1"), - Ownable, - IStakingCore, - IValidatorSelectionCore, - IRollupCore -{ +contract RollupCore is EIP712("Aztec Rollup", "1"), Ownable, IStakingCore, IValidatorSelectionCore, IRollupCore { using TimeLib for Timestamp; using TimeLib for Slot; using TimeLib for Epoch; @@ -80,10 +68,7 @@ contract RollupCore is RollupConfigInput memory _config ) Ownable(_governance) { TimeLib.initialize( - block.timestamp, - _config.aztecSlotDuration, - _config.aztecEpochDuration, - _config.aztecProofSubmissionEpochs + block.timestamp, _config.aztecSlotDuration, _config.aztecEpochDuration, _config.aztecProofSubmissionEpochs ); Timestamp exitDelay = Timestamp.wrap(_config.exitDelaySeconds); @@ -95,9 +80,7 @@ contract RollupCore is _config.slashingVetoer ); - StakingLib.initialize( - _stakingAsset, _gse, exitDelay, address(slasher), _config.stakingQueueConfig - ); + StakingLib.initialize(_stakingAsset, _gse, exitDelay, address(slasher), _config.stakingQueueConfig); ExtRollupLib2.initializeValidatorSelection(_config.targetCommitteeSize); // If no booster specifically provided deploy one. @@ -117,16 +100,11 @@ contract RollupCore is // @todo handle case where L1 forks and chainid is different // @note Truncated to 32 bits to make simpler to deal with all the node changes at a separate time. - uint32 version = uint32( - uint256( - keccak256(abi.encode(bytes("aztec_rollup"), block.chainid, address(this), _genesisState)) - ) - ); + uint32 version = + uint32(uint256(keccak256(abi.encode(bytes("aztec_rollup"), block.chainid, address(this), _genesisState)))); rollupStore.config.version = version; - IInbox inbox = IInbox( - address(new Inbox(address(this), _feeAsset, version, Constants.L1_TO_L2_MSG_SUBTREE_HEIGHT)) - ); + IInbox inbox = IInbox(address(new Inbox(address(this), _feeAsset, version, Constants.L1_TO_L2_MSG_SUBTREE_HEIGHT))); rollupStore.config.inbox = inbox; @@ -148,10 +126,7 @@ contract RollupCore is function updateManaTarget(uint256 _manaTarget) external override(IRollupCore) onlyOwner { uint256 currentManaTarget = FeeLib.getStorage().config.getManaTarget(); - require( - _manaTarget >= currentManaTarget, - Errors.Rollup__InvalidManaTarget(currentManaTarget, _manaTarget) - ); + require(_manaTarget >= currentManaTarget, Errors.Rollup__InvalidManaTarget(currentManaTarget, _manaTarget)); FeeLib.updateManaTarget(_manaTarget); emit IRollupCore.ManaTargetUpdated(_manaTarget); } @@ -165,27 +140,15 @@ contract RollupCore is ExtRollupLib2.setSlasher(_slasher); } - function setProvingCostPerMana(EthValue _provingCostPerMana) - external - override(IRollupCore) - onlyOwner - { + function setProvingCostPerMana(EthValue _provingCostPerMana) external override(IRollupCore) onlyOwner { FeeLib.updateProvingCostPerMana(_provingCostPerMana); } - function updateStakingQueueConfig(StakingQueueConfig memory _config) - external - override(IStakingCore) - onlyOwner - { + function updateStakingQueueConfig(StakingQueueConfig memory _config) external override(IStakingCore) onlyOwner { ExtRollupLib2.updateStakingQueueConfig(_config); } - function claimSequencerRewards(address _recipient) - external - override(IRollupCore) - returns (uint256) - { + function claimSequencerRewards(address _recipient) external override(IRollupCore) returns (uint256) { require(isRewardsClaimable, Errors.Rollup__RewardsNotClaimable()); return RewardLib.claimSequencerRewards(_recipient); } @@ -203,10 +166,7 @@ contract RollupCore is ExtRollupLib2.vote(_proposalId); } - function deposit(address _attester, address _withdrawer, bool _moveWithLatestRollup) - external - override(IStakingCore) - { + function deposit(address _attester, address _withdrawer, bool _moveWithLatestRollup) external override(IStakingCore) { ExtRollupLib2.deposit(_attester, _withdrawer, _moveWithLatestRollup); } @@ -215,11 +175,7 @@ contract RollupCore is ExtRollupLib2.flushEntryQueue(maxAddableValidators); } - function initiateWithdraw(address _attester, address _recipient) - external - override(IStakingCore) - returns (bool) - { + function initiateWithdraw(address _attester, address _recipient) external override(IStakingCore) returns (bool) { return ExtRollupLib2.initiateWithdraw(_attester, _recipient); } @@ -235,10 +191,7 @@ contract RollupCore is ExtRollupLib.prune(); } - function submitEpochRootProof(SubmitEpochRootProofArgs calldata _args) - external - override(IRollupCore) - { + function submitEpochRootProof(SubmitEpochRootProofArgs calldata _args) external override(IRollupCore) { ExtRollupLib.submitEpochRootProof(_args); } diff --git a/l1-contracts/src/core/interfaces/IFeeJuicePortal.sol b/l1-contracts/src/core/interfaces/IFeeJuicePortal.sol index bb2e78555aa5..4f5f24b0d489 100644 --- a/l1-contracts/src/core/interfaces/IFeeJuicePortal.sol +++ b/l1-contracts/src/core/interfaces/IFeeJuicePortal.sol @@ -7,15 +7,11 @@ import {IERC20} from "@oz/token/ERC20/IERC20.sol"; import {IInbox} from "./messagebridge/IInbox.sol"; interface IFeeJuicePortal { - event DepositToAztecPublic( - bytes32 indexed to, uint256 amount, bytes32 secretHash, bytes32 key, uint256 index - ); + event DepositToAztecPublic(bytes32 indexed to, uint256 amount, bytes32 secretHash, bytes32 key, uint256 index); event FeesDistributed(address indexed to, uint256 amount); function distributeFees(address _to, uint256 _amount) external; - function depositToAztecPublic(bytes32 _to, uint256 _amount, bytes32 _secretHash) - external - returns (bytes32, uint256); + function depositToAztecPublic(bytes32 _to, uint256 _amount, bytes32 _secretHash) external returns (bytes32, uint256); // solhint-disable-next-line func-name-mixedcase function UNDERLYING() external view returns (IERC20); diff --git a/l1-contracts/src/core/interfaces/IRollup.sol b/l1-contracts/src/core/interfaces/IRollup.sol index 8ed0cbb9b755..ba7280274066 100644 --- a/l1-contracts/src/core/interfaces/IRollup.sol +++ b/l1-contracts/src/core/interfaces/IRollup.sol @@ -6,14 +6,10 @@ import {IFeeJuicePortal} from "@aztec/core/interfaces/IFeeJuicePortal.sol"; import {IVerifier} from "@aztec/core/interfaces/IVerifier.sol"; import {IInbox} from "@aztec/core/interfaces/messagebridge/IInbox.sol"; import {IOutbox} from "@aztec/core/interfaces/messagebridge/IOutbox.sol"; -import { - BlockLog, CompressedTempBlockLog -} from "@aztec/core/libraries/compressed-data/BlockLog.sol"; +import {BlockLog, CompressedTempBlockLog} from "@aztec/core/libraries/compressed-data/BlockLog.sol"; import {StakingQueueConfig} from "@aztec/core/libraries/compressed-data/StakingQueueConfig.sol"; import {CompressedChainTips, ChainTips} from "@aztec/core/libraries/compressed-data/Tips.sol"; -import { - FeeHeader, L1FeeData, ManaBaseFeeComponents -} from "@aztec/core/libraries/rollup/FeeLib.sol"; +import {FeeHeader, L1FeeData, ManaBaseFeeComponents} from "@aztec/core/libraries/rollup/FeeLib.sol"; import {FeeAssetPerEthE9, EthValue, FeeAssetValue} from "@aztec/core/libraries/rollup/FeeLib.sol"; import {ProposedHeader} from "@aztec/core/libraries/rollup/ProposedHeaderLib.sol"; import {ProposeArgs} from "@aztec/core/libraries/rollup/ProposeLib.sol"; @@ -93,9 +89,7 @@ struct RollupStore { } interface IRollupCore { - event L2BlockProposed( - uint256 indexed blockNumber, bytes32 indexed archive, bytes32[] versionedBlobHashes - ); + event L2BlockProposed(uint256 indexed blockNumber, bytes32 indexed archive, bytes32[] versionedBlobHashes); event L2ProofVerified(uint256 indexed blockNumber, address indexed proverId); event BlockInvalidated(uint256 indexed blockNumber); event RewardConfigUpdated(RewardConfig rewardConfig); @@ -107,9 +101,7 @@ interface IRollupCore { function setRewardsClaimable(bool _isRewardsClaimable) external; function claimSequencerRewards(address _recipient) external returns (uint256); - function claimProverRewards(address _recipient, Epoch[] memory _epochs) - external - returns (uint256); + function claimProverRewards(address _recipient, Epoch[] memory _epochs) external returns (uint256); function prune() external; function updateL1GasFeeOracle() external; @@ -155,9 +147,7 @@ interface IRollup is IRollupCore, IHaveVersion { BlockHeaderValidationFlags memory _flags ) external; - function canProposeAtTime(Timestamp _ts, bytes32 _archive, address _who) - external - returns (Slot, uint256); + function canProposeAtTime(Timestamp _ts, bytes32 _archive, address _who) external returns (Slot, uint256); function getTips() external view returns (ChainTips memory); @@ -181,10 +171,7 @@ interface IRollup is IRollupCore, IHaveVersion { bytes calldata _blobPublicInputs ) external view returns (bytes32[] memory); - function validateBlobs(bytes calldata _blobsInputs) - external - view - returns (bytes32[] memory, bytes32, bytes[] memory); + function validateBlobs(bytes calldata _blobsInputs) external view returns (bytes32[] memory, bytes32, bytes[] memory); function getManaBaseFeeComponentsAt(Timestamp _timestamp, bool _inFeeAsset) external @@ -209,14 +196,8 @@ interface IRollup is IRollupCore, IHaveVersion { function getSharesFor(address _prover) external view returns (uint256); function getSequencerRewards(address _sequencer) external view returns (uint256); function getCollectiveProverRewardsForEpoch(Epoch _epoch) external view returns (uint256); - function getSpecificProverRewardsForEpoch(Epoch _epoch, address _prover) - external - view - returns (uint256); - function getHasSubmitted(Epoch _epoch, uint256 _length, address _prover) - external - view - returns (bool); + function getSpecificProverRewardsForEpoch(Epoch _epoch, address _prover) external view returns (uint256); + function getHasSubmitted(Epoch _epoch, uint256 _length, address _prover) external view returns (bool); function getHasClaimed(address _prover, Epoch _epoch) external view returns (bool); function getProofSubmissionEpochs() external view returns (uint256); diff --git a/l1-contracts/src/core/interfaces/IVerifier.sol b/l1-contracts/src/core/interfaces/IVerifier.sol index 45bf6acdcbc8..3e78ac84b905 100644 --- a/l1-contracts/src/core/interfaces/IVerifier.sol +++ b/l1-contracts/src/core/interfaces/IVerifier.sol @@ -3,8 +3,5 @@ pragma solidity >=0.8.27; interface IVerifier { - function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) - external - view - returns (bool); + function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool); } diff --git a/l1-contracts/src/core/interfaces/messagebridge/IInbox.sol b/l1-contracts/src/core/interfaces/messagebridge/IInbox.sol index 38a96c8bbdfc..db2f6982cab6 100644 --- a/l1-contracts/src/core/interfaces/messagebridge/IInbox.sol +++ b/l1-contracts/src/core/interfaces/messagebridge/IInbox.sol @@ -28,9 +28,7 @@ interface IInbox { * @param hash - The hash of the message * @param rollingHash - The rolling hash of all messages inserted into the inbox */ - event MessageSent( - uint256 indexed l2BlockNumber, uint256 index, bytes32 indexed hash, bytes16 rollingHash - ); + event MessageSent(uint256 indexed l2BlockNumber, uint256 index, bytes32 indexed hash, bytes16 rollingHash); // docs:start:send_l1_to_l2_message /** @@ -38,14 +36,13 @@ interface IInbox { * @dev Emits `MessageSent` with data for easy access by the sequencer * @param _recipient - The recipient of the message * @param _content - The content of the message (application specific) - * @param _secretHash - The secret hash of the message (make it possible to hide when a specific message is consumed on L2) + * @param _secretHash - The secret hash of the message (make it possible to hide when a specific message is consumed + * on L2) * @return The key of the message in the set and its leaf index in the tree */ - function sendL2Message( - DataStructures.L2Actor memory _recipient, - bytes32 _content, - bytes32 _secretHash - ) external returns (bytes32, uint256); + function sendL2Message(DataStructures.L2Actor memory _recipient, bytes32 _content, bytes32 _secretHash) + external + returns (bytes32, uint256); // docs:end:send_l1_to_l2_message // docs:start:consume diff --git a/l1-contracts/src/core/interfaces/messagebridge/IOutbox.sol b/l1-contracts/src/core/interfaces/messagebridge/IOutbox.sol index b169d0bebe36..328e9fb4a3cc 100644 --- a/l1-contracts/src/core/interfaces/messagebridge/IOutbox.sol +++ b/l1-contracts/src/core/interfaces/messagebridge/IOutbox.sol @@ -55,10 +55,7 @@ interface IOutbox { * @param _l2BlockNumber - The block number specifying the block that contains the message we want to check * @param _leafId - The unique id of the message leaf */ - function hasMessageBeenConsumedAtBlock(uint256 _l2BlockNumber, uint256 _leafId) - external - view - returns (bool); + function hasMessageBeenConsumedAtBlock(uint256 _l2BlockNumber, uint256 _leafId) external view returns (bool); // docs:end:outbox_has_message_been_consumed_at_block_and_index /** diff --git a/l1-contracts/src/core/libraries/ConstantsGen.sol b/l1-contracts/src/core/libraries/ConstantsGen.sol index 9f4409d7cf5c..43f2d080a3e4 100644 --- a/l1-contracts/src/core/libraries/ConstantsGen.sol +++ b/l1-contracts/src/core/libraries/ConstantsGen.sol @@ -11,17 +11,17 @@ pragma solidity >=0.8.27; library Constants { // Prime field modulus uint256 internal constant P = - 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; uint256 internal constant MAX_FIELD_VALUE = - 21888242871839275222246405745257275088548364400416034343698204186575808495616; + 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_616; uint256 internal constant L1_TO_L2_MSG_SUBTREE_HEIGHT = 4; uint256 internal constant MAX_L2_TO_L1_MSGS_PER_TX = 8; uint256 internal constant INITIAL_L2_BLOCK_NUM = 1; uint256 internal constant BLOBS_PER_BLOCK = 3; uint256 internal constant AZTEC_MAX_EPOCH_DURATION = 48; uint256 internal constant GENESIS_ARCHIVE_ROOT = - 14298165331316638916453567345577793920283466066305521584041971978819102601406; + 14_298_165_331_316_638_916_453_567_345_577_793_920_283_466_066_305_521_584_041_971_978_819_102_601_406; uint256 internal constant FEE_JUICE_ADDRESS = 5; uint256 internal constant BLS12_POINT_COMPRESSED_BYTES = 48; uint256 internal constant PROPOSED_BLOCK_HEADER_LENGTH_BYTES = 284; diff --git a/l1-contracts/src/core/libraries/DataStructures.sol b/l1-contracts/src/core/libraries/DataStructures.sol index 86f2f0da59f9..a9c5ac9f38eb 100644 --- a/l1-contracts/src/core/libraries/DataStructures.sol +++ b/l1-contracts/src/core/libraries/DataStructures.sol @@ -38,7 +38,8 @@ library DataStructures { * @param sender - The sender of the message * @param recipient - The recipient of the message * @param content - The content of the message (application specific) padded to bytes32 or hashed if larger. - * @param secretHash - The secret hash of the message (make it possible to hide when a specific message is consumed on L2). + * @param secretHash - The secret hash of the message (make it possible to hide when a specific message is consumed on + * L2). * @param index - Global leaf index on the L1 to L2 messages tree. */ struct L1ToL2Msg { diff --git a/l1-contracts/src/core/libraries/Errors.sol b/l1-contracts/src/core/libraries/Errors.sol index 7697234c0ecf..22af78f54c8b 100644 --- a/l1-contracts/src/core/libraries/Errors.sol +++ b/l1-contracts/src/core/libraries/Errors.sol @@ -11,7 +11,8 @@ import {Timestamp, Slot, Epoch} from "@aztec/core/libraries/TimeLib.sol"; * Errors are prefixed with the contract name to make it easy to identify where the error originated * when there are multiple contracts that could have thrown the error. * - * Sigs are provided for easy reference, but don't trust; verify! run `forge inspect src/core/libraries/Errors.sol:Errors errors` + * Sigs are provided for easy reference, but don't trust; verify! run `forge inspect + * src/core/libraries/Errors.sol:Errors errors` */ library Errors { // DEVNET related diff --git a/l1-contracts/src/core/libraries/StakingQueue.sol b/l1-contracts/src/core/libraries/StakingQueue.sol index 1006f42b1304..b11fa1cb37ae 100644 --- a/l1-contracts/src/core/libraries/StakingQueue.sol +++ b/l1-contracts/src/core/libraries/StakingQueue.sol @@ -25,19 +25,14 @@ library StakingQueueLib { self.last = 1; } - function enqueue( - StakingQueue storage self, - address _attester, - address _withdrawer, - bool _moveWithLatestRollup - ) internal returns (uint256) { + function enqueue(StakingQueue storage self, address _attester, address _withdrawer, bool _moveWithLatestRollup) + internal + returns (uint256) + { uint128 queueLocation = self.last; - self.validators[queueLocation] = DepositArgs({ - attester: _attester, - withdrawer: _withdrawer, - moveWithLatestRollup: _moveWithLatestRollup - }); + self.validators[queueLocation] = + DepositArgs({attester: _attester, withdrawer: _withdrawer, moveWithLatestRollup: _moveWithLatestRollup}); self.last = queueLocation + 1; return queueLocation; diff --git a/l1-contracts/src/core/libraries/TimeLib.sol b/l1-contracts/src/core/libraries/TimeLib.sol index e9392dda4009..3e4c398e7a19 100644 --- a/l1-contracts/src/core/libraries/TimeLib.sol +++ b/l1-contracts/src/core/libraries/TimeLib.sol @@ -12,7 +12,9 @@ struct TimeStorage { uint32 slotDuration; // Number of seconds in a slot uint32 epochDuration; // Number of slots in an epoch /** - * @notice Number of epochs after the end of a given epoch that proofs are still accepted. For example, a value of 1 means that after epoch n ends, the proofs must land *before* epoch n+1 ends. A value of 0 would mean that the proofs for epoch n must land while the epoch is ongoing. + * @notice Number of epochs after the end of a given epoch that proofs are still accepted. For example, a value of 1 + * means that after epoch n ends, the proofs must land *before* epoch n+1 ends. A value of 0 would mean that the + * proofs for epoch n must land while the epoch is ongoing. */ uint32 proofSubmissionEpochs; } @@ -91,9 +93,7 @@ library TimeLib { function epochFromTimestamp(Timestamp _a) internal view returns (Epoch) { TimeStorage storage store = getStorage(); - return Epoch.wrap( - (Timestamp.unwrap(_a) - store.genesisTime) / (store.epochDuration * store.slotDuration) - ); + return Epoch.wrap((Timestamp.unwrap(_a) - store.genesisTime) / (store.epochDuration * store.slotDuration)); } function epochFromSlot(Slot _a) internal view returns (Epoch) { diff --git a/l1-contracts/src/core/libraries/compressed-data/BlockLog.sol b/l1-contracts/src/core/libraries/compressed-data/BlockLog.sol index 96479484ed17..a3f3dc4e8b36 100644 --- a/l1-contracts/src/core/libraries/compressed-data/BlockLog.sol +++ b/l1-contracts/src/core/libraries/compressed-data/BlockLog.sol @@ -2,11 +2,7 @@ // Copyright 2024 Aztec Labs. pragma solidity >=0.8.27; -import { - CompressedFeeHeader, - FeeHeader, - FeeHeaderLib -} from "@aztec/core/libraries/compressed-data/fees/FeeStructs.sol"; +import {CompressedFeeHeader, FeeHeader, FeeHeaderLib} from "@aztec/core/libraries/compressed-data/fees/FeeStructs.sol"; import {CompressedSlot, CompressedTimeMath} from "@aztec/shared/libraries/CompressedTimeMath.sol"; import {Slot} from "@aztec/shared/libraries/TimeMath.sol"; @@ -14,7 +10,8 @@ import {Slot} from "@aztec/shared/libraries/TimeMath.sol"; * @notice Struct for storing block data, set in proposal. * @param archive - Archive tree root of the block * @param headerHash - Hash of the proposed block header - * @param blobCommitmentsHash - H(...H(H(commitment_0), commitment_1).... commitment_n) - used to validate we are using the same blob commitments on L1 and in the rollup circuit + * @param blobCommitmentsHash - H(...H(H(commitment_0), commitment_1).... commitment_n) - used to validate we are using + * the same blob commitments on L1 and in the rollup circuit * @param attestationsHash - Hash of the attestations for this block * @param payloadDigest - Digest of the proposal payload that was attested to * @param slotNumber - This block's slot @@ -53,11 +50,7 @@ library CompressedTempBlockLogLib { using FeeHeaderLib for FeeHeader; using FeeHeaderLib for CompressedFeeHeader; - function compress(TempBlockLog memory _blockLog) - internal - pure - returns (CompressedTempBlockLog memory) - { + function compress(TempBlockLog memory _blockLog) internal pure returns (CompressedTempBlockLog memory) { return CompressedTempBlockLog({ headerHash: _blockLog.headerHash, blobCommitmentsHash: _blockLog.blobCommitmentsHash, @@ -68,11 +61,7 @@ library CompressedTempBlockLogLib { }); } - function decompress(CompressedTempBlockLog memory _compressedBlockLog) - internal - pure - returns (TempBlockLog memory) - { + function decompress(CompressedTempBlockLog memory _compressedBlockLog) internal pure returns (TempBlockLog memory) { return TempBlockLog({ headerHash: _compressedBlockLog.headerHash, blobCommitmentsHash: _compressedBlockLog.blobCommitmentsHash, diff --git a/l1-contracts/src/core/libraries/compressed-data/StakingQueueConfig.sol b/l1-contracts/src/core/libraries/compressed-data/StakingQueueConfig.sol index 84c2870ca6a6..7e8beec46142 100644 --- a/l1-contracts/src/core/libraries/compressed-data/StakingQueueConfig.sol +++ b/l1-contracts/src/core/libraries/compressed-data/StakingQueueConfig.sol @@ -6,17 +6,22 @@ import {SafeCast} from "@oz/utils/math/SafeCast.sol"; type CompressedStakingQueueConfig is uint256; /** - * If the number of validators in the rollup is 0, and the number of validators in the queue is less than `bootstrapValidatorSetSize`, + * If the number of validators in the rollup is 0, and the number of validators in the queue is less than + * `bootstrapValidatorSetSize`, * then `getEntryQueueFlushSize` will return 0. * - * If the number of validators in the rollup is 0, and the number of validators in the queue is greater than or equal to `bootstrapValidatorSetSize`, + * If the number of validators in the rollup is 0, and the number of validators in the queue is greater than or equal to + * `bootstrapValidatorSetSize`, * then `getEntryQueueFlushSize` will return `bootstrapFlushSize`. * - * If the number of validators in the rollup is greater than 0 and less than `bootstrapValidatorSetSize`, then `getEntryQueueFlushSize` will return `bootstrapFlushSize`. + * If the number of validators in the rollup is greater than 0 and less than `bootstrapValidatorSetSize`, then + * `getEntryQueueFlushSize` will return `bootstrapFlushSize`. * - * If the number of validators in the rollup is greater than or equal to `bootstrapValidatorSetSize`, then `getEntryQueueFlushSize` will return Max( `normalFlushSizeMin`, `activeAttesterCount` / `normalFlushSizeQuotient`). + * If the number of validators in the rollup is greater than or equal to `bootstrapValidatorSetSize`, then + * `getEntryQueueFlushSize` will return Max( `normalFlushSizeMin`, `activeAttesterCount` / `normalFlushSizeQuotient`). * - * NOTE: We will NEVER flush more than `MAX_QUEUE_FLUSH_SIZE` validators: it is applied as a Max at the end of every calculation. + * NOTE: We will NEVER flush more than `MAX_QUEUE_FLUSH_SIZE` validators: it is applied as a Max at the end of every + * calculation. * This is to prevent a situation where flushing the queue would exceed the block gas limit. */ struct StakingQueueConfig { @@ -31,11 +36,7 @@ library StakingQueueConfigLib { uint256 private constant MASK_64BIT = 0xFFFFFFFFFFFFFFFF; - function compress(StakingQueueConfig memory _config) - internal - pure - returns (CompressedStakingQueueConfig) - { + function compress(StakingQueueConfig memory _config) internal pure returns (CompressedStakingQueueConfig) { uint256 value = 0; value |= uint256(_config.normalFlushSizeQuotient.toUint64()); value |= uint256(_config.normalFlushSizeMin.toUint64()) << 64; @@ -45,11 +46,7 @@ library StakingQueueConfigLib { return CompressedStakingQueueConfig.wrap(value); } - function decompress(CompressedStakingQueueConfig _compressedConfig) - internal - pure - returns (StakingQueueConfig memory) - { + function decompress(CompressedStakingQueueConfig _compressedConfig) internal pure returns (StakingQueueConfig memory) { uint256 value = CompressedStakingQueueConfig.unwrap(_compressedConfig); return StakingQueueConfig({ diff --git a/l1-contracts/src/core/libraries/compressed-data/Tips.sol b/l1-contracts/src/core/libraries/compressed-data/Tips.sol index 0cb5c2dab02a..44075ca3c494 100644 --- a/l1-contracts/src/core/libraries/compressed-data/Tips.sol +++ b/l1-contracts/src/core/libraries/compressed-data/Tips.sol @@ -18,34 +18,28 @@ library ChainTipsLib { 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000; uint256 internal constant PROVEN_BLOCK_NUMBER_MASK = 0xffffffffffffffffffffffffffffffff; - function getPendingBlockNumber(CompressedChainTips _compressedChainTips) - internal - pure - returns (uint256) - { + function getPendingBlockNumber(CompressedChainTips _compressedChainTips) internal pure returns (uint256) { return CompressedChainTips.unwrap(_compressedChainTips) >> 128; } - function getProvenBlockNumber(CompressedChainTips _compressedChainTips) - internal - pure - returns (uint256) - { + function getProvenBlockNumber(CompressedChainTips _compressedChainTips) internal pure returns (uint256) { return CompressedChainTips.unwrap(_compressedChainTips) & PROVEN_BLOCK_NUMBER_MASK; } - function updatePendingBlockNumber( - CompressedChainTips _compressedChainTips, - uint256 _pendingBlockNumber - ) internal pure returns (CompressedChainTips) { + function updatePendingBlockNumber(CompressedChainTips _compressedChainTips, uint256 _pendingBlockNumber) + internal + pure + returns (CompressedChainTips) + { uint256 value = CompressedChainTips.unwrap(_compressedChainTips) & ~PENDING_BLOCK_NUMBER_MASK; return CompressedChainTips.wrap(value | (_pendingBlockNumber << 128)); } - function updateProvenBlockNumber( - CompressedChainTips _compressedChainTips, - uint256 _provenBlockNumber - ) internal pure returns (CompressedChainTips) { + function updateProvenBlockNumber(CompressedChainTips _compressedChainTips, uint256 _provenBlockNumber) + internal + pure + returns (CompressedChainTips) + { uint256 value = CompressedChainTips.unwrap(_compressedChainTips) & ~PROVEN_BLOCK_NUMBER_MASK; return CompressedChainTips.wrap(value | _provenBlockNumber); } @@ -57,11 +51,7 @@ library ChainTipsLib { return CompressedChainTips.wrap((pending << 128) | proven); } - function decompress(CompressedChainTips _compressedChainTips) - internal - pure - returns (ChainTips memory) - { + function decompress(CompressedChainTips _compressedChainTips) internal pure returns (ChainTips memory) { return ChainTips({ pendingBlockNumber: getPendingBlockNumber(_compressedChainTips), provenBlockNumber: getProvenBlockNumber(_compressedChainTips) diff --git a/l1-contracts/src/core/libraries/compressed-data/fees/FeeConfig.sol b/l1-contracts/src/core/libraries/compressed-data/fees/FeeConfig.sol index 21e176ca2cdd..d597f987067e 100644 --- a/l1-contracts/src/core/libraries/compressed-data/fees/FeeConfig.sol +++ b/l1-contracts/src/core/libraries/compressed-data/fees/FeeConfig.sol @@ -32,33 +32,17 @@ struct FeeConfig { } library PriceLib { - function toEth(FeeAssetValue _feeAssetValue, FeeAssetPerEthE9 _feeAssetPerEth) - internal - pure - returns (EthValue) - { + function toEth(FeeAssetValue _feeAssetValue, FeeAssetPerEthE9 _feeAssetPerEth) internal pure returns (EthValue) { return EthValue.wrap( Math.mulDiv( - FeeAssetValue.unwrap(_feeAssetValue), - 1e9, - FeeAssetPerEthE9.unwrap(_feeAssetPerEth), - Math.Rounding.Ceil + FeeAssetValue.unwrap(_feeAssetValue), 1e9, FeeAssetPerEthE9.unwrap(_feeAssetPerEth), Math.Rounding.Ceil ) ); } - function toFeeAsset(EthValue _ethValue, FeeAssetPerEthE9 _feeAssetPerEth) - internal - pure - returns (FeeAssetValue) - { + function toFeeAsset(EthValue _ethValue, FeeAssetPerEthE9 _feeAssetPerEth) internal pure returns (FeeAssetValue) { return FeeAssetValue.wrap( - Math.mulDiv( - EthValue.unwrap(_ethValue), - FeeAssetPerEthE9.unwrap(_feeAssetPerEth), - 1e9, - Math.Rounding.Ceil - ) + Math.mulDiv(EthValue.unwrap(_ethValue), FeeAssetPerEthE9.unwrap(_feeAssetPerEth), 1e9, Math.Rounding.Ceil) ); } } @@ -73,20 +57,11 @@ library FeeConfigLib { return (CompressedFeeConfig.unwrap(_compressedFeeConfig) >> 192) & MASK_64_BITS; } - function getCongestionUpdateFraction(CompressedFeeConfig _compressedFeeConfig) - internal - pure - returns (uint256) - { - return - (CompressedFeeConfig.unwrap(_compressedFeeConfig) >> 64) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; + function getCongestionUpdateFraction(CompressedFeeConfig _compressedFeeConfig) internal pure returns (uint256) { + return (CompressedFeeConfig.unwrap(_compressedFeeConfig) >> 64) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; } - function getProvingCostPerMana(CompressedFeeConfig _compressedFeeConfig) - internal - pure - returns (EthValue) - { + function getProvingCostPerMana(CompressedFeeConfig _compressedFeeConfig) internal pure returns (EthValue) { return EthValue.wrap(CompressedFeeConfig.unwrap(_compressedFeeConfig) & MASK_64_BITS); } @@ -99,11 +74,7 @@ library FeeConfigLib { return CompressedFeeConfig.wrap(value); } - function decompress(CompressedFeeConfig _compressedFeeConfig) - internal - pure - returns (FeeConfig memory) - { + function decompress(CompressedFeeConfig _compressedFeeConfig) internal pure returns (FeeConfig memory) { return FeeConfig({ provingCostPerMana: getProvingCostPerMana(_compressedFeeConfig), congestionUpdateFraction: getCongestionUpdateFraction(_compressedFeeConfig), diff --git a/l1-contracts/src/core/libraries/compressed-data/fees/FeeStructs.sol b/l1-contracts/src/core/libraries/compressed-data/fees/FeeStructs.sol index 99ba21ae7012..00fcc98ce97d 100644 --- a/l1-contracts/src/core/libraries/compressed-data/fees/FeeStructs.sol +++ b/l1-contracts/src/core/libraries/compressed-data/fees/FeeStructs.sol @@ -87,20 +87,12 @@ library FeeHeaderLib { return (CompressedFeeHeader.unwrap(_compressedFeeHeader) >> 32) & 0xFFFFFFFFFFFF; } - function getFeeAssetPriceNumerator(CompressedFeeHeader _compressedFeeHeader) - internal - pure - returns (uint256) - { + function getFeeAssetPriceNumerator(CompressedFeeHeader _compressedFeeHeader) internal pure returns (uint256) { // Reads the bits 128-175 return (CompressedFeeHeader.unwrap(_compressedFeeHeader) >> 80) & 0xFFFFFFFFFFFF; } - function getCongestionCost(CompressedFeeHeader _compressedFeeHeader) - internal - pure - returns (uint256) - { + function getCongestionCost(CompressedFeeHeader _compressedFeeHeader) internal pure returns (uint256) { // Reads the bits 64-127 return (CompressedFeeHeader.unwrap(_compressedFeeHeader) >> 128) & 0xFFFFFFFFFFFFFFFF; } @@ -128,11 +120,7 @@ library FeeHeaderLib { return CompressedFeeHeader.wrap(value); } - function decompress(CompressedFeeHeader _compressedFeeHeader) - internal - pure - returns (FeeHeader memory) - { + function decompress(CompressedFeeHeader _compressedFeeHeader) internal pure returns (FeeHeader memory) { uint256 value = CompressedFeeHeader.unwrap(_compressedFeeHeader); uint256 manaUsed = value & 0xFFFFFFFF; @@ -154,11 +142,7 @@ library FeeHeaderLib { }); } - function preheat(CompressedFeeHeader _compressedFeeHeader) - internal - pure - returns (CompressedFeeHeader) - { + function preheat(CompressedFeeHeader _compressedFeeHeader) internal pure returns (CompressedFeeHeader) { uint256 value = CompressedFeeHeader.unwrap(_compressedFeeHeader); value |= 1 << 255; return CompressedFeeHeader.wrap(value); diff --git a/l1-contracts/src/core/libraries/crypto/Hash.sol b/l1-contracts/src/core/libraries/crypto/Hash.sol index bb01deb436ce..b2d4df0aac56 100644 --- a/l1-contracts/src/core/libraries/crypto/Hash.sol +++ b/l1-contracts/src/core/libraries/crypto/Hash.sol @@ -18,9 +18,7 @@ library Hash { */ function sha256ToField(DataStructures.L1ToL2Msg memory _message) internal pure returns (bytes32) { return sha256ToField( - abi.encode( - _message.sender, _message.recipient, _message.content, _message.secretHash, _message.index - ) + abi.encode(_message.sender, _message.recipient, _message.content, _message.secretHash, _message.index) ); } @@ -43,7 +41,8 @@ library Hash { /** * @notice Computes the sha256 hash of the provided data and converts it to a field element - * @dev Truncating one byte to convert the hash to a field element. We prepend a byte rather than cast bytes31(bytes32) to match Noir's to_be_bytes. + * @dev Truncating one byte to convert the hash to a field element. We prepend a byte rather than cast + * bytes31(bytes32) to match Noir's to_be_bytes. * @param _data - The bytes to hash * @return The hash of the provided data as a field element */ diff --git a/l1-contracts/src/core/libraries/crypto/MerkleLib.sol b/l1-contracts/src/core/libraries/crypto/MerkleLib.sol index 24224b6fe624..7b9e6fcfe718 100644 --- a/l1-contracts/src/core/libraries/crypto/MerkleLib.sol +++ b/l1-contracts/src/core/libraries/crypto/MerkleLib.sol @@ -19,25 +19,25 @@ library MerkleLib { * @param _index - The index of the message inside the L2 to L1 message tree * @param _expectedRoot - The expected root to check the validity of the message and sibling path with. * @notice - - * E.g. A sibling path for a leaf at index 3 (L) in a tree of depth 3 (between 5 and 8 leafs) consists of the 3 elements denoted as *'s + * E.g. A sibling path for a leaf at index 3 (L) in a tree of depth 3 (between 5 and 8 leafs) consists of the 3 + * elements denoted as *'s * d0: [ root ] * d1: [ ] [*] * d2: [*] [ ] [ ] [ ] * d3: [ ] [ ] [*] [L] [ ] [ ] [ ] [ ]. * And the elements would be ordered as: [ d3_index_2, d2_index_0, d1_index_1 ]. */ - function verifyMembership( - bytes32[] calldata _path, - bytes32 _leaf, - uint256 _index, - bytes32 _expectedRoot - ) internal pure { + function verifyMembership(bytes32[] calldata _path, bytes32 _leaf, uint256 _index, bytes32 _expectedRoot) + internal + pure + { bytes32 subtreeRoot = _leaf; /// @notice - We use the indexAtHeight to see whether our child of the next subtree is at the left or the right side uint256 indexAtHeight = _index; for (uint256 height = 0; height < _path.length; height++) { - /// @notice - This affects the way we concatenate our two children to then hash and calculate the root, as any odd indexes (index bit-masked with least significant bit) are right-sided children. + /// @notice - This affects the way we concatenate our two children to then hash and calculate the root, as any odd + /// indexes (index bit-masked with least significant bit) are right-sided children. bool isRight = (indexAtHeight & 1) == 1; subtreeRoot = isRight @@ -47,10 +47,7 @@ library MerkleLib { indexAtHeight >>= 1; } - require( - subtreeRoot == _expectedRoot, - Errors.MerkleLib__InvalidRoot(_expectedRoot, subtreeRoot, _leaf, _index) - ); + require(subtreeRoot == _expectedRoot, Errors.MerkleLib__InvalidRoot(_expectedRoot, subtreeRoot, _leaf, _index)); } /** @@ -106,8 +103,7 @@ library MerkleLib { leavesInSubtree[i - start] = _leaves[i]; } bytes32 subtreeRoot = computeRoot(leavesInSubtree); - root = - numTxs == _leaves.length ? subtreeRoot : Hash.sha256ToField(bytes.concat(subtreeRoot, root)); + root = numTxs == _leaves.length ? subtreeRoot : Hash.sha256ToField(bytes.concat(subtreeRoot, root)); numTxs -= currentSubtreeSize; currentSubtreeSize <<= 1; } diff --git a/l1-contracts/src/core/libraries/crypto/SampleLib.sol b/l1-contracts/src/core/libraries/crypto/SampleLib.sol index 97bc18267ec8..2f90879422ec 100644 --- a/l1-contracts/src/core/libraries/crypto/SampleLib.sol +++ b/l1-contracts/src/core/libraries/crypto/SampleLib.sol @@ -34,10 +34,7 @@ library SampleLib { internal returns (uint256[] memory) { - require( - _committeeSize <= _indexCount, - Errors.SampleLib__SampleLargerThanIndex(_committeeSize, _indexCount) - ); + require(_committeeSize <= _indexCount, Errors.SampleLib__SampleLargerThanIndex(_committeeSize, _indexCount)); if (_committeeSize == 0) { return new uint256[](0); @@ -100,11 +97,7 @@ library SampleLib { * * @return shuffledIndex - The shuffled index */ - function computeSampleIndex(uint256 _index, uint256 _indexCount, uint256 _seed) - internal - pure - returns (uint256) - { + function computeSampleIndex(uint256 _index, uint256 _indexCount, uint256 _seed) internal pure returns (uint256) { // Cannot modulo by 0 if (_indexCount == 0) { return 0; diff --git a/l1-contracts/src/core/libraries/rollup/BlobLib.sol b/l1-contracts/src/core/libraries/rollup/BlobLib.sol index 09011259a819..f6dafca54c22 100644 --- a/l1-contracts/src/core/libraries/rollup/BlobLib.sol +++ b/l1-contracts/src/core/libraries/rollup/BlobLib.sol @@ -54,26 +54,26 @@ library BlobLib { /** * @notice Validate an L2 block's blobs and return the blobHashes, the hashed blobHashes, and blob commitments. * - * We assume that the Aztec related blobs will be first in the propose transaction, additional blobs can be at the end. + * We assume that the Aztec related blobs will be first in the propose transaction, additional blobs can be + * at the end. * * Input bytes: * input[0] - num blobs in block * input[1:] - blob commitments (48 bytes * num blobs in block) * @param _blobsInput - The above bytes to verify our input blob commitments match real blobs - * @param _checkBlob - Whether to skip blob related checks. Hardcoded to true (See RollupCore.sol -> checkBlob), exists only to be overriden in tests. + * @param _checkBlob - Whether to skip blob related checks. Hardcoded to true (See RollupCore.sol -> checkBlob), + * exists only to be overriden in tests. * Returns for proposal: * @return blobHashes - All of the blob hashes included in this block, to be emitted in L2BlockProposed event. - * @return blobsHashesCommitment - A hash of all blob hashes in this block, to be included in the block header. See comment at the end of this fn for more info. - * @return blobCommitments - All of the blob commitments included in this block, to be stored then validated against those used in the rollup in epoch proof verification. + * @return blobsHashesCommitment - A hash of all blob hashes in this block, to be included in the block header. See + * comment at the end of this fn for more info. + * @return blobCommitments - All of the blob commitments included in this block, to be stored then validated against + * those used in the rollup in epoch proof verification. */ function validateBlobs(bytes calldata _blobsInput, bool _checkBlob) internal view - returns ( - bytes32[] memory blobHashes, - bytes32 blobsHashesCommitment, - bytes[] memory blobCommitments - ) + returns (bytes32[] memory blobHashes, bytes32 blobsHashesCommitment, bytes[] memory blobCommitments) { // We cannot input the incorrect number of blobs below, as the blobsHash // and epoch proof verification will fail. @@ -85,9 +85,8 @@ library BlobLib { uint256 blobInputStart = 1; for (uint256 i = 0; i < numBlobs; i++) { // Commitments = arrays of bytes48 compressed points - blobCommitments[i] = abi.encodePacked( - _blobsInput[blobInputStart:blobInputStart + Constants.BLS12_POINT_COMPRESSED_BYTES] - ); + blobCommitments[i] = + abi.encodePacked(_blobsInput[blobInputStart:blobInputStart + Constants.BLS12_POINT_COMPRESSED_BYTES]); blobInputStart += Constants.BLS12_POINT_COMPRESSED_BYTES; bytes32 blobHashCheck = calculateBlobHash(blobCommitments[i]); @@ -102,32 +101,40 @@ library BlobLib { blobHashes[i] = blobHash; } // Hash the EVM blob hashes for the block header - // TODO(#13430): The below blobsHashesCommitment known as blobsHash elsewhere in the code. The name blobsHashesCommitment is confusingly similar to blobCommitmentsHash + // TODO(#13430): The below blobsHashesCommitment known as blobsHash elsewhere in the code. The name + // blobsHashesCommitment is confusingly similar to blobCommitmentsHash // which are different values: - // - blobsHash := sha256([blobhash_0, ..., blobhash_m]) = a hash of all blob hashes in a block with m+1 blobs inserted into the header, exists so a user can cross check blobs. - // - blobCommitmentsHash := sha256( ...sha256(sha256(C_0), C_1) ... C_n) = iteratively calculated hash of all blob commitments in an epoch with n+1 blobs (see calculateBlobCommitmentsHash()), + // - blobsHash := sha256([blobhash_0, ..., blobhash_m]) = a hash of all blob hashes in a block with m+1 blobs + // inserted into the header, exists so a user can cross check blobs. + // - blobCommitmentsHash := sha256( ...sha256(sha256(C_0), C_1) ... C_n) = iteratively calculated hash of all blob + // commitments in an epoch with n+1 blobs (see calculateBlobCommitmentsHash()), // exists so we can validate injected commitments to the rollup circuits correspond to the correct real blobs. - // We may be able to combine these values e.g. blobCommitmentsHash := sha256( ...sha256(sha256(blobshash_0), blobshash_1) ... blobshash_l) for an epoch with l+1 blocks. + // We may be able to combine these values e.g. blobCommitmentsHash := sha256( ...sha256(sha256(blobshash_0), + // blobshash_1) ... blobshash_l) for an epoch with l+1 blocks. blobsHashesCommitment = Hash.sha256ToField(abi.encodePacked(blobHashes)); } /** * @notice Validate a batched blob. * Input bytes: - * input[:32] - versioned_hash - NB for a batched blob, this is simply the versioned hash of the batched commitment + * input[:32] - versioned_hash - NB for a batched blob, this is simply the versioned hash of the batched + * commitment * input[32:64] - z = poseidon2( ...poseidon2(poseidon2(z_0, z_1), z_2) ... z_n) * input[64:96] - y = y_0 + gamma * y_1 + gamma^2 * y_2 + ... + gamma^n * y_n * input[96:144] - commitment C = C_0 + gamma * C_1 + gamma^2 * C_2 + ... + gamma^n * C_n - * input[144:192] - proof (a commitment to the quotient polynomial q(X)) = Q_0 + gamma * Q_1 + gamma^2 * Q_2 + ... + gamma^n * Q_n + * input[144:192] - proof (a commitment to the quotient polynomial q(X)) = Q_0 + gamma * Q_1 + gamma^2 * Q_2 + ... + + * gamma^n * Q_n * @param _blobInput - The above bytes to verify a batched blob * * If this function passes where the values of z, y, and C are valid public inputs to the final epoch root proof, then * we know that the data in each blob of the epoch corresponds to the tx effects of all our proven txs in the epoch. * - * The rollup circuits calculate each z_i and y_i as above, so if this function passes but they do not match the values from the + * The rollup circuits calculate each z_i and y_i as above, so if this function passes but they do not match the + * values from the * circuit, then proof verification will fail. * - * Each commitment C_i is injected into the circuits and their correctness is validated using the blobCommitmentsHash, as + * Each commitment C_i is injected into the circuits and their correctness is validated using the blobCommitmentsHash, + * as * explained below in calculateBlobCommitmentsHash(). * */ @@ -175,8 +182,7 @@ library BlobLib { currentblobCommitmentsHash = Hash.sha256ToField(abi.encodePacked(_blobCommitments[i++])); } for (i; i < _blobCommitments.length; i++) { - currentblobCommitmentsHash = - Hash.sha256ToField(abi.encodePacked(currentblobCommitmentsHash, _blobCommitments[i])); + currentblobCommitmentsHash = Hash.sha256ToField(abi.encodePacked(currentblobCommitmentsHash, _blobCommitments[i])); } } @@ -191,10 +197,8 @@ library BlobLib { */ function calculateBlobHash(bytes memory _blobCommitment) internal pure returns (bytes32) { return bytes32( - ( - uint256(sha256(_blobCommitment)) - & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - ) | VERSIONED_HASH_VERSION_KZG + (uint256(sha256(_blobCommitment)) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) + | VERSIONED_HASH_VERSION_KZG ); } } diff --git a/l1-contracts/src/core/libraries/rollup/EpochProofLib.sol b/l1-contracts/src/core/libraries/rollup/EpochProofLib.sol index 7a1ac7b20d51..612b295a2794 100644 --- a/l1-contracts/src/core/libraries/rollup/EpochProofLib.sol +++ b/l1-contracts/src/core/libraries/rollup/EpochProofLib.sol @@ -2,12 +2,7 @@ // Copyright 2024 Aztec Labs. pragma solidity >=0.8.27; -import { - SubmitEpochRootProofArgs, - PublicInputArgs, - IRollupCore, - RollupStore -} from "@aztec/core/interfaces/IRollup.sol"; +import {SubmitEpochRootProofArgs, PublicInputArgs, IRollupCore, RollupStore} from "@aztec/core/interfaces/IRollup.sol"; import {CompressedTempBlockLog} from "@aztec/core/libraries/compressed-data/BlockLog.sol"; import {ChainTipsLib, CompressedChainTips} from "@aztec/core/libraries/compressed-data/Tips.sol"; import {Constants} from "@aztec/core/libraries/ConstantsGen.sol"; @@ -61,7 +56,8 @@ library EpochProofLib { * _end - The block number at the end of the epoch * _args - Array of public inputs to the proof (previousArchive, endArchive, endTimestamp, outHash, proverId) * _fees - Array of recipient-value pairs with fees to be distributed for the epoch - * _blobInputs - The batched blob inputs for the EVM point evaluation precompile and as public inputs for the proof + * _blobInputs - The batched blob inputs for the EVM point evaluation precompile and as public inputs for the + * proof * _proof - The proof to verify */ function submitEpochRootProof(SubmitEpochRootProofArgs calldata _args) internal { @@ -77,9 +73,8 @@ library EpochProofLib { require(verifyEpochRootProof(_args), Errors.Rollup__InvalidProof()); RollupStore storage rollupStore = STFLib.getStorage(); - rollupStore.tips = rollupStore.tips.updateProvenBlockNumber( - Math.max(rollupStore.tips.getProvenBlockNumber(), _args.end) - ); + rollupStore.tips = + rollupStore.tips.updateProvenBlockNumber(Math.max(rollupStore.tips.getProvenBlockNumber(), _args.end)); RewardLib.handleRewardsAndFees(_args, endEpoch); @@ -123,8 +118,7 @@ library EpochProofLib { { bytes32 expectedEndArchive = rollupStore.archives[_end]; require( - expectedEndArchive == _args.endArchive, - Errors.Rollup__InvalidArchive(expectedEndArchive, _args.endArchive) + expectedEndArchive == _args.endArchive, Errors.Rollup__InvalidArchive(expectedEndArchive, _args.endArchive) ); } } @@ -187,9 +181,12 @@ library EpochProofLib { offset += 1; // FinalBlobAccumulatorPublicInputs: - // The blob public inputs do not require the versioned hash of the batched commitment, which is stored in _blobPublicInputs[0:32] - // or the KZG opening 'proof' (commitment Q) stored in _blobPublicInputs[144:]. They are used in validateBatchedBlob(). - // See BlobLib.sol -> validateBatchedBlob() and calculateBlobCommitmentsHash() for documentation on the below blob related inputs. + // The blob public inputs do not require the versioned hash of the batched commitment, which is stored in + // _blobPublicInputs[0:32] + // or the KZG opening 'proof' (commitment Q) stored in _blobPublicInputs[144:]. They are used in + // validateBatchedBlob(). + // See BlobLib.sol -> validateBatchedBlob() and calculateBlobCommitmentsHash() for documentation on the below blob + // related inputs. // blobCommitmentsHash publicInputs[offset] = STFLib.getBlobCommitmentsHash(_end); @@ -221,18 +218,13 @@ library EpochProofLib { * @param _endBlockNumber The last block number in the epoch * @param _attestations The attestations to verify */ - function verifyLastBlockAttestations( - uint256 _endBlockNumber, - CommitteeAttestations memory _attestations - ) private { + function verifyLastBlockAttestations(uint256 _endBlockNumber, CommitteeAttestations memory _attestations) private { // Get the stored attestation hash and payload digest for the last block CompressedTempBlockLog storage blockLog = STFLib.getStorageTempBlockLog(_endBlockNumber); // Verify that the provided attestations match the stored hash bytes32 providedAttestationsHash = keccak256(abi.encode(_attestations)); - require( - providedAttestationsHash == blockLog.attestationsHash, Errors.Rollup__InvalidAttestations() - ); + require(providedAttestationsHash == blockLog.attestationsHash, Errors.Rollup__InvalidAttestations()); // Get the slot and epoch for the last block Slot slot = blockLog.slotNumber.decompress(); @@ -271,18 +263,13 @@ library EpochProofLib { bool claimedNumBlocksInEpoch = _end - _start + 1 <= Constants.AZTEC_MAX_EPOCH_DURATION; require( - claimedNumBlocksInEpoch, - Errors.Rollup__TooManyBlocksInEpoch(Constants.AZTEC_MAX_EPOCH_DURATION, _end - _start) + claimedNumBlocksInEpoch, Errors.Rollup__TooManyBlocksInEpoch(Constants.AZTEC_MAX_EPOCH_DURATION, _end - _start) ); return endEpoch; } - function verifyEpochRootProof(SubmitEpochRootProofArgs calldata _args) - private - view - returns (bool) - { + function verifyEpochRootProof(SubmitEpochRootProofArgs calldata _args) private view returns (bool) { RollupStore storage rollupStore = STFLib.getStorage(); BlobLib.validateBatchedBlob(_args.blobInputs); @@ -290,10 +277,7 @@ library EpochProofLib { bytes32[] memory publicInputs = getEpochProofPublicInputs(_args.start, _args.end, _args.args, _args.fees, _args.blobInputs); - require( - rollupStore.config.epochProofVerifier.verify(_args.proof, publicInputs), - Errors.Rollup__InvalidProof() - ); + require(rollupStore.config.epochProofVerifier.verify(_args.proof, publicInputs), Errors.Rollup__InvalidProof()); return true; } diff --git a/l1-contracts/src/core/libraries/rollup/ExtRollupLib.sol b/l1-contracts/src/core/libraries/rollup/ExtRollupLib.sol index b325fd71849e..e4cde6e33eed 100644 --- a/l1-contracts/src/core/libraries/rollup/ExtRollupLib.sol +++ b/l1-contracts/src/core/libraries/rollup/ExtRollupLib.sol @@ -11,11 +11,7 @@ import {BlobLib} from "./BlobLib.sol"; import {EpochProofLib} from "./EpochProofLib.sol"; import {SignatureLib} from "@aztec/shared/libraries/SignatureLib.sol"; import { - ProposeLib, - ProposeArgs, - CommitteeAttestations, - ValidateHeaderArgs, - ValidatorSelectionLib + ProposeLib, ProposeArgs, CommitteeAttestations, ValidateHeaderArgs, ValidatorSelectionLib } from "./ProposeLib.sol"; // We are using this library such that we can more easily "link" just a larger external library @@ -73,11 +69,7 @@ library ExtRollupLib { function validateBlobs(bytes calldata _blobsInput, bool _checkBlob) external view - returns ( - bytes32[] memory blobHashes, - bytes32 blobsHashesCommitment, - bytes[] memory blobCommitments - ) + returns (bytes32[] memory blobHashes, bytes32 blobsHashesCommitment, bytes[] memory blobCommitments) { return BlobLib.validateBlobs(_blobsInput, _checkBlob); } diff --git a/l1-contracts/src/core/libraries/rollup/ExtRollupLib2.sol b/l1-contracts/src/core/libraries/rollup/ExtRollupLib2.sol index 07e6bc8aa4d5..71581e0f18fb 100644 --- a/l1-contracts/src/core/libraries/rollup/ExtRollupLib2.sol +++ b/l1-contracts/src/core/libraries/rollup/ExtRollupLib2.sol @@ -76,10 +76,7 @@ library ExtRollupLib2 { return StakingLib.trySlash(_attester, _amount); } - function canProposeAtTime(Timestamp _ts, bytes32 _archive, address _who) - external - returns (Slot, uint256) - { + function canProposeAtTime(Timestamp _ts, bytes32 _archive, address _who) external returns (Slot, uint256) { return ValidatorSelectionLib.canProposeAtTime(_ts, _archive, _who); } diff --git a/l1-contracts/src/core/libraries/rollup/ExtRollupLib3.sol b/l1-contracts/src/core/libraries/rollup/ExtRollupLib3.sol index f20ea4f8579b..35a166b3c325 100644 --- a/l1-contracts/src/core/libraries/rollup/ExtRollupLib3.sol +++ b/l1-contracts/src/core/libraries/rollup/ExtRollupLib3.sol @@ -25,11 +25,7 @@ library ExtRollupLib3 { address _slashingVetoer ) external returns (ISlasher) { Slasher slasher = new Slasher( - _slashingQuorum, - _slashingRoundSize, - _slashingLifetimeInRounds, - _slashingExecutionDelayInRounds, - _slashingVetoer + _slashingQuorum, _slashingRoundSize, _slashingLifetimeInRounds, _slashingExecutionDelayInRounds, _slashingVetoer ); return ISlasher(address(slasher)); } diff --git a/l1-contracts/src/core/libraries/rollup/FeeLib.sol b/l1-contracts/src/core/libraries/rollup/FeeLib.sol index 159f6d5b3975..be73d7cb67de 100644 --- a/l1-contracts/src/core/libraries/rollup/FeeLib.sol +++ b/l1-contracts/src/core/libraries/rollup/FeeLib.sol @@ -34,8 +34,8 @@ uint256 constant MINIMUM_FEE_ASSET_PER_ETH = 10e9; uint256 constant MAX_FEE_ASSET_PRICE_MODIFIER = 1e6; uint256 constant FEE_ASSET_PRICE_UPDATE_FRACTION = 100e6; -uint256 constant L1_GAS_PER_BLOCK_PROPOSED = 300000; -uint256 constant L1_GAS_PER_EPOCH_VERIFIED = 1000000; +uint256 constant L1_GAS_PER_BLOCK_PROPOSED = 300_000; +uint256 constant L1_GAS_PER_EPOCH_VERIFIED = 1_000_000; uint256 constant MINIMUM_CONGESTION_MULTIPLIER = 1e9; @@ -43,7 +43,7 @@ uint256 constant MINIMUM_CONGESTION_MULTIPLIER = 1e9; // (numerator / denominator) is close to 0.117, as that leads to ~1.125 multiplier // per increase by TARGET of the numerator; uint256 constant MAGIC_CONGESTION_VALUE_DIVISOR = 1e8; -uint256 constant MAGIC_CONGESTION_VALUE_MULTIPLIER = 854700854; +uint256 constant MAGIC_CONGESTION_VALUE_MULTIPLIER = 854_700_854; uint256 constant BLOB_GAS_PER_BLOB = 2 ** 17; uint256 constant BLOBS_PER_BLOCK = 3; @@ -94,8 +94,7 @@ library FeeLib { feeStore.config = FeeConfig({ manaTarget: _manaTarget, - congestionUpdateFraction: _manaTarget * MAGIC_CONGESTION_VALUE_MULTIPLIER - / MAGIC_CONGESTION_VALUE_DIVISOR, + congestionUpdateFraction: _manaTarget * MAGIC_CONGESTION_VALUE_MULTIPLIER / MAGIC_CONGESTION_VALUE_DIVISOR, provingCostPerMana: _provingCostPerMana }).compress(); @@ -111,8 +110,7 @@ library FeeLib { FeeConfig memory config = feeStore.config.decompress(); config.manaTarget = _manaTarget; - config.congestionUpdateFraction = - _manaTarget * MAGIC_CONGESTION_VALUE_MULTIPLIER / MAGIC_CONGESTION_VALUE_DIVISOR; + config.congestionUpdateFraction = _manaTarget * MAGIC_CONGESTION_VALUE_MULTIPLIER / MAGIC_CONGESTION_VALUE_DIVISOR; feeStore.config = config.compress(); } @@ -156,9 +154,7 @@ library FeeLib { CompressedFeeHeader parentFeeHeader = STFLib.getFeeHeader(_blockNumber - 1); return FeeHeader({ excessMana: FeeLib.computeExcessMana(parentFeeHeader), - feeAssetPriceNumerator: FeeLib.clampedAdd( - parentFeeHeader.getFeeAssetPriceNumerator(), _feeAssetPriceModifier - ), + feeAssetPriceNumerator: FeeLib.clampedAdd(parentFeeHeader.getFeeAssetPriceNumerator(), _feeAssetPriceModifier), manaUsed: _manaUsed, congestionCost: _congestionCost, proverCost: _proverCost @@ -172,22 +168,17 @@ library FeeLib { : feeStore.l1GasOracleValues.post.decompress(); } - function getManaBaseFeeComponentsAt( - uint256 _blockOfInterest, - Timestamp _timestamp, - bool _inFeeAsset - ) internal view returns (ManaBaseFeeComponents memory) { + function getManaBaseFeeComponentsAt(uint256 _blockOfInterest, Timestamp _timestamp, bool _inFeeAsset) + internal + view + returns (ManaBaseFeeComponents memory) + { FeeStore storage feeStore = getStorage(); uint256 manaTarget = feeStore.config.getManaTarget(); if (manaTarget == 0) { - return ManaBaseFeeComponents({ - sequencerCost: 0, - proverCost: 0, - congestionCost: 0, - congestionMultiplier: 0 - }); + return ManaBaseFeeComponents({sequencerCost: 0, proverCost: 0, congestionCost: 0, congestionMultiplier: 0}); } EthValue sequencerCostPerMana; @@ -199,23 +190,17 @@ library FeeLib { // Sequencer cost per mana { - uint256 ethUsed = (L1_GAS_PER_BLOCK_PROPOSED * fees.baseFee) - + (BLOBS_PER_BLOCK * BLOB_GAS_PER_BLOB * fees.blobFee); + uint256 ethUsed = + (L1_GAS_PER_BLOCK_PROPOSED * fees.baseFee) + (BLOBS_PER_BLOCK * BLOB_GAS_PER_BLOB * fees.blobFee); - sequencerCostPerMana = - EthValue.wrap(Math.mulDiv(ethUsed, 1, manaTarget, Math.Rounding.Ceil)); + sequencerCostPerMana = EthValue.wrap(Math.mulDiv(ethUsed, 1, manaTarget, Math.Rounding.Ceil)); } // Prover cost per mana { proverCostPerMana = EthValue.wrap( Math.mulDiv( - Math.mulDiv( - L1_GAS_PER_EPOCH_VERIFIED, - fees.baseFee, - TimeLib.getStorage().epochDuration, - Math.Rounding.Ceil - ), + Math.mulDiv(L1_GAS_PER_EPOCH_VERIFIED, fees.baseFee, TimeLib.getStorage().epochDuration, Math.Rounding.Ceil), 1, manaTarget, Math.Rounding.Ceil @@ -227,18 +212,12 @@ library FeeLib { } CompressedFeeHeader parentFeeHeader = STFLib.getFeeHeader(_blockOfInterest); - uint256 excessMana = FeeLib.clampedAdd( - parentFeeHeader.getExcessMana() + parentFeeHeader.getManaUsed(), -int256(manaTarget) - ); + uint256 excessMana = + FeeLib.clampedAdd(parentFeeHeader.getExcessMana() + parentFeeHeader.getManaUsed(), -int256(manaTarget)); uint256 congestionMultiplier_ = congestionMultiplier(excessMana); EthValue congestionCost = EthValue.wrap( - Math.mulDiv( - EthValue.unwrap(total), - congestionMultiplier_, - MINIMUM_CONGESTION_MULTIPLIER, - Math.Rounding.Floor - ) + Math.mulDiv(EthValue.unwrap(total), congestionMultiplier_, MINIMUM_CONGESTION_MULTIPLIER, Math.Rounding.Floor) ) - total; FeeAssetPerEthE9 feeAssetPrice = @@ -276,23 +255,17 @@ library FeeLib { function computeExcessMana(CompressedFeeHeader _feeHeader) internal view returns (uint256) { FeeStore storage feeStore = getStorage(); - return clampedAdd( - _feeHeader.getExcessMana() + _feeHeader.getManaUsed(), - -int256(feeStore.config.getManaTarget()) - ); + return clampedAdd(_feeHeader.getExcessMana() + _feeHeader.getManaUsed(), -int256(feeStore.config.getManaTarget())); } function congestionMultiplier(uint256 _numerator) internal view returns (uint256) { FeeStore storage feeStore = getStorage(); - return fakeExponential( - MINIMUM_CONGESTION_MULTIPLIER, _numerator, feeStore.config.getCongestionUpdateFraction() - ); + return fakeExponential(MINIMUM_CONGESTION_MULTIPLIER, _numerator, feeStore.config.getCongestionUpdateFraction()); } function getFeeAssetPerEth(uint256 _numerator) internal pure returns (FeeAssetPerEthE9) { - return FeeAssetPerEthE9.wrap( - fakeExponential(MINIMUM_FEE_ASSET_PER_ETH, _numerator, FEE_ASSET_PRICE_UPDATE_FRACTION) - ); + return + FeeAssetPerEthE9.wrap(fakeExponential(MINIMUM_FEE_ASSET_PER_ETH, _numerator, FEE_ASSET_PRICE_UPDATE_FRACTION)); } function summedBaseFee(ManaBaseFeeComponents memory _components) internal pure returns (uint256) { @@ -371,11 +344,7 @@ library FeeLib { * @param _denominator The denominator * @return The approximated value `_factor * e ** (_numerator / _denominator)` */ - function fakeExponential(uint256 _factor, uint256 _numerator, uint256 _denominator) - private - pure - returns (uint256) - { + function fakeExponential(uint256 _factor, uint256 _numerator, uint256 _denominator) private pure returns (uint256) { uint256 i = 1; uint256 output = 0; uint256 numeratorAccumulator = _factor * _denominator; diff --git a/l1-contracts/src/core/libraries/rollup/InvalidateLib.sol b/l1-contracts/src/core/libraries/rollup/InvalidateLib.sol index 4fbafdbec9b0..e4c0cea13c02 100644 --- a/l1-contracts/src/core/libraries/rollup/InvalidateLib.sol +++ b/l1-contracts/src/core/libraries/rollup/InvalidateLib.sol @@ -10,9 +10,7 @@ import {STFLib} from "@aztec/core/libraries/rollup/STFLib.sol"; import {ValidatorSelectionLib} from "@aztec/core/libraries/rollup/ValidatorSelectionLib.sol"; import {Timestamp, Slot, Epoch, TimeLib} from "@aztec/core/libraries/TimeLib.sol"; import {CompressedSlot, CompressedTimeMath} from "@aztec/shared/libraries/CompressedTimeMath.sol"; -import { - CommitteeAttestations, SignatureLib, Signature -} from "@aztec/shared/libraries/SignatureLib.sol"; +import {CommitteeAttestations, SignatureLib, Signature} from "@aztec/shared/libraries/SignatureLib.sol"; import {ECDSA} from "@oz/utils/cryptography/ECDSA.sol"; import {MessageHashUtils} from "@oz/utils/cryptography/MessageHashUtils.sol"; @@ -112,37 +110,27 @@ library InvalidateLib { RollupStore storage rollupStore = STFLib.getStorage(); // Block must be in the pending chain - require( - _blockNumber <= rollupStore.tips.getPendingBlockNumber(), - Errors.Rollup__BlockNotInPendingChain() - ); + require(_blockNumber <= rollupStore.tips.getPendingBlockNumber(), Errors.Rollup__BlockNotInPendingChain()); // But not yet proven - require( - _blockNumber > rollupStore.tips.getProvenBlockNumber(), Errors.Rollup__BlockAlreadyProven() - ); + require(_blockNumber > rollupStore.tips.getProvenBlockNumber(), Errors.Rollup__BlockAlreadyProven()); // Get the stored block data CompressedTempBlockLog storage blockLog = STFLib.getStorageTempBlockLog(_blockNumber); // Verify that the provided attestations match the stored hash bytes32 providedAttestationsHash = keccak256(abi.encode(_attestations)); - require( - providedAttestationsHash == blockLog.attestationsHash, Errors.Rollup__InvalidAttestations() - ); + require(providedAttestationsHash == blockLog.attestationsHash, Errors.Rollup__InvalidAttestations()); // Get the epoch for the block's slot to verify committee Epoch epoch = blockLog.slotNumber.decompress().epochFromSlot(); // Get and verify the committee commitment - (bytes32 committeeCommitment, uint256 committeeSize) = - ValidatorSelectionLib.getCommitteeCommitmentAt(epoch); + (bytes32 committeeCommitment, uint256 committeeSize) = ValidatorSelectionLib.getCommitteeCommitmentAt(epoch); bytes32 providedCommitteeCommitment = keccak256(abi.encode(_committee)); require( committeeCommitment == providedCommitteeCommitment, - Errors.ValidatorSelection__InvalidCommitteeCommitment( - providedCommitteeCommitment, committeeCommitment - ) + Errors.ValidatorSelection__InvalidCommitteeCommitment(providedCommitteeCommitment, committeeCommitment) ); // Get the digest of the payload that was signed by the committee diff --git a/l1-contracts/src/core/libraries/rollup/ProposeLib.sol b/l1-contracts/src/core/libraries/rollup/ProposeLib.sol index e34d95da2f7c..7ece3402e62c 100644 --- a/l1-contracts/src/core/libraries/rollup/ProposeLib.sol +++ b/l1-contracts/src/core/libraries/rollup/ProposeLib.sol @@ -2,9 +2,7 @@ // Copyright 2024 Aztec Labs. pragma solidity >=0.8.27; -import { - RollupStore, IRollupCore, BlockHeaderValidationFlags -} from "@aztec/core/interfaces/IRollup.sol"; +import {RollupStore, IRollupCore, BlockHeaderValidationFlags} from "@aztec/core/interfaces/IRollup.sol"; import {TempBlockLog} from "@aztec/core/libraries/compressed-data/BlockLog.sol"; import {FeeHeader} from "@aztec/core/libraries/compressed-data/fees/FeeStructs.sol"; import {ChainTipsLib, CompressedChainTips} from "@aztec/core/libraries/compressed-data/Tips.sol"; @@ -13,9 +11,7 @@ import {OracleInput, FeeLib, ManaBaseFeeComponents} from "@aztec/core/libraries/ import {ValidatorSelectionLib} from "@aztec/core/libraries/rollup/ValidatorSelectionLib.sol"; import {Timestamp, Slot, Epoch, TimeLib} from "@aztec/core/libraries/TimeLib.sol"; import {CompressedSlot, CompressedTimeMath} from "@aztec/shared/libraries/CompressedTimeMath.sol"; -import { - SignatureDomainSeparator, CommitteeAttestations -} from "@aztec/shared/libraries/SignatureLib.sol"; +import {SignatureDomainSeparator, CommitteeAttestations} from "@aztec/shared/libraries/SignatureLib.sol"; import {BlobLib} from "./BlobLib.sol"; import {ProposedHeader, ProposedHeaderLib, StateReference} from "./ProposedHeaderLib.sol"; import {STFLib} from "./STFLib.sol"; @@ -105,10 +101,10 @@ library ProposeLib { FeeLib.updateL1GasFeeOracle(); } - // TODO(#13430): The below blobsHashesCommitment known as blobsHash elsewhere in the code. The name is confusingly similar to blobCommitmentsHash, + // TODO(#13430): The below blobsHashesCommitment known as blobsHash elsewhere in the code. The name is confusingly + // similar to blobCommitmentsHash, // see comment in BlobLib.sol -> validateBlobs(). - (v.blobHashes, v.blobsHashesCommitment, v.blobCommitments) = - BlobLib.validateBlobs(_blobsInput, _checkBlob); + (v.blobHashes, v.blobsHashesCommitment, v.blobCommitments) = BlobLib.validateBlobs(_blobsInput, _checkBlob); ProposedHeader memory header = _args.header; v.headerHash = ProposedHeaderLib.hash(_args.header); @@ -141,9 +137,7 @@ library ProposeLib { }) ); - ValidatorSelectionLib.verifyProposer( - header.slotNumber, v.currentEpoch, _attestations, _signers, v.payloadDigest - ); + ValidatorSelectionLib.verifyProposer(header.slotNumber, v.currentEpoch, _attestations, _signers, v.payloadDigest); RollupStore storage rollupStore = STFLib.getStorage(); CompressedChainTips tips = rollupStore.tips; @@ -151,9 +145,9 @@ library ProposeLib { uint256 blockNumber = tips.getPendingBlockNumber() + 1; tips = tips.updatePendingBlockNumber(blockNumber); - // Blob commitments are collected and proven per root rollup proof (=> per epoch), so we need to know whether we are at the epoch start: - v.isFirstBlockOfEpoch = - v.currentEpoch > STFLib.getEpochForBlock(blockNumber - 1) || blockNumber == 1; + // Blob commitments are collected and proven per root rollup proof (=> per epoch), so we need to know whether we are + // at the epoch start: + v.isFirstBlockOfEpoch = v.currentEpoch > STFLib.getEpochForBlock(blockNumber - 1) || blockNumber == 1; bytes32 blobCommitmentsHash = BlobLib.calculateBlobCommitmentsHash( STFLib.getBlobCommitmentsHash(blockNumber - 1), v.blobCommitments, v.isFirstBlockOfEpoch ); @@ -228,16 +222,12 @@ library ProposeLib { require(slot == currentSlot, Errors.HeaderLib__InvalidSlotNumber(currentSlot, slot)); Timestamp timestamp = TimeLib.toTimestamp(slot); - require( - _args.header.timestamp == timestamp, - Errors.Rollup__InvalidTimestamp(timestamp, _args.header.timestamp) - ); + require(_args.header.timestamp == timestamp, Errors.Rollup__InvalidTimestamp(timestamp, _args.header.timestamp)); require(timestamp <= currentTime, Errors.Rollup__TimestampInFuture(currentTime, timestamp)); require( - _args.flags.ignoreDA - || _args.header.contentCommitment.blobsHash == _args.blobsHashesCommitment, + _args.flags.ignoreDA || _args.header.contentCommitment.blobsHash == _args.blobsHashesCommitment, Errors.Rollup__UnavailableTxs(_args.header.contentCommitment.blobsHash) ); diff --git a/l1-contracts/src/core/libraries/rollup/RewardLib.sol b/l1-contracts/src/core/libraries/rollup/RewardLib.sol index 7a67984c705d..404b99266b22 100644 --- a/l1-contracts/src/core/libraries/rollup/RewardLib.sol +++ b/l1-contracts/src/core/libraries/rollup/RewardLib.sol @@ -19,7 +19,7 @@ type Bps is uint32; library BpsLib { function mul(uint256 _a, Bps _b) internal pure returns (uint256) { - return _a * uint256(Bps.unwrap(_b)) / 10000; + return _a * uint256(Bps.unwrap(_b)) / 10_000; } } @@ -92,10 +92,7 @@ library RewardLib { return amount; } - function claimProverRewards(address _recipient, Epoch[] memory _epochs) - internal - returns (uint256) - { + function claimProverRewards(address _recipient, Epoch[] memory _epochs) internal returns (uint256) { Epoch currentEpoch = Timestamp.wrap(block.timestamp).epochFromTimestamp(); RollupStore storage rollupStore = STFLib.getStorage(); @@ -165,9 +162,8 @@ library RewardLib { IRewardDistributor distributor = rewardStorage.config.rewardDistributor; if (address(this) == distributor.canonicalRollup()) { - uint256 amountToClaim = Math.min( - blockRewardsDesired, rollupStore.config.feeAsset.balanceOf(address(distributor)) - ); + uint256 amountToClaim = + Math.min(blockRewardsDesired, rollupStore.config.feeAsset.balanceOf(address(distributor))); if (amountToClaim > 0) { distributor.claim(address(this), amountToClaim); @@ -176,8 +172,7 @@ library RewardLib { } } - uint256 sequencerShare = - BpsLib.mul(blockRewardsAvailable, rewardStorage.config.sequencerBps); + uint256 sequencerShare = BpsLib.mul(blockRewardsAvailable, rewardStorage.config.sequencerBps); v.sequencerBlockReward = sequencerShare / added; $er.rewards += (blockRewardsAvailable - sequencerShare).toUint128(); @@ -237,11 +232,7 @@ library RewardLib { return getStorage().epochRewards[_epoch].rewards; } - function getHasSubmitted(Epoch _epoch, uint256 _length, address _prover) - internal - view - returns (bool) - { + function getHasSubmitted(Epoch _epoch, uint256 _length, address _prover) internal view returns (bool) { return getStorage().epochRewards[_epoch].subEpoch[_length].shares[_prover] > 0; } @@ -253,11 +244,7 @@ library RewardLib { return getStorage().config.blockReward; } - function getSpecificProverRewardsForEpoch(Epoch _epoch, address _prover) - internal - view - returns (uint256) - { + function getSpecificProverRewardsForEpoch(Epoch _epoch, address _prover) internal view returns (uint256) { RewardStorage storage rewardStorage = getStorage(); if (rewardStorage.proverClaimed[_prover].get(Epoch.unwrap(_epoch))) { diff --git a/l1-contracts/src/core/libraries/rollup/STFLib.sol b/l1-contracts/src/core/libraries/rollup/STFLib.sol index 224483aa735e..3bc46ac21cf1 100644 --- a/l1-contracts/src/core/libraries/rollup/STFLib.sol +++ b/l1-contracts/src/core/libraries/rollup/STFLib.sol @@ -8,10 +8,7 @@ import { TempBlockLog, CompressedTempBlockLogLib } from "@aztec/core/libraries/compressed-data/BlockLog.sol"; -import { - CompressedFeeHeader, - FeeHeaderLib -} from "@aztec/core/libraries/compressed-data/fees/FeeStructs.sol"; +import {CompressedFeeHeader, FeeHeaderLib} from "@aztec/core/libraries/compressed-data/fees/FeeStructs.sol"; import {ChainTipsLib, CompressedChainTips} from "@aztec/core/libraries/compressed-data/Tips.sol"; import {Errors} from "@aztec/core/libraries/Errors.sol"; import {Timestamp, Slot, Epoch, TimeLib} from "@aztec/core/libraries/TimeLib.sol"; @@ -87,7 +84,8 @@ library STFLib { CompressedChainTips tips = rollupStore.tips; uint256 pending = tips.getPendingBlockNumber(); - // @note We are not deleting the blocks, but we are "winding back" the pendingTip to the last block that was proven. + // @note We are not deleting the blocks, but we are "winding back" the pendingTip to the last block that was + // proven. // We can do because any new block proposed will overwrite a previous block in the block log, // so no values should "survive". // People must therefore read the chain using the pendingTip as a boundary. @@ -130,11 +128,7 @@ library STFLib { return getStorage().tempBlockLogs[_blockNumber % size].decompress(); } - function getStorageTempBlockLog(uint256 _blockNumber) - internal - view - returns (CompressedTempBlockLog storage) - { + function getStorageTempBlockLog(uint256 _blockNumber) internal view returns (CompressedTempBlockLog storage) { (, uint256 size) = innerIsStale(_blockNumber, true); return getStorage().tempBlockLogs[_blockNumber % size]; } @@ -162,8 +156,7 @@ library STFLib { function getEffectivePendingBlockNumber(Timestamp _timestamp) internal view returns (uint256) { RollupStore storage rollupStore = STFLib.getStorage(); CompressedChainTips tips = rollupStore.tips; - return - STFLib.canPruneAtTime(_timestamp) ? tips.getProvenBlockNumber() : tips.getPendingBlockNumber(); + return STFLib.canPruneAtTime(_timestamp) ? tips.getProvenBlockNumber() : tips.getPendingBlockNumber(); } function getEpochForBlock(uint256 _blockNumber) internal view returns (Epoch) { diff --git a/l1-contracts/src/core/libraries/rollup/StakingLib.sol b/l1-contracts/src/core/libraries/rollup/StakingLib.sol index a2c3f9da9f6a..93eff72ea623 100644 --- a/l1-contracts/src/core/libraries/rollup/StakingLib.sol +++ b/l1-contracts/src/core/libraries/rollup/StakingLib.sol @@ -16,9 +16,7 @@ import {GSE, AttesterConfig} from "@aztec/governance/GSE.sol"; import {Proposal} from "@aztec/governance/interfaces/IGovernance.sol"; import {ProposalLib} from "@aztec/governance/libraries/ProposalLib.sol"; import {GovernanceProposer} from "@aztec/governance/proposer/GovernanceProposer.sol"; -import { - CompressedTimeMath, CompressedTimestamp -} from "@aztec/shared/libraries/CompressedTimeMath.sol"; +import {CompressedTimeMath, CompressedTimestamp} from "@aztec/shared/libraries/CompressedTimeMath.sol"; import {IERC20} from "@oz/token/ERC20/IERC20.sol"; import {SafeERC20} from "@oz/token/ERC20/utils/SafeERC20.sol"; import {Math} from "@oz/utils/math/Math.sol"; @@ -115,13 +113,10 @@ library StakingLib { require(address(this) == govProposer.getInstance(), Errors.Staking__NotCanonical(address(this))); address proposalProposer = govProposer.getProposalProposer(_proposalId); require( - address(this) == proposalProposer, - Errors.Staking__NotOurProposal(_proposalId, address(this), proposalProposer) + address(this) == proposalProposer, Errors.Staking__NotOurProposal(_proposalId, address(this), proposalProposer) ); Proposal memory proposal = gov.getProposal(_proposalId); - require( - proposal.proposer == address(govProposer), Errors.Staking__IncorrectGovProposer(_proposalId) - ); + require(proposal.proposer == address(govProposer), Errors.Staking__IncorrectGovProposer(_proposalId)); Timestamp ts = proposal.pendingThroughMemory(); @@ -171,10 +166,7 @@ library StakingLib { Exit storage exit = store.exits[_attester]; if (exit.exists) { - require( - exit.exitableAt > Timestamp.wrap(block.timestamp), - Errors.Staking__CannotSlashExitedStake(_attester) - ); + require(exit.exitableAt > Timestamp.wrap(block.timestamp), Errors.Staking__CannotSlashExitedStake(_attester)); // If the slash amount is greater than the exit amount, bound it to the exit amount uint256 slashAmount = Math.min(_amount, exit.amount); @@ -197,8 +189,7 @@ library StakingLib { // If the slash amount is greater than the effective balance, bound it to the effective balance uint256 slashAmount = Math.min(_amount, effectiveBalance); - (uint256 amountWithdrawn, bool isRemoved, uint256 withdrawalId) = - store.gse.withdraw(_attester, slashAmount); + (uint256 amountWithdrawn, bool isRemoved, uint256 withdrawalId) = store.gse.withdraw(_attester, slashAmount); uint256 toUser = amountWithdrawn - slashAmount; if (isRemoved && toUser > 0) { @@ -219,8 +210,7 @@ library StakingLib { function deposit(address _attester, address _withdrawer, bool _moveWithLatestRollup) internal { require( - _attester != address(0) && _withdrawer != address(0), - Errors.Staking__InvalidDeposit(_attester, _withdrawer) + _attester != address(0) && _withdrawer != address(0), Errors.Staking__InvalidDeposit(_attester, _withdrawer) ); StakingStorage storage store = getStorage(); // We don't allow deposits, if we are currently exiting. @@ -239,9 +229,7 @@ library StakingLib { Epoch currentEpoch = TimeLib.epochFromTimestamp(Timestamp.wrap(block.timestamp)); StakingStorage storage store = getStorage(); - require( - store.nextFlushableEpoch <= currentEpoch, Errors.Staking__QueueAlreadyFlushed(currentEpoch) - ); + require(store.nextFlushableEpoch <= currentEpoch, Errors.Staking__QueueAlreadyFlushed(currentEpoch)); store.nextFlushableEpoch = currentEpoch + Epoch.wrap(1); uint256 amount = store.gse.ACTIVATION_THRESHOLD(); @@ -251,9 +239,7 @@ library StakingLib { for (uint256 i = 0; i < numToDequeue; i++) { DepositArgs memory args = store.entryQueue.dequeue(); (bool success, bytes memory data) = address(store.gse).call( - abi.encodeWithSelector( - IStakingCore.deposit.selector, args.attester, args.withdrawer, args.moveWithLatestRollup - ) + abi.encodeWithSelector(IStakingCore.deposit.selector, args.attester, args.withdrawer, args.moveWithLatestRollup) ); if (success) { emit IStakingCore.Deposit(args.attester, args.withdrawer, amount); @@ -296,8 +282,7 @@ library StakingLib { require(msg.sender == withdrawer, Errors.Staking__NotWithdrawer(withdrawer, msg.sender)); uint256 amount = store.gse.effectiveBalanceOf(address(this), _attester); - (uint256 actualAmount, bool removed, uint256 withdrawalId) = - store.gse.withdraw(_attester, amount); + (uint256 actualAmount, bool removed, uint256 withdrawalId) = store.gse.withdraw(_attester, amount); require(removed, Errors.Staking__WithdrawFailed(_attester)); store.exits[_attester] = Exit({ @@ -348,16 +333,10 @@ library StakingLib { } function getAttesterAtIndex(uint256 _index) internal view returns (address) { - return getStorage().gse.getAttesterFromIndexAtTime( - address(this), _index, Timestamp.wrap(block.timestamp) - ); + return getStorage().gse.getAttesterFromIndexAtTime(address(this), _index, Timestamp.wrap(block.timestamp)); } - function getAttesterFromIndexAtTime(uint256 _index, Timestamp _timestamp) - internal - view - returns (address) - { + function getAttesterFromIndexAtTime(uint256 _index, Timestamp _timestamp) internal view returns (address) { return getStorage().gse.getAttesterFromIndexAtTime(address(this), _index, _timestamp); } diff --git a/l1-contracts/src/core/libraries/rollup/ValidatorSelectionLib.sol b/l1-contracts/src/core/libraries/rollup/ValidatorSelectionLib.sol index a716dafb26c7..8e0fb9f2fe6c 100644 --- a/l1-contracts/src/core/libraries/rollup/ValidatorSelectionLib.sol +++ b/l1-contracts/src/core/libraries/rollup/ValidatorSelectionLib.sol @@ -9,9 +9,7 @@ import {Errors} from "@aztec/core/libraries/Errors.sol"; import {StakingLib} from "@aztec/core/libraries/rollup/StakingLib.sol"; import {STFLib} from "@aztec/core/libraries/rollup/STFLib.sol"; import {Timestamp, Slot, Epoch, TimeLib} from "@aztec/core/libraries/TimeLib.sol"; -import { - SignatureLib, Signature, CommitteeAttestations -} from "@aztec/shared/libraries/SignatureLib.sol"; +import {SignatureLib, Signature, CommitteeAttestations} from "@aztec/shared/libraries/SignatureLib.sol"; import {ECDSA} from "@oz/utils/cryptography/ECDSA.sol"; import {MessageHashUtils} from "@oz/utils/cryptography/MessageHashUtils.sol"; import {SafeCast} from "@oz/utils/math/SafeCast.sol"; @@ -42,8 +40,7 @@ library ValidatorSelectionLib { address[] reconstructedCommittee; } - bytes32 private constant VALIDATOR_SELECTION_STORAGE_POSITION = - keccak256("aztec.validator_selection.storage"); + bytes32 private constant VALIDATOR_SELECTION_STORAGE_POSITION = keccak256("aztec.validator_selection.storage"); // Namespace for cached proposer computations string private constant PROPOSER_NAMESPACE = "aztec.validator_selection.transient.proposer"; @@ -111,15 +108,12 @@ library ValidatorSelectionLib { } // Reconstruct the committee from the attestations and signers - address[] memory committee = - _attestations.reconstructCommitteeFromSigners(_signers, committeeSize); + address[] memory committee = _attestations.reconstructCommitteeFromSigners(_signers, committeeSize); // Check it matches the expected one bytes32 reconstructedCommitment = computeCommitteeCommitment(committee); if (reconstructedCommitment != committeeCommitment) { - revert Errors.ValidatorSelection__InvalidCommitteeCommitment( - reconstructedCommitment, committeeCommitment - ); + revert Errors.ValidatorSelection__InvalidCommitteeCommitment(reconstructedCommitment, committeeCommitment); } // Get the proposer from the committee based on the epoch, slot, and sample seed @@ -162,8 +156,7 @@ library ValidatorSelectionLib { CommitteeAttestations memory _attestations, bytes32 _digest ) internal { - (bytes32 committeeCommitment, uint256 targetCommitteeSize) = - getCommitteeCommitmentAt(_epochNumber); + (bytes32 committeeCommitment, uint256 targetCommitteeSize) = getCommitteeCommitmentAt(_epochNumber); // If the rollup is *deployed* with a target committee size of 0, we skip the validation. // Note: This generally only happens in test setups; In production, the target committee is non-zero, @@ -173,9 +166,7 @@ library ValidatorSelectionLib { } VerifyStack memory stack = VerifyStack({ - proposerIndex: computeProposerIndex( - _epochNumber, _slot, getSampleSeed(_epochNumber), targetCommitteeSize - ), + proposerIndex: computeProposerIndex(_epochNumber, _slot, getSampleSeed(_epochNumber), targetCommitteeSize), needed: (targetCommitteeSize << 1) / 3 + 1, // targetCommitteeSize * 2 / 3 + 1, but cheaper index: 0, signaturesRecovered: 0, @@ -231,19 +222,14 @@ library ValidatorSelectionLib { // Check the committee commitment bytes32 reconstructedCommitment = computeCommitteeCommitment(stack.reconstructedCommittee); if (reconstructedCommitment != committeeCommitment) { - revert Errors.ValidatorSelection__InvalidCommitteeCommitment( - reconstructedCommitment, committeeCommitment - ); + revert Errors.ValidatorSelection__InvalidCommitteeCommitment(reconstructedCommitment, committeeCommitment); } setCachedProposer(_slot, proposer, stack.proposerIndex); } function setCachedProposer(Slot _slot, address _proposer, uint256 _proposerIndex) internal { - require( - _proposerIndex <= type(uint96).max, - Errors.ValidatorSelection__ProposerIndexTooLarge(_proposerIndex) - ); + require(_proposerIndex <= type(uint96).max, Errors.ValidatorSelection__ProposerIndexTooLarge(_proposerIndex)); bytes32 packed = bytes32(uint256(uint160(_proposer))) | (bytes32(_proposerIndex) << 160); PROPOSER_NAMESPACE.erc7201Slot().deriveMapping(Slot.unwrap(_slot)).asBytes32().tstore(packed); } @@ -263,10 +249,7 @@ library ValidatorSelectionLib { return (address(0), 0); } uint256 proposerIndex = computeProposerIndex(epochNumber, _slot, sampleSeed, committeeSize); - return ( - StakingLib.getAttesterFromIndexAtTime(indices[proposerIndex], Timestamp.wrap(ts)), - proposerIndex - ); + return (StakingLib.getAttesterFromIndexAtTime(indices[proposerIndex], Timestamp.wrap(ts)), proposerIndex); } /** @@ -311,8 +294,7 @@ library ValidatorSelectionLib { committeeCommitment = store.committeeCommitments[_epochNumber]; if (committeeCommitment == 0) { // If no committee has been stored, then we need to setup the epoch - committeeCommitment = - computeCommitteeCommitment(sampleValidators(_epochNumber, getSampleSeed(_epochNumber))); + committeeCommitment = computeCommitteeCommitment(sampleValidators(_epochNumber, getSampleSeed(_epochNumber))); } return (committeeCommitment, store.targetCommitteeSize); @@ -337,7 +319,8 @@ library ValidatorSelectionLib { uint32 epoch = Epoch.unwrap(_epoch).toUint32(); // Check if the latest checkpoint is for the next epoch - // It should be impossible that zero epoch snapshots exist, as in the genesis state we push the first sample seed into the store + // It should be impossible that zero epoch snapshots exist, as in the genesis state we push the first sample seed + // into the store (, uint32 mostRecentSeedEpoch,) = store.seeds.latestCheckpoint(); // If the sample seed for the next epoch is already set, we can skip the computation @@ -345,7 +328,8 @@ library ValidatorSelectionLib { return; } - // If the most recently stored seed is less than the epoch we are querying, then we need to compute it's seed for later use + // If the most recently stored seed is less than the epoch we are querying, then we need to compute it's seed for + // later use if (mostRecentSeedEpoch < epoch) { // Compute the sample seed for the next epoch uint224 nextSeed = computeNextSeed(_epoch); @@ -353,10 +337,7 @@ library ValidatorSelectionLib { } } - function canProposeAtTime(Timestamp _ts, bytes32 _archive, address _who) - internal - returns (Slot, uint256) - { + function canProposeAtTime(Timestamp _ts, bytes32 _archive, address _who) internal returns (Slot, uint256) { Slot slot = _ts.slotFromTimestamp(); RollupStore storage rollupStore = STFLib.getStorage(); @@ -376,13 +357,8 @@ library ValidatorSelectionLib { return (slot, pendingBlockNumber + 1); } - function getCachedProposer(Slot _slot) - internal - view - returns (address proposer, uint256 proposerIndex) - { - bytes32 packed = - PROPOSER_NAMESPACE.erc7201Slot().deriveMapping(Slot.unwrap(_slot)).asBytes32().tload(); + function getCachedProposer(Slot _slot) internal view returns (address proposer, uint256 proposerIndex) { + bytes32 packed = PROPOSER_NAMESPACE.erc7201Slot().deriveMapping(Slot.unwrap(_slot)).asBytes32().tload(); // Extract address from lower 160 bits proposer = address(uint160(uint256(packed))); // Extract uint96 from upper 96 bits @@ -396,8 +372,7 @@ library ValidatorSelectionLib { // as we "start" time $t$. We then shift that back by an entire L2 epoch to guarantee // we are not hit by last-minute changes or L1 reorgs when syncing validators from our clients. - return Timestamp.unwrap(_epoch.toTimestamp()).toUint32() - - uint32(TimeLib.getEpochDurationInSeconds()) - 1; + return Timestamp.unwrap(_epoch.toTimestamp()).toUint32() - uint32(TimeLib.getEpochDurationInSeconds()) - 1; } /** @@ -432,11 +407,7 @@ library ValidatorSelectionLib { * * @return The index of the proposer */ - function computeProposerIndex(Epoch _epoch, Slot _slot, uint256 _seed, uint256 _size) - internal - pure - returns (uint256) - { + function computeProposerIndex(Epoch _epoch, Slot _slot, uint256 _seed, uint256 _size) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_epoch, _slot, _seed))) % _size; } @@ -448,10 +419,7 @@ library ValidatorSelectionLib { * * @return The sample time and the indices of the validators for the given epoch */ - function sampleValidatorsIndices(Epoch _epoch, uint224 _seed) - private - returns (uint32, uint256[] memory) - { + function sampleValidatorsIndices(Epoch _epoch, uint224 _seed) private returns (uint32, uint256[] memory) { ValidatorSelectionStorage storage store = getStorage(); uint32 ts = epochToSampleTime(_epoch); uint256 validatorSetSize = StakingLib.getAttesterCountAtTime(Timestamp.wrap(ts)); diff --git a/l1-contracts/src/core/messagebridge/FeeJuicePortal.sol b/l1-contracts/src/core/messagebridge/FeeJuicePortal.sol index 93e00c0067fa..0bab84d30534 100644 --- a/l1-contracts/src/core/messagebridge/FeeJuicePortal.sol +++ b/l1-contracts/src/core/messagebridge/FeeJuicePortal.sol @@ -33,7 +33,8 @@ contract FeeJuicePortal is IFeeJuicePortal { * @notice Deposit funds into the portal and adds an L2 message which can only be consumed publicly on Aztec * @param _to - The aztec address of the recipient * @param _amount - The amount to deposit - * @param _secretHash - The hash of the secret consumable message. The hash should be 254 bits (so it can fit in a Field element) + * @param _secretHash - The hash of the secret consumable message. The hash should be 254 bits (so it can fit in a + * Field element) * @return - The key of the entry in the Inbox and its leaf index */ function depositToAztecPublic(bytes32 _to, uint256 _amount, bytes32 _secretHash) @@ -45,8 +46,7 @@ contract FeeJuicePortal is IFeeJuicePortal { DataStructures.L2Actor memory actor = DataStructures.L2Actor(L2_TOKEN_ADDRESS, VERSION); // Hash the message content to be reconstructed in the receiving contract - bytes32 contentHash = - Hash.sha256ToField(abi.encodeWithSignature("claim(bytes32,uint256)", _to, _amount)); + bytes32 contentHash = Hash.sha256ToField(abi.encodeWithSignature("claim(bytes32,uint256)", _to, _amount)); // Hold the tokens in the portal UNDERLYING.safeTransferFrom(msg.sender, address(this), _amount); diff --git a/l1-contracts/src/core/messagebridge/Inbox.sol b/l1-contracts/src/core/messagebridge/Inbox.sol index 234828583922..922f1864d520 100644 --- a/l1-contracts/src/core/messagebridge/Inbox.sol +++ b/l1-contracts/src/core/messagebridge/Inbox.sol @@ -44,17 +44,13 @@ contract Inbox is IInbox { HEIGHT = _height; SIZE = 2 ** _height; - state = InboxState({ - rollingHash: 0, - totalMessagesInserted: 0, - inProgress: uint64(Constants.INITIAL_L2_BLOCK_NUM) + 1 - }); + state = + InboxState({rollingHash: 0, totalMessagesInserted: 0, inProgress: uint64(Constants.INITIAL_L2_BLOCK_NUM) + 1}); forest.initialize(_height); EMPTY_ROOT = trees[uint64(Constants.INITIAL_L2_BLOCK_NUM) + 1].root(forest, HEIGHT, SIZE); - FEE_ASSET_PORTAL = - address(new FeeJuicePortal(IRollup(_rollup), _feeAsset, IInbox(this), VERSION)); + FEE_ASSET_PORTAL = address(new FeeJuicePortal(IRollup(_rollup), _feeAsset, IInbox(this), VERSION)); } /** @@ -64,27 +60,20 @@ contract Inbox is IInbox { * * @param _recipient - The recipient of the message * @param _content - The content of the message (application specific) - * @param _secretHash - The secret hash of the message (make it possible to hide when a specific message is consumed on L2) + * @param _secretHash - The secret hash of the message (make it possible to hide when a specific message is consumed + * on L2) * * @return Hash of the sent message and its leaf index in the tree. */ - function sendL2Message( - DataStructures.L2Actor memory _recipient, - bytes32 _content, - bytes32 _secretHash - ) external override(IInbox) returns (bytes32, uint256) { - require( - uint256(_recipient.actor) <= Constants.MAX_FIELD_VALUE, - Errors.Inbox__ActorTooLarge(_recipient.actor) - ); - require( - _recipient.version == VERSION, Errors.Inbox__VersionMismatch(_recipient.version, VERSION) - ); + function sendL2Message(DataStructures.L2Actor memory _recipient, bytes32 _content, bytes32 _secretHash) + external + override(IInbox) + returns (bytes32, uint256) + { + require(uint256(_recipient.actor) <= Constants.MAX_FIELD_VALUE, Errors.Inbox__ActorTooLarge(_recipient.actor)); + require(_recipient.version == VERSION, Errors.Inbox__VersionMismatch(_recipient.version, VERSION)); require(uint256(_content) <= Constants.MAX_FIELD_VALUE, Errors.Inbox__ContentTooLarge(_content)); - require( - uint256(_secretHash) <= Constants.MAX_FIELD_VALUE, - Errors.Inbox__SecretHashTooLarge(_secretHash) - ); + require(uint256(_secretHash) <= Constants.MAX_FIELD_VALUE, Errors.Inbox__SecretHashTooLarge(_secretHash)); require(IRollup(ROLLUP).getManaTarget() > 0, Errors.Inbox__Ignition()); // Is this the best way to read a packed struct into local variables in a single SLOAD @@ -109,8 +98,7 @@ contract Inbox is IInbox { // If the sender is the fee asset portal, we use a magic address to simpler have it initialized at genesis. // We assume that no-one will know the private key for this address and that the precompile won't change to // make calls into arbitrary contracts. - address senderAddress = - msg.sender == FEE_ASSET_PORTAL ? address(uint160(Constants.FEE_JUICE_ADDRESS)) : msg.sender; + address senderAddress = msg.sender == FEE_ASSET_PORTAL ? address(uint160(Constants.FEE_JUICE_ADDRESS)) : msg.sender; DataStructures.L1ToL2Msg memory message = DataStructures.L1ToL2Msg({ sender: DataStructures.L1Actor(senderAddress, block.chainid), diff --git a/l1-contracts/src/core/messagebridge/Outbox.sol b/l1-contracts/src/core/messagebridge/Outbox.sol index 3833486ba1a1..8deeedcf7a8f 100644 --- a/l1-contracts/src/core/messagebridge/Outbox.sol +++ b/l1-contracts/src/core/messagebridge/Outbox.sol @@ -71,17 +71,11 @@ contract Outbox is IOutbox { uint256 _leafIndex, bytes32[] calldata _path ) external override(IOutbox) { - require( - _l2BlockNumber <= ROLLUP.getProvenBlockNumber(), Errors.Outbox__BlockNotProven(_l2BlockNumber) - ); - require( - _message.sender.version == VERSION, - Errors.Outbox__VersionMismatch(_message.sender.version, VERSION) - ); + require(_l2BlockNumber <= ROLLUP.getProvenBlockNumber(), Errors.Outbox__BlockNotProven(_l2BlockNumber)); + require(_message.sender.version == VERSION, Errors.Outbox__VersionMismatch(_message.sender.version, VERSION)); require( - msg.sender == _message.recipient.actor, - Errors.Outbox__InvalidRecipient(_message.recipient.actor, msg.sender) + msg.sender == _message.recipient.actor, Errors.Outbox__InvalidRecipient(_message.recipient.actor, msg.sender) ); require(block.chainid == _message.recipient.chainId, Errors.Outbox__InvalidChainId()); @@ -94,9 +88,7 @@ contract Outbox is IOutbox { uint256 leafId = (1 << _path.length) + _leafIndex; - require( - !rootData.nullified.get(leafId), Errors.Outbox__AlreadyNullified(_l2BlockNumber, leafId) - ); + require(!rootData.nullified.get(leafId), Errors.Outbox__AlreadyNullified(_l2BlockNumber, leafId)); bytes32 messageHash = _message.sha256ToField(); diff --git a/l1-contracts/src/core/reward-boost/RewardBooster.sol b/l1-contracts/src/core/reward-boost/RewardBooster.sol index 381141e7e767..90ffc3d5589e 100644 --- a/l1-contracts/src/core/reward-boost/RewardBooster.sol +++ b/l1-contracts/src/core/reward-boost/RewardBooster.sol @@ -71,12 +71,7 @@ contract RewardBooster is IBooster { CONFIG_K = _config.k; } - function updateAndGetShares(address _prover) - external - override(IBoosterCore) - onlyRollup - returns (uint256) - { + function updateAndGetShares(address _prover) external override(IBoosterCore) onlyRollup returns (uint256) { Epoch currentEpoch = ROLLUP.getCurrentEpoch(); CompressedActivityScore storage store = activityScores[_prover]; @@ -105,12 +100,7 @@ contract RewardBooster is IBooster { return _toShares(getActivityScore(_prover).value); } - function getActivityScore(address _prover) - public - view - override(IBooster) - returns (ActivityScore memory) - { + function getActivityScore(address _prover) public view override(IBooster) returns (ActivityScore memory) { return _activityScoreAt(activityScores[_prover], ROLLUP.getCurrentEpoch()); } @@ -120,10 +110,8 @@ contract RewardBooster is IBooster { returns (ActivityScore memory) { uint256 decrease = (Epoch.unwrap(_epoch) - Epoch.unwrap(_score.time.decompress())) * 1e5; - return ActivityScore({ - value: decrease > uint256(_score.value) ? 0 : _score.value - decrease.toUint32(), - time: _epoch - }); + return + ActivityScore({value: decrease > uint256(_score.value) ? 0 : _score.value - decrease.toUint32(), time: _epoch}); } function _toShares(uint256 _value) internal view returns (uint256) { diff --git a/l1-contracts/src/core/slashing/Slasher.sol b/l1-contracts/src/core/slashing/Slasher.sol index 567d12476cea..cf0d80178faf 100644 --- a/l1-contracts/src/core/slashing/Slasher.sol +++ b/l1-contracts/src/core/slashing/Slasher.sol @@ -24,9 +24,8 @@ contract Slasher is ISlasher { uint256 _executionDelayInRounds, address _vetoer ) { - PROPOSER = new SlashingProposer( - msg.sender, this, _quorumSize, _roundSize, _lifetimeInRounds, _executionDelayInRounds - ); + PROPOSER = + new SlashingProposer(msg.sender, this, _quorumSize, _roundSize, _lifetimeInRounds, _executionDelayInRounds); VETOER = _vetoer; } @@ -37,9 +36,7 @@ contract Slasher is ISlasher { } function slash(IPayload _payload) external override(ISlasher) returns (bool) { - require( - msg.sender == address(PROPOSER), Slasher__CallerNotProposer(msg.sender, address(PROPOSER)) - ); + require(msg.sender == address(PROPOSER), Slasher__CallerNotProposer(msg.sender, address(PROPOSER))); require(!vetoedPayloads[address(_payload)], Slasher__PayloadVetoed(address(_payload))); diff --git a/l1-contracts/src/governance/GSE.sol b/l1-contracts/src/governance/GSE.sol index fed044f28e0c..997509554e11 100644 --- a/l1-contracts/src/governance/GSE.sol +++ b/l1-contracts/src/governance/GSE.sol @@ -5,13 +5,9 @@ pragma solidity >=0.8.27; import {Governance} from "@aztec/governance/Governance.sol"; import {Proposal} from "@aztec/governance/interfaces/IGovernance.sol"; import {IPayload} from "@aztec/governance/interfaces/IPayload.sol"; +import {AddressSnapshotLib, SnapshottedAddressSet} from "@aztec/governance/libraries/AddressSnapshotLib.sol"; import { - AddressSnapshotLib, - SnapshottedAddressSet -} from "@aztec/governance/libraries/AddressSnapshotLib.sol"; -import { - DepositDelegationLib, - DepositAndDelegationAccounting + DepositDelegationLib, DepositAndDelegationAccounting } from "@aztec/governance/libraries/DepositDelegationLib.sol"; import {Errors} from "@aztec/governance/libraries/Errors.sol"; import {ProposalLib} from "@aztec/governance/libraries/ProposalLib.sol"; @@ -59,37 +55,21 @@ interface IGSECore { interface IGSE is IGSECore { function getDelegatee(address _instance, address _attester) external view returns (address); function getVotingPower(address _attester) external view returns (uint256); - function getVotingPowerAt(address _attester, Timestamp _timestamp) - external - view - returns (uint256); + function getVotingPowerAt(address _attester, Timestamp _timestamp) external view returns (uint256); - function getWithdrawer(address _instance, address _attester) - external - view - returns (address, bool, address); + function getWithdrawer(address _instance, address _attester) external view returns (address, bool, address); function balanceOf(address _instance, address _attester) external view returns (uint256); function effectiveBalanceOf(address _instance, address _attester) external view returns (uint256); function supplyOf(address _instance) external view returns (uint256); function totalSupply() external view returns (uint256); - function getConfig(address _instance, address _attester) - external - view - returns (AttesterConfig memory); - function getAttesterCountAtTime(address _instance, Timestamp _timestamp) - external - view - returns (uint256); + function getConfig(address _instance, address _attester) external view returns (AttesterConfig memory); + function getAttesterCountAtTime(address _instance, Timestamp _timestamp) external view returns (uint256); - function getAttestersFromIndicesAtTime( - address _instance, - Timestamp _timestamp, - uint256[] memory _indices - ) external view returns (address[] memory); - function getAttestersAtTime(address _instance, Timestamp _timestamp) + function getAttestersFromIndicesAtTime(address _instance, Timestamp _timestamp, uint256[] memory _indices) external view returns (address[] memory); + function getAttestersAtTime(address _instance, Timestamp _timestamp) external view returns (address[] memory); function getAttesterFromIndexAtTime(address _instance, uint256 _index, Timestamp _timestamp) external view @@ -180,8 +160,7 @@ contract GSECore is IGSECore, Ownable { * NB: in a large way, the BONUS_INSTANCE_ADDRESS is the entire point of the GSE, * otherwise the rollups would've managed their own attesters/delegation/etc. */ - address public constant BONUS_INSTANCE_ADDRESS = - address(uint160(uint256(keccak256("bonus-instance")))); + address public constant BONUS_INSTANCE_ADDRESS = address(uint160(uint256(keccak256("bonus-instance")))); // The amount of ASSET needed to add an attester to the set uint256 public immutable ACTIVATION_THRESHOLD; @@ -190,7 +169,8 @@ contract GSECore is IGSECore, Ownable { // the attester will be ejected from the set. uint256 public immutable EJECTION_THRESHOLD; - // The asset used for sybil resistance and power in governance. Must match the ASSET in `Governance` to work as intended. + // The asset used for sybil resistance and power in governance. Must match the ASSET in `Governance` to work as + // intended. IERC20 public immutable ASSET; // The GSE's history of rollups. @@ -231,12 +211,9 @@ contract GSECore is IGSECore, Ownable { * @param _ejectionThreshold - The minimum amount of asset required to be in the set to be considered an attester. * If the balance falls below this threshold, the attester is ejected from the set. */ - constructor( - address __owner, - IERC20 _asset, - uint256 _activationThreshold, - uint256 _ejectionThreshold - ) Ownable(__owner) { + constructor(address __owner, IERC20 _asset, uint256 _activationThreshold, uint256 _ejectionThreshold) + Ownable(__owner) + { ASSET = _asset; ACTIVATION_THRESHOLD = _activationThreshold; EJECTION_THRESHOLD = _ejectionThreshold; @@ -305,14 +282,10 @@ contract GSECore is IGSECore, Ownable { bool isMsgSenderLatestRollup = getLatestRollup() == msg.sender; // If _moveWithLatestRollup is true, then msg.sender must be the latest rollup. - require( - !_moveWithLatestRollup || isMsgSenderLatestRollup, Errors.GSE__NotLatestRollup(msg.sender) - ); + require(!_moveWithLatestRollup || isMsgSenderLatestRollup, Errors.GSE__NotLatestRollup(msg.sender)); // Ensure that we are not already attesting on the rollup - require( - !isRegistered(msg.sender, _attester), Errors.GSE__AlreadyRegistered(msg.sender, _attester) - ); + require(!isRegistered(msg.sender, _attester), Errors.GSE__AlreadyRegistered(msg.sender, _attester)); // Ensure that if we are the latest rollup, we are not already attesting on the bonus instance. require( @@ -330,8 +303,7 @@ contract GSECore is IGSECore, Ownable { // Add the attester to the instance's checkpointed set of attesters. require( - instances[recipientInstance].attesters.add(_attester), - Errors.GSE__AlreadyRegistered(recipientInstance, _attester) + instances[recipientInstance].attesters.add(_attester), Errors.GSE__AlreadyRegistered(recipientInstance, _attester) ); instances[recipientInstance].configOf[_attester] = AttesterConfig({withdrawer: _withdrawer}); @@ -379,7 +351,8 @@ contract GSECore is IGSECore, Ownable { InstanceAttesterRegistry storage attesterRegistry = instances[msg.sender]; bool foundAttester = attesterRegistry.attesters.contains(_attester); - // If we haven't found the attester in the rollup instance, and we are latest rollup, go look in the "bonus" instance. + // If we haven't found the attester in the rollup instance, and we are latest rollup, go look in the "bonus" + // instance. if ( !foundAttester && getLatestRollup() == msg.sender && instances[BONUS_INSTANCE_ADDRESS].attesters.contains(_attester) @@ -463,11 +436,7 @@ contract GSECore is IGSECore, Ownable { * * @return The id of the proposal */ - function proposeWithLock(IPayload _payload, address _to) - external - override(IGSECore) - returns (uint256) - { + function proposeWithLock(IPayload _payload, address _to) external override(IGSECore) returns (uint256) { Governance gov = getGovernance(); uint256 amount = gov.getConfiguration().proposeConfig.lockAmount; @@ -499,10 +468,7 @@ contract GSECore is IGSECore, Ownable { * @param _attester - The address of the attester to delegate on behalf of * @param _delegatee - The delegatee that should receive the power */ - function delegate(address _instance, address _attester, address _delegatee) - external - override(IGSECore) - { + function delegate(address _instance, address _attester, address _delegatee) external override(IGSECore) { require(isRollupRegistered(_instance), Errors.GSE__InstanceDoesNotExist(_instance)); address withdrawer = instances[_instance].configOf[_attester].withdrawer; require(msg.sender == withdrawer, Errors.GSE__NotWithdrawer(withdrawer, msg.sender)); @@ -529,10 +495,7 @@ contract GSECore is IGSECore, Ownable { * @param _amount - The amount of voting power to use in the vote * In the gov, it is possible to do a vote with partial power */ - function voteWithBonus(uint256 _proposalId, uint256 _amount, bool _support) - external - override(IGSECore) - { + function voteWithBonus(uint256 _proposalId, uint256 _amount, bool _support) external override(IGSECore) { Timestamp ts = _pendingThrough(_proposalId); require(msg.sender == getLatestRollupAt(ts), Errors.GSE__NotLatestRollup(msg.sender)); _vote(BONUS_INSTANCE_ADDRESS, _proposalId, _amount, _support); @@ -550,12 +513,7 @@ contract GSECore is IGSECore, Ownable { * * @return True if the `_attester` is in the set of `_instance`, false otherwise */ - function isRegistered(address _instance, address _attester) - public - view - override(IGSECore) - returns (bool) - { + function isRegistered(address _instance, address _attester) public view override(IGSECore) returns (bool) { return instances[_instance].attesters.contains(_attester); } @@ -614,19 +572,11 @@ contract GSE is IGSE, GSECore { using Checkpoints for Checkpoints.Trace224; using DepositDelegationLib for DepositAndDelegationAccounting; - constructor( - address __owner, - IERC20 _asset, - uint256 _activationThreshold, - uint256 _ejectionThreshold - ) GSECore(__owner, _asset, _activationThreshold, _ejectionThreshold) {} + constructor(address __owner, IERC20 _asset, uint256 _activationThreshold, uint256 _ejectionThreshold) + GSECore(__owner, _asset, _activationThreshold, _ejectionThreshold) + {} - function getConfig(address _instance, address _attester) - external - view - override(IGSE) - returns (AttesterConfig memory) - { + function getConfig(address _instance, address _attester) external view override(IGSE) returns (AttesterConfig memory) { (InstanceAttesterRegistry storage attesterRegistry, bool attesterExists,) = _getInstanceStoreWithAttester(_instance, _attester); @@ -644,8 +594,7 @@ contract GSE is IGSE, GSECore { returns (address withdrawer, bool attesterExists, address instanceAddress) { InstanceAttesterRegistry storage attesterRegistry; - (attesterRegistry, attesterExists, instanceAddress) = - _getInstanceStoreWithAttester(_instance, _attester); + (attesterRegistry, attesterExists, instanceAddress) = _getInstanceStoreWithAttester(_instance, _attester); if (!attesterExists) { return (address(0), false, address(0)); @@ -654,12 +603,7 @@ contract GSE is IGSE, GSECore { return (attesterRegistry.configOf[_attester].withdrawer, true, instanceAddress); } - function balanceOf(address _instance, address _attester) - external - view - override(IGSE) - returns (uint256) - { + function balanceOf(address _instance, address _attester) external view override(IGSE) returns (uint256) { return delegation.getBalanceOf(_instance, _attester); } @@ -674,12 +618,7 @@ contract GSE is IGSE, GSECore { * * @return The effective balance of the attester at the instance */ - function effectiveBalanceOf(address _instance, address _attester) - external - view - override(IGSE) - returns (uint256) - { + function effectiveBalanceOf(address _instance, address _attester) external view override(IGSE) returns (uint256) { uint256 balance = delegation.getBalanceOf(_instance, _attester); if (getLatestRollup() == _instance) { balance += delegation.getBalanceOf(BONUS_INSTANCE_ADDRESS, _attester); @@ -695,12 +634,7 @@ contract GSE is IGSE, GSECore { return delegation.getSupply(); } - function getDelegatee(address _instance, address _attester) - external - view - override(IGSE) - returns (address) - { + function getDelegatee(address _instance, address _attester) external view override(IGSE) returns (address) { return delegation.getDelegatee(_instance, _attester); } @@ -731,11 +665,12 @@ contract GSE is IGSE, GSECore { return _getAddressFromIndicesAtTimestamp(_instance, indices, _timestamp); } - function getAttestersFromIndicesAtTime( - address _instance, - Timestamp _timestamp, - uint256[] memory _indices - ) external view override(IGSE) returns (address[] memory) { + function getAttestersFromIndicesAtTime(address _instance, Timestamp _timestamp, uint256[] memory _indices) + external + view + override(IGSE) + returns (address[] memory) + { return _getAddressFromIndicesAtTimestamp(_instance, _indices, _timestamp); } @@ -750,12 +685,7 @@ contract GSE is IGSE, GSECore { return _getAddressFromIndicesAtTimestamp(_instance, indices, _timestamp)[0]; } - function getPowerUsed(address _delegatee, uint256 _proposalId) - external - view - override(IGSE) - returns (uint256) - { + function getPowerUsed(address _delegatee, uint256 _proposalId) external view override(IGSE) returns (uint256) { return delegation.getPowerUsed(_delegatee, _proposalId); } @@ -763,12 +693,7 @@ contract GSE is IGSE, GSECore { return BONUS_INSTANCE_ADDRESS; } - function getVotingPowerAt(address _delegatee, Timestamp _timestamp) - public - view - override(IGSE) - returns (uint256) - { + function getVotingPowerAt(address _delegatee, Timestamp _timestamp) public view override(IGSE) returns (uint256) { return delegation.getVotingPowerAt(_delegatee, _timestamp); } @@ -781,12 +706,7 @@ contract GSE is IGSE, GSECore { * * @return The number of effective attesters at the instance at the time of `_timestamp` */ - function getAttesterCountAtTime(address _instance, Timestamp _timestamp) - public - view - override(IGSE) - returns (uint256) - { + function getAttesterCountAtTime(address _instance, Timestamp _timestamp) public view override(IGSE) returns (uint256) { InstanceAttesterRegistry storage store = instances[_instance]; uint32 timestamp = Timestamp.unwrap(_timestamp).toUint32(); @@ -809,11 +729,11 @@ contract GSE is IGSE, GSECore { * * @return The addresses of the attesters at the instance at the time of `_timestamp` */ - function _getAddressFromIndicesAtTimestamp( - address _instance, - uint256[] memory _indices, - Timestamp _timestamp - ) internal view returns (address[] memory) { + function _getAddressFromIndicesAtTimestamp(address _instance, uint256[] memory _indices, Timestamp _timestamp) + internal + view + returns (address[] memory) + { address[] memory attesters = new address[](_indices.length); // Note: This function could get called where _instance is the bonus instance. @@ -831,7 +751,8 @@ contract GSE is IGSE, GSECore { // When this is called from `getAttestersAtTime`, _indices.length is one more than the effective attester count. // And the returned array will be: - // [rollup attester 1, rollup attester 2, ..., rollup attester N, bonus attester 1, bonus attester 2, ..., bonus attester M] + // [rollup attester 1, rollup attester 2, ..., rollup attester N, bonus attester 1, bonus attester 2, ..., bonus + // attester M] for (uint256 i = 0; i < _indices.length; i++) { uint256 index = _indices[i]; require(index < totalSize, Errors.GSE__OutOfBounds(index, totalSize)); @@ -839,8 +760,7 @@ contract GSE is IGSE, GSECore { if (index < storeSize) { attesters[i] = instanceStore.attesters.unsafeGetRecentAddressFromIndexAtTimestamp(index, ts); } else if (isLatestRollup) { - attesters[i] = - bonusStore.attesters.unsafeGetRecentAddressFromIndexAtTimestamp(index - storeSize, ts); + attesters[i] = bonusStore.attesters.unsafeGetRecentAddressFromIndexAtTimestamp(index - storeSize, ts); } else { revert Errors.GSE__FatalError("SHOULD NEVER HAPPEN"); } diff --git a/l1-contracts/src/governance/GSEPayload.sol b/l1-contracts/src/governance/GSEPayload.sol index 265ae2d47df3..742ec6a8b378 100644 --- a/l1-contracts/src/governance/GSEPayload.sol +++ b/l1-contracts/src/governance/GSEPayload.sol @@ -61,10 +61,8 @@ contract GSEPayload is IProposerPayload { actions[i] = originalActions[i]; } - actions[originalActions.length] = IPayload.Action({ - target: address(this), - data: abi.encodeWithSelector(GSEPayload.amIValid.selector) - }); + actions[originalActions.length] = + IPayload.Action({target: address(this), data: abi.encodeWithSelector(GSEPayload.amIValid.selector)}); return actions; } @@ -84,10 +82,7 @@ contract GSEPayload is IProposerPayload { address bonusInstance = GSE.getBonusInstanceAddress(); uint256 effectiveSupplyOfLatestRollup = GSE.supplyOf(latestRollup) + GSE.supplyOf(bonusInstance); - require( - effectiveSupplyOfLatestRollup > totalSupply * 2 / 3, - Errors.GovernanceProposer__GSEPayloadInvalid() - ); + require(effectiveSupplyOfLatestRollup > totalSupply * 2 / 3, Errors.GovernanceProposer__GSEPayloadInvalid()); return true; } } diff --git a/l1-contracts/src/governance/Governance.sol b/l1-contracts/src/governance/Governance.sol index ad55ac8ec929..7e732df3d0f4 100644 --- a/l1-contracts/src/governance/Governance.sol +++ b/l1-contracts/src/governance/Governance.sol @@ -11,9 +11,7 @@ import { Withdrawal } from "@aztec/governance/interfaces/IGovernance.sol"; import {IPayload} from "@aztec/governance/interfaces/IPayload.sol"; -import { - Checkpoints, CheckpointedUintLib -} from "@aztec/governance/libraries/CheckpointedUintLib.sol"; +import {Checkpoints, CheckpointedUintLib} from "@aztec/governance/libraries/CheckpointedUintLib.sol"; import {ConfigurationLib} from "@aztec/governance/libraries/ConfigurationLib.sol"; import {Errors} from "@aztec/governance/libraries/Errors.sol"; import {ProposalLib, VoteTabulationReturn} from "@aztec/governance/libraries/ProposalLib.sol"; @@ -216,9 +214,7 @@ contract Governance is IGovernance { * Protects functions that allow the governance contract to modify its own state, via a proposal. */ modifier onlySelf() { - require( - msg.sender == address(this), Errors.Governance__CallerNotSelf(msg.sender, address(this)) - ); + require(msg.sender == address(this), Errors.Governance__CallerNotSelf(msg.sender, address(this))); _; } @@ -237,12 +233,7 @@ contract Governance is IGovernance { /** * @dev the initial _beneficiary is expected to be the GSE. */ - constructor( - IERC20 _asset, - address _governanceProposer, - address _beneficiary, - Configuration memory _configuration - ) { + constructor(IERC20 _asset, address _governanceProposer, address _beneficiary, Configuration memory _configuration) { ASSET = _asset; governanceProposer = _governanceProposer; @@ -288,14 +279,8 @@ contract Governance is IGovernance { * * @param _governanceProposer The new governance proposer. */ - function updateGovernanceProposer(address _governanceProposer) - external - override(IGovernance) - onlySelf - { - require( - _governanceProposer != address(this), Errors.Governance__GovernanceProposerCannotBeSelf() - ); + function updateGovernanceProposer(address _governanceProposer) external override(IGovernance) onlySelf { + require(_governanceProposer != address(this), Errors.Governance__GovernanceProposerCannotBeSelf()); governanceProposer = _governanceProposer; emit GovernanceProposerUpdated(_governanceProposer); } @@ -306,11 +291,7 @@ contract Governance is IGovernance { * * @dev all existing proposals will use the configuration they were created with. */ - function updateConfiguration(Configuration memory _configuration) - external - override(IGovernance) - onlySelf - { + function updateConfiguration(Configuration memory _configuration) external override(IGovernance) onlySelf { // This following MUST revert if the configuration is invalid _configuration.assertValid(); @@ -338,11 +319,7 @@ contract Governance is IGovernance { * @param _beneficiary The beneficiary to increase the power of. * @param _amount The amount of funds to deposit, which is converted to power 1:1. */ - function deposit(address _beneficiary, uint256 _amount) - external - override(IGovernance) - isDepositAllowed(_beneficiary) - { + function deposit(address _beneficiary, uint256 _amount) external override(IGovernance) isDepositAllowed(_beneficiary) { ASSET.safeTransferFrom(msg.sender, address(this), _amount); users[_beneficiary].add(_amount); total.add(_amount); @@ -360,11 +337,7 @@ contract Governance is IGovernance { * @param _amount The amount of power to reduce, and thus funds to withdraw. * @return The id of the withdrawal, passed to `finaliseWithdraw`. */ - function initiateWithdraw(address _to, uint256 _amount) - external - override(IGovernance) - returns (uint256) - { + function initiateWithdraw(address _to, uint256 _amount) external override(IGovernance) returns (uint256) { return _initiateWithdraw(msg.sender, _to, _amount, configuration.withdrawalDelay()); } @@ -381,9 +354,7 @@ contract Governance is IGovernance { require(!withdrawal.claimed, Errors.Governance__WithdrawalAlreadyClaimed()); require( Timestamp.wrap(block.timestamp) >= withdrawal.unlocksAt, - Errors.Governance__WithdrawalNotUnlockedYet( - Timestamp.wrap(block.timestamp), withdrawal.unlocksAt - ) + Errors.Governance__WithdrawalNotUnlockedYet(Timestamp.wrap(block.timestamp), withdrawal.unlocksAt) ); withdrawal.claimed = true; @@ -400,13 +371,13 @@ contract Governance is IGovernance { * Note that the `proposer` of the proposal is the *current* governanceProposer; if the governanceProposer * no longer matches the one stored in the proposal, the state of the proposal will be `Droppable`. * - * @param _proposal The IPayload address, which is a contract that contains the proposed actions to be executed by the governance. + * @param _proposal The IPayload address, which is a contract that contains the proposed actions to be executed by the + * governance. * @return The id of the proposal. */ function propose(IPayload _proposal) external override(IGovernance) returns (uint256) { require( - msg.sender == governanceProposer, - Errors.Governance__CallerNotGovernanceProposer(msg.sender, governanceProposer) + msg.sender == governanceProposer, Errors.Governance__CallerNotGovernanceProposer(msg.sender, governanceProposer) ); return _propose(_proposal, governanceProposer); } @@ -429,14 +400,8 @@ contract Governance is IGovernance { * `finaliseWithdraw`) * @return The id of the proposal */ - function proposeWithLock(IPayload _proposal, address _to) - external - override(IGovernance) - returns (uint256) - { - _initiateWithdraw( - msg.sender, _to, configuration.proposeConfig.lockAmount, configuration.proposeConfig.lockDelay - ); + function proposeWithLock(IPayload _proposal, address _to) external override(IGovernance) returns (uint256) { + _initiateWithdraw(msg.sender, _to, configuration.proposeConfig.lockAmount, configuration.proposeConfig.lockDelay); return _propose(_proposal, address(this)); } @@ -457,11 +422,7 @@ contract Governance is IGovernance { * @param _amount The amount of power to vote with, which must be less than the available power. * @param _support The support of the vote. */ - function vote(uint256 _proposalId, uint256 _amount, bool _support) - external - override(IGovernance) - returns (bool) - { + function vote(uint256 _proposalId, uint256 _amount, bool _support) external override(IGovernance) returns (bool) { ProposalState state = getProposalState(_proposalId); require(state == ProposalState.Active, Errors.Governance__ProposalNotActive()); @@ -471,10 +432,7 @@ contract Governance is IGovernance { Ballot storage userBallot = ballots[_proposalId][msg.sender]; uint256 availablePower = userPower - (userBallot.nay + userBallot.yea); - require( - _amount <= availablePower, - Errors.Governance__InsufficientPower(msg.sender, availablePower, _amount) - ); + require(_amount <= availablePower, Errors.Governance__InsufficientPower(msg.sender, availablePower, _amount)); Ballot storage summedBallot = proposals[_proposalId].summedBallot; if (_support) { @@ -534,10 +492,7 @@ contract Governance is IGovernance { function dropProposal(uint256 _proposalId) external override(IGovernance) returns (bool) { Proposal storage self = proposals[_proposalId]; require(self.cachedState != ProposalState.Dropped, Errors.Governance__ProposalAlreadyDropped()); - require( - getProposalState(_proposalId) == ProposalState.Droppable, - Errors.Governance__ProposalCannotBeDropped() - ); + require(getProposalState(_proposalId) == ProposalState.Droppable, Errors.Governance__ProposalCannotBeDropped()); self.cachedState = ProposalState.Dropped; return true; @@ -562,12 +517,7 @@ contract Governance is IGovernance { * @param _ts The timestamp to get the power at. * @return The power of the address at the given timestamp. */ - function powerAt(address _owner, Timestamp _ts) - external - view - override(IGovernance) - returns (uint256) - { + function powerAt(address _owner, Timestamp _ts) external view override(IGovernance) returns (uint256) { if (_ts == Timestamp.wrap(block.timestamp)) { return users[_owner].valueNow(); } @@ -599,12 +549,7 @@ contract Governance is IGovernance { * @param _beneficiary The address to check. * @return True if the address is permitted to hold power in Governance. */ - function isPermittedInGovernance(address _beneficiary) - external - view - override(IGovernance) - returns (bool) - { + function isPermittedInGovernance(address _beneficiary) external view override(IGovernance) returns (bool) { return depositControl.isAllowed[_beneficiary]; } @@ -621,21 +566,11 @@ contract Governance is IGovernance { return configuration; } - function getProposal(uint256 _proposalId) - external - view - override(IGovernance) - returns (Proposal memory) - { + function getProposal(uint256 _proposalId) external view override(IGovernance) returns (Proposal memory) { return proposals[_proposalId]; } - function getWithdrawal(uint256 _withdrawalId) - external - view - override(IGovernance) - returns (Withdrawal memory) - { + function getWithdrawal(uint256 _withdrawalId) external view override(IGovernance) returns (Withdrawal memory) { return withdrawals[_withdrawalId]; } @@ -680,12 +615,7 @@ contract Governance is IGovernance { * @param _proposalId The ID of the proposal to check * @return The current state of the proposal */ - function getProposalState(uint256 _proposalId) - public - view - override(IGovernance) - returns (ProposalState) - { + function getProposalState(uint256 _proposalId) public view override(IGovernance) returns (ProposalState) { require(_proposalId < proposalCount, Errors.Governance__ProposalDoesNotExists(_proposalId)); Proposal storage self = proposals[_proposalId]; @@ -742,21 +672,14 @@ contract Governance is IGovernance { * @param _delay The delay before the funds can be withdrawn. * @return The id of the withdrawal. */ - function _initiateWithdraw(address _from, address _to, uint256 _amount, Timestamp _delay) - internal - returns (uint256) - { + function _initiateWithdraw(address _from, address _to, uint256 _amount, Timestamp _delay) internal returns (uint256) { users[_from].sub(_amount); total.sub(_amount); uint256 withdrawalId = withdrawalCount++; - withdrawals[withdrawalId] = Withdrawal({ - amount: _amount, - unlocksAt: Timestamp.wrap(block.timestamp) + _delay, - recipient: _to, - claimed: false - }); + withdrawals[withdrawalId] = + Withdrawal({amount: _amount, unlocksAt: Timestamp.wrap(block.timestamp) + _delay, recipient: _to, claimed: false}); emit WithdrawInitiated(withdrawalId, _to, _amount); diff --git a/l1-contracts/src/governance/Registry.sol b/l1-contracts/src/governance/Registry.sol index e73c673cac3c..044e4ca5be5a 100644 --- a/l1-contracts/src/governance/Registry.sol +++ b/l1-contracts/src/governance/Registry.sol @@ -48,8 +48,7 @@ contract Registry is IRegistry, Ownable { * Then the owner is updated to Governance. */ constructor(address _owner, IERC20 _rewardAsset) Ownable(_owner) { - $.rewardDistributor = - IRewardDistributor(address(new RewardDistributor(_rewardAsset, IRegistry(address(this))))); + $.rewardDistributor = IRewardDistributor(address(new RewardDistributor(_rewardAsset, IRegistry(address(this))))); emit RewardDistributorUpdated(address($.rewardDistributor)); } @@ -60,8 +59,7 @@ contract Registry is IRegistry, Ownable { function addRollup(IHaveVersion _rollup) external override(IRegistry) onlyOwner { uint256 version = _rollup.getVersion(); require( - address($.versionToRollup[version]) == address(0), - Errors.Registry__RollupAlreadyRegistered(address(_rollup)) + address($.versionToRollup[version]) == address(0), Errors.Registry__RollupAlreadyRegistered(address(_rollup)) ); $.versionToRollup[version] = _rollup; $.versions.push(version); @@ -69,11 +67,7 @@ contract Registry is IRegistry, Ownable { emit CanonicalRollupUpdated(address(_rollup), version); } - function updateRewardDistributor(address _rewardDistributor) - external - override(IRegistry) - onlyOwner - { + function updateRewardDistributor(address _rewardDistributor) external override(IRegistry) onlyOwner { $.rewardDistributor = IRewardDistributor(_rewardDistributor); emit RewardDistributorUpdated(_rewardDistributor); } diff --git a/l1-contracts/src/governance/RewardDistributor.sol b/l1-contracts/src/governance/RewardDistributor.sol index dcedfda880e5..fc5c37bb313d 100644 --- a/l1-contracts/src/governance/RewardDistributor.sol +++ b/l1-contracts/src/governance/RewardDistributor.sol @@ -24,10 +24,7 @@ contract RewardDistributor is IRewardDistributor { } function claim(address _to, uint256 _amount) external override(IRewardDistributor) { - require( - msg.sender == canonicalRollup(), - Errors.RewardDistributor__InvalidCaller(msg.sender, canonicalRollup()) - ); + require(msg.sender == canonicalRollup(), Errors.RewardDistributor__InvalidCaller(msg.sender, canonicalRollup())); ASSET.safeTransfer(_to, _amount); } diff --git a/l1-contracts/src/governance/interfaces/IEmpire.sol b/l1-contracts/src/governance/interfaces/IEmpire.sol index 8aaa52122c00..71bb4b6c3dfb 100644 --- a/l1-contracts/src/governance/interfaces/IEmpire.sol +++ b/l1-contracts/src/governance/interfaces/IEmpire.sol @@ -24,10 +24,7 @@ interface IEmpire { function signalWithSig(IPayload _payload, Signature memory _sig) external returns (bool); function submitRoundWinner(uint256 _roundNumber) external returns (bool); - function signalCount(address _instance, uint256 _round, IPayload _payload) - external - view - returns (uint256); + function signalCount(address _instance, uint256 _round, IPayload _payload) external view returns (uint256); function computeRound(Slot _slot) external view returns (uint256); function getInstance() external view returns (address); } diff --git a/l1-contracts/src/governance/libraries/AddressSnapshotLib.sol b/l1-contracts/src/governance/libraries/AddressSnapshotLib.sol index 45736a72d48f..ad45f39f2632 100644 --- a/l1-contracts/src/governance/libraries/AddressSnapshotLib.sol +++ b/l1-contracts/src/governance/libraries/AddressSnapshotLib.sol @@ -38,7 +38,8 @@ error AddressSnapshotLib__AddressNotInSet(address addr); * * The SnapshottedAddressSet is maintained such that the you can take a timestamp, and from it: * 1. Get the `size` of the set at that timestamp - * 2. Query the first `size` indices in `indexToAddressHistory` at that timestamp to get a set of addresses of size `size` + * 2. Query the first `size` indices in `indexToAddressHistory` at that timestamp to get a set of addresses of size + * `size` */ library AddressSnapshotLib { using SafeCast for *; @@ -102,10 +103,7 @@ library AddressSnapshotLib { * @param _index The index of the validator to remove * @return bool True if the validator was removed, reverts otherwise */ - function _remove(SnapshottedAddressSet storage _self, uint224 _index, address _address) - internal - returns (bool) - { + function _remove(SnapshottedAddressSet storage _self, uint224 _index, address _address) internal returns (bool) { uint224 currentSize = _self.size.latest(); if (_index >= currentSize) { revert AddressSnapshotLib__IndexOutOfBounds(_index, currentSize); @@ -158,11 +156,11 @@ library AddressSnapshotLib { * @param _timestamp The timestamp to query * @return address The address at the given index and timestamp */ - function getAddressFromIndexAtTimestamp( - SnapshottedAddressSet storage _self, - uint256 _index, - uint32 _timestamp - ) internal view returns (address) { + function getAddressFromIndexAtTimestamp(SnapshottedAddressSet storage _self, uint256 _index, uint32 _timestamp) + internal + view + returns (address) + { uint256 size = lengthAtTimestamp(_self, _timestamp); require(_index < size, AddressSnapshotLib__IndexOutOfBounds(_index, size)); @@ -210,11 +208,7 @@ library AddressSnapshotLib { * * @dev Note, the values returned from this function are in flux if the timestamp is in the future. */ - function lengthAtTimestamp(SnapshottedAddressSet storage _self, uint32 _timestamp) - internal - view - returns (uint256) - { + function lengthAtTimestamp(SnapshottedAddressSet storage _self, uint32 _timestamp) internal view returns (uint256) { return _self.size.upperLookup(_timestamp); } @@ -259,11 +253,7 @@ library AddressSnapshotLib { return vals; } - function contains(SnapshottedAddressSet storage _self, address _address) - internal - view - returns (bool) - { + function contains(SnapshottedAddressSet storage _self, address _address) internal view returns (bool) { return _self.addressToCurrentIndex[_address].exists; } } diff --git a/l1-contracts/src/governance/libraries/CheckpointedUintLib.sol b/l1-contracts/src/governance/libraries/CheckpointedUintLib.sol index 1ca160b4340e..2a06f4db9530 100644 --- a/l1-contracts/src/governance/libraries/CheckpointedUintLib.sol +++ b/l1-contracts/src/governance/libraries/CheckpointedUintLib.sol @@ -26,10 +26,7 @@ library CheckpointedUintLib { * * @return - The current value and the new value */ - function add(Checkpoints.Trace224 storage _self, uint256 _amount) - internal - returns (uint256, uint256) - { + function add(Checkpoints.Trace224 storage _self, uint256 _amount) internal returns (uint256, uint256) { uint224 current = _self.latest(); if (_amount == 0) { return (current, current); @@ -46,19 +43,13 @@ library CheckpointedUintLib { * @param _amount - The amount to subtract * @return - The current value and the new value */ - function sub(Checkpoints.Trace224 storage _self, uint256 _amount) - internal - returns (uint256, uint256) - { + function sub(Checkpoints.Trace224 storage _self, uint256 _amount) internal returns (uint256, uint256) { uint224 current = _self.latest(); if (_amount == 0) { return (current, current); } uint224 amount = _amount.toUint224(); - require( - current >= amount, - Errors.Governance__CheckpointedUintLib__InsufficientValue(msg.sender, current, amount) - ); + require(current >= amount, Errors.Governance__CheckpointedUintLib__InsufficientValue(msg.sender, current, amount)); _self.push(block.timestamp.toUint32(), current - amount); return (current, current - amount); } @@ -84,14 +75,8 @@ library CheckpointedUintLib { * @param _time - The timestamp to get the value at * @return - The value at the given timestamp */ - function valueAt(Checkpoints.Trace224 storage _self, Timestamp _time) - internal - view - returns (uint256) - { - require( - _time < Timestamp.wrap(block.timestamp), Errors.Governance__CheckpointedUintLib__NotInPast() - ); + function valueAt(Checkpoints.Trace224 storage _self, Timestamp _time) internal view returns (uint256) { + require(_time < Timestamp.wrap(block.timestamp), Errors.Governance__CheckpointedUintLib__NotInPast()); return _self.upperLookupRecent(Timestamp.unwrap(_time).toUint32()); } } diff --git a/l1-contracts/src/governance/libraries/ConfigurationLib.sol b/l1-contracts/src/governance/libraries/ConfigurationLib.sol index b15d08e04959..072292451a3d 100644 --- a/l1-contracts/src/governance/libraries/ConfigurationLib.sol +++ b/l1-contracts/src/governance/libraries/ConfigurationLib.sol @@ -26,8 +26,7 @@ library ConfigurationLib { * The "small buffer" is somewhat arbitrarily set to the votingDelay / 5. */ function withdrawalDelay(Configuration storage _self) internal view returns (Timestamp) { - return Timestamp.wrap(Timestamp.unwrap(_self.votingDelay) / 5) + _self.votingDuration - + _self.executionDelay; + return Timestamp.wrap(Timestamp.unwrap(_self.votingDelay) / 5) + _self.votingDuration + _self.executionDelay; } /** @@ -44,61 +43,28 @@ library ConfigurationLib { Errors.Governance__ConfigurationLib__RequiredYeaMarginTooBig() ); - require( - _self.minimumVotes >= VOTES_LOWER, Errors.Governance__ConfigurationLib__InvalidMinimumVotes() - ); - require( - _self.proposeConfig.lockAmount >= VOTES_LOWER, - Errors.Governance__ConfigurationLib__LockAmountTooSmall() - ); + require(_self.minimumVotes >= VOTES_LOWER, Errors.Governance__ConfigurationLib__InvalidMinimumVotes()); + require(_self.proposeConfig.lockAmount >= VOTES_LOWER, Errors.Governance__ConfigurationLib__LockAmountTooSmall()); - // Beyond checking the bounds like this, it might be useful to ensure that the value is larger than the withdrawal delay - // this, can be useful if one want to ensure that the "locker" cannot himself vote in the proposal, but as it is unclear + // Beyond checking the bounds like this, it might be useful to ensure that the value is larger than the withdrawal + // delay + // this, can be useful if one want to ensure that the "locker" cannot himself vote in the proposal, but as it is + // unclear // if this is a useful property, it is not enforced. - require( - _self.proposeConfig.lockDelay >= TIME_LOWER, - Errors.Governance__ConfigurationLib__TimeTooSmall("LockDelay") - ); - require( - _self.proposeConfig.lockDelay <= TIME_UPPER, - Errors.Governance__ConfigurationLib__TimeTooBig("LockDelay") - ); + require(_self.proposeConfig.lockDelay >= TIME_LOWER, Errors.Governance__ConfigurationLib__TimeTooSmall("LockDelay")); + require(_self.proposeConfig.lockDelay <= TIME_UPPER, Errors.Governance__ConfigurationLib__TimeTooBig("LockDelay")); - require( - _self.votingDelay >= TIME_LOWER, - Errors.Governance__ConfigurationLib__TimeTooSmall("VotingDelay") - ); - require( - _self.votingDelay <= TIME_UPPER, - Errors.Governance__ConfigurationLib__TimeTooBig("VotingDelay") - ); + require(_self.votingDelay >= TIME_LOWER, Errors.Governance__ConfigurationLib__TimeTooSmall("VotingDelay")); + require(_self.votingDelay <= TIME_UPPER, Errors.Governance__ConfigurationLib__TimeTooBig("VotingDelay")); - require( - _self.votingDuration >= TIME_LOWER, - Errors.Governance__ConfigurationLib__TimeTooSmall("VotingDuration") - ); - require( - _self.votingDuration <= TIME_UPPER, - Errors.Governance__ConfigurationLib__TimeTooBig("VotingDuration") - ); + require(_self.votingDuration >= TIME_LOWER, Errors.Governance__ConfigurationLib__TimeTooSmall("VotingDuration")); + require(_self.votingDuration <= TIME_UPPER, Errors.Governance__ConfigurationLib__TimeTooBig("VotingDuration")); - require( - _self.executionDelay >= TIME_LOWER, - Errors.Governance__ConfigurationLib__TimeTooSmall("ExecutionDelay") - ); - require( - _self.executionDelay <= TIME_UPPER, - Errors.Governance__ConfigurationLib__TimeTooBig("ExecutionDelay") - ); + require(_self.executionDelay >= TIME_LOWER, Errors.Governance__ConfigurationLib__TimeTooSmall("ExecutionDelay")); + require(_self.executionDelay <= TIME_UPPER, Errors.Governance__ConfigurationLib__TimeTooBig("ExecutionDelay")); - require( - _self.gracePeriod >= TIME_LOWER, - Errors.Governance__ConfigurationLib__TimeTooSmall("GracePeriod") - ); - require( - _self.gracePeriod <= TIME_UPPER, - Errors.Governance__ConfigurationLib__TimeTooBig("GracePeriod") - ); + require(_self.gracePeriod >= TIME_LOWER, Errors.Governance__ConfigurationLib__TimeTooSmall("GracePeriod")); + require(_self.gracePeriod <= TIME_UPPER, Errors.Governance__ConfigurationLib__TimeTooBig("GracePeriod")); return true; } diff --git a/l1-contracts/src/governance/libraries/DepositDelegationLib.sol b/l1-contracts/src/governance/libraries/DepositDelegationLib.sol index 9c220c0aaf51..a5f6bafbfb71 100644 --- a/l1-contracts/src/governance/libraries/DepositDelegationLib.sol +++ b/l1-contracts/src/governance/libraries/DepositDelegationLib.sol @@ -2,9 +2,7 @@ // Copyright 2024 Aztec Labs. pragma solidity >=0.8.27; -import { - Checkpoints, CheckpointedUintLib -} from "@aztec/governance/libraries/CheckpointedUintLib.sol"; +import {Checkpoints, CheckpointedUintLib} from "@aztec/governance/libraries/CheckpointedUintLib.sol"; import {Errors} from "@aztec/governance/libraries/Errors.sol"; import {Timestamp} from "@aztec/shared/libraries/TimeMath.sol"; @@ -107,8 +105,7 @@ library DepositDelegationLib { uint256 powerUsed = getPowerUsed(_self, _delegatee, _proposalId); require( - powerAt >= powerUsed + _amount, - Errors.Delegation__InsufficientPower(_delegatee, powerAt, powerUsed + _amount) + powerAt >= powerUsed + _amount, Errors.Delegation__InsufficientPower(_delegatee, powerAt, powerUsed + _amount) ); _self.votingAccounts[_delegatee].powerUsed[_proposalId] += _amount; @@ -130,27 +127,19 @@ library DepositDelegationLib { moveVotingPower(_self, oldDelegate, _delegatee, getBalanceOf(_self, _instance, _attester)); } - function undelegate( - DepositAndDelegationAccounting storage _self, - address _instance, - address _attester - ) internal { + function undelegate(DepositAndDelegationAccounting storage _self, address _instance, address _attester) internal { delegate(_self, _instance, _attester, address(0)); } - function getBalanceOf( - DepositAndDelegationAccounting storage _self, - address _instance, - address _attester - ) internal view returns (uint256) { - return _self.ledgers[_instance].positions[_attester].balance; - } - - function getSupplyOf(DepositAndDelegationAccounting storage _self, address _instance) + function getBalanceOf(DepositAndDelegationAccounting storage _self, address _instance, address _attester) internal view returns (uint256) { + return _self.ledgers[_instance].positions[_attester].balance; + } + + function getSupplyOf(DepositAndDelegationAccounting storage _self, address _instance) internal view returns (uint256) { return _self.ledgers[_instance].supply.valueNow(); } @@ -158,11 +147,11 @@ library DepositDelegationLib { return _self.supply.valueNow(); } - function getDelegatee( - DepositAndDelegationAccounting storage _self, - address _instance, - address _attester - ) internal view returns (address) { + function getDelegatee(DepositAndDelegationAccounting storage _self, address _instance, address _attester) + internal + view + returns (address) + { return _self.ledgers[_instance].positions[_attester].delegatee; } @@ -174,28 +163,25 @@ library DepositDelegationLib { return _self.votingAccounts[_delegatee].votingPower.valueNow(); } - function getVotingPowerAt( - DepositAndDelegationAccounting storage _self, - address _delegatee, - Timestamp _timestamp - ) internal view returns (uint256) { + function getVotingPowerAt(DepositAndDelegationAccounting storage _self, address _delegatee, Timestamp _timestamp) + internal + view + returns (uint256) + { return _self.votingAccounts[_delegatee].votingPower.valueAt(_timestamp); } - function getPowerUsed( - DepositAndDelegationAccounting storage _self, - address _delegatee, - uint256 _proposalId - ) internal view returns (uint256) { + function getPowerUsed(DepositAndDelegationAccounting storage _self, address _delegatee, uint256 _proposalId) + internal + view + returns (uint256) + { return _self.votingAccounts[_delegatee].powerUsed[_proposalId]; } - function moveVotingPower( - DepositAndDelegationAccounting storage _self, - address _from, - address _to, - uint256 _amount - ) private { + function moveVotingPower(DepositAndDelegationAccounting storage _self, address _from, address _to, uint256 _amount) + private + { if (_from == _to || _amount == 0) { return; } diff --git a/l1-contracts/src/governance/libraries/Errors.sol b/l1-contracts/src/governance/libraries/Errors.sol index e1ef260ea212..3fedd4f2ea43 100644 --- a/l1-contracts/src/governance/libraries/Errors.sol +++ b/l1-contracts/src/governance/libraries/Errors.sol @@ -30,9 +30,7 @@ library Errors { error Governance__ProposalCannotBeDropped(); error Governance__DepositNotAllowed(); - error Governance__CheckpointedUintLib__InsufficientValue( - address owner, uint256 have, uint256 required - ); + error Governance__CheckpointedUintLib__InsufficientValue(address owner, uint256 have, uint256 required); error Governance__CheckpointedUintLib__NotInPast(); error Governance__ConfigurationLib__InvalidMinimumVotes(); @@ -54,9 +52,7 @@ library Errors { error GovernanceProposer__InsufficientSignals(uint256 signalsCast, uint256 signalsNeeded); error GovernanceProposer__InvalidQuorumAndRoundSize(uint256 quorumSize, uint256 roundSize); error GovernanceProposer__QuorumCannotBeLargerThanRoundSize(uint256 quorumSize, uint256 roundSize); - error GovernanceProposer__InvalidLifetimeAndExecutionDelay( - uint256 lifetimeInRounds, uint256 executionDelayInRounds - ); + error GovernanceProposer__InvalidLifetimeAndExecutionDelay(uint256 lifetimeInRounds, uint256 executionDelayInRounds); error GovernanceProposer__OnlyProposerCanSignal(address caller, address proposer); error GovernanceProposer__PayloadAlreadySubmitted(uint256 roundNumber); error GovernanceProposer__PayloadCannotBeAddressZero(); diff --git a/l1-contracts/src/governance/libraries/ProposalLib.sol b/l1-contracts/src/governance/libraries/ProposalLib.sol index 33b42632be9c..3d33475a515b 100644 --- a/l1-contracts/src/governance/libraries/ProposalLib.sol +++ b/l1-contracts/src/governance/libraries/ProposalLib.sol @@ -130,8 +130,7 @@ library ProposalLib { } uint256 requiredApprovalVotesFraction = Math.ceilDiv(1e18 + _self.config.requiredYeaMargin, 2); - uint256 requiredApprovalVotes = - Math.mulDiv(votesCast, requiredApprovalVotesFraction, 1e18, Math.Rounding.Ceil); + uint256 requiredApprovalVotes = Math.mulDiv(votesCast, requiredApprovalVotesFraction, 1e18, Math.Rounding.Ceil); /*if (requiredApprovalVotes == 0) { // It should be impossible to hit this case as `requiredApprovalVotesFraction` cannot be 0, diff --git a/l1-contracts/src/governance/proposer/EmpireBase.sol b/l1-contracts/src/governance/proposer/EmpireBase.sol index ec9f931a3470..d323688bc38f 100644 --- a/l1-contracts/src/governance/proposer/EmpireBase.sol +++ b/l1-contracts/src/governance/proposer/EmpireBase.sol @@ -38,7 +38,8 @@ struct CompressedRoundAccounting { * - The GovernanceProposer * - The SlashingProposer * - * The GovernanceProposer is used to signal support for payloads before they are submitted to the main Governance contract, + * The GovernanceProposer is used to signal support for payloads before they are submitted to the main Governance + * contract, * resulting in a two-stage governance process: * 1. Signal gathering (GovernanceProposer contract) - validators indicate support * 2. Formal governance (Governance contract) - actual voting and execution @@ -53,8 +54,10 @@ struct CompressedRoundAccounting { * **Rounds**: Time is divided into rounds of ROUND_SIZE slots. Payloads compete for support * within a round. * - * **Instances**: Refers to an instance of the rollup contract, which in this case is exposed via a simplified IEmperor interface. - * This contract only needs the instance to determine the current slot (to compute the round), and the current block proposer. + * **Instances**: Refers to an instance of the rollup contract, which in this case is exposed via a simplified IEmperor + * interface. + * This contract only needs the instance to determine the current slot (to compute the round), and the current block + * proposer. * * **Signalers**: Each slot has a designated signaler (determined by IEmperor). * Only the current slot's signaler can signal support, either directly or via signature. @@ -88,12 +91,15 @@ struct CompressedRoundAccounting { * - `getInstance()`: Returns the IEmperor instance for slot/signaler info * - `_handleRoundWinner(IPayload _payload)`: Called during `submitRoundWinner` * - * Note this contract can support multiple instances/rollups. This is because the instance is retrieved dynamically from the + * Note this contract can support multiple instances/rollups. This is because the instance is retrieved dynamically from + * the * underlying implementation. For example, when the GovernanceProposer is used, the instance is the canonical rollup, * which will change whenever there is a new canonical rollup. * - * This also means that if the new canonical rollup does not support the IEmperor interface, this contract will not work, - * and a different implementation will need to be specified as part of the payload which deploys the new canonical instance. + * This also means that if the new canonical rollup does not support the IEmperor interface, this contract will not + * work, + * and a different implementation will need to be specified as part of the payload which deploys the new canonical + * instance. */ abstract contract EmpireBase is EIP712, IEmpire { using SignatureLib for Signature; @@ -101,8 +107,7 @@ abstract contract EmpireBase is EIP712, IEmpire { using CompressedTimeMath for CompressedSlot; // EIP-712 type hash for the Signal struct - bytes32 public constant SIGNAL_TYPEHASH = - keccak256("Signal(address payload,uint256 nonce,uint256 round)"); + bytes32 public constant SIGNAL_TYPEHASH = keccak256("Signal(address payload,uint256 nonce,uint256 round)"); // The number of signals needed for a payload to be considered submittable. uint256 public immutable QUORUM_SIZE; @@ -114,36 +119,26 @@ abstract contract EmpireBase is EIP712, IEmpire { uint256 public immutable EXECUTION_DELAY_IN_ROUNDS; // Mapping of instance to round number to round accounting. - mapping(address instance => mapping(uint256 roundNumber => CompressedRoundAccounting)) internal - rounds; + mapping(address instance => mapping(uint256 roundNumber => CompressedRoundAccounting)) internal rounds; // Mapping of instance signaler to nonce. Used to prevent replay attacks. mapping(address signaler => uint256 nonce) public nonces; - constructor( - uint256 _quorumSize, - uint256 _roundSize, - uint256 _lifetimeInRounds, - uint256 _executionDelayInRounds - ) EIP712("EmpireBase", "1") { + constructor(uint256 _quorumSize, uint256 _roundSize, uint256 _lifetimeInRounds, uint256 _executionDelayInRounds) + EIP712("EmpireBase", "1") + { QUORUM_SIZE = _quorumSize; ROUND_SIZE = _roundSize; LIFETIME_IN_ROUNDS = _lifetimeInRounds; EXECUTION_DELAY_IN_ROUNDS = _executionDelayInRounds; + require(QUORUM_SIZE > ROUND_SIZE / 2, Errors.GovernanceProposer__InvalidQuorumAndRoundSize(QUORUM_SIZE, ROUND_SIZE)); require( - QUORUM_SIZE > ROUND_SIZE / 2, - Errors.GovernanceProposer__InvalidQuorumAndRoundSize(QUORUM_SIZE, ROUND_SIZE) - ); - require( - QUORUM_SIZE <= ROUND_SIZE, - Errors.GovernanceProposer__QuorumCannotBeLargerThanRoundSize(QUORUM_SIZE, ROUND_SIZE) + QUORUM_SIZE <= ROUND_SIZE, Errors.GovernanceProposer__QuorumCannotBeLargerThanRoundSize(QUORUM_SIZE, ROUND_SIZE) ); require( LIFETIME_IN_ROUNDS > EXECUTION_DELAY_IN_ROUNDS, - Errors.GovernanceProposer__InvalidLifetimeAndExecutionDelay( - LIFETIME_IN_ROUNDS, EXECUTION_DELAY_IN_ROUNDS - ) + Errors.GovernanceProposer__InvalidLifetimeAndExecutionDelay(LIFETIME_IN_ROUNDS, EXECUTION_DELAY_IN_ROUNDS) ); } @@ -168,11 +163,7 @@ abstract contract EmpireBase is EIP712, IEmpire { * * @return True if executed successfully, false otherwise */ - function signalWithSig(IPayload _payload, Signature memory _sig) - external - override(IEmpire) - returns (bool) - { + function signalWithSig(IPayload _payload, Signature memory _sig) external override(IEmpire) returns (bool) { return _internalSignal(_payload, _sig); } @@ -208,14 +199,10 @@ abstract contract EmpireBase is EIP712, IEmpire { CompressedRoundAccounting storage round = rounds[instance][_roundNumber]; require(!round.executed, Errors.GovernanceProposer__PayloadAlreadySubmitted(_roundNumber)); require( - round.payloadWithMostSignals != IPayload(address(0)), - Errors.GovernanceProposer__PayloadCannotBeAddressZero() + round.payloadWithMostSignals != IPayload(address(0)), Errors.GovernanceProposer__PayloadCannotBeAddressZero() ); uint256 signalsCast = round.signalCount[round.payloadWithMostSignals]; - require( - signalsCast >= QUORUM_SIZE, - Errors.GovernanceProposer__InsufficientSignals(signalsCast, QUORUM_SIZE) - ); + require(signalsCast >= QUORUM_SIZE, Errors.GovernanceProposer__InsufficientSignals(signalsCast, QUORUM_SIZE)); round.executed = true; @@ -257,11 +244,7 @@ abstract contract EmpireBase is EIP712, IEmpire { return computeRound(currentSlot); } - function getRoundData(address _instance, uint256 _round) - external - view - returns (RoundAccounting memory) - { + function getRoundData(address _instance, uint256 _round) external view returns (RoundAccounting memory) { CompressedRoundAccounting storage compressedRound = rounds[_instance][_round]; return RoundAccounting({ lastSignalSlot: compressedRound.lastSignalSlot.decompress(), @@ -281,13 +264,8 @@ abstract contract EmpireBase is EIP712, IEmpire { return Slot.unwrap(_slot) / ROUND_SIZE; } - function getSignalSignatureDigest(IPayload _payload, address _signaler, uint256 _round) - public - view - returns (bytes32) - { - return - _hashTypedDataV4(keccak256(abi.encode(SIGNAL_TYPEHASH, _payload, nonces[_signaler], _round))); + function getSignalSignatureDigest(IPayload _payload, address _signaler, uint256 _round) public view returns (bytes32) { + return _hashTypedDataV4(keccak256(abi.encode(SIGNAL_TYPEHASH, _payload, nonces[_signaler], _round))); } // Virtual functions @@ -306,26 +284,19 @@ abstract contract EmpireBase is EIP712, IEmpire { CompressedRoundAccounting storage round = rounds[instance][roundNumber]; require( - currentSlot > round.lastSignalSlot.decompress(), - Errors.GovernanceProposer__SignalAlreadyCastForSlot(currentSlot) + currentSlot > round.lastSignalSlot.decompress(), Errors.GovernanceProposer__SignalAlreadyCastForSlot(currentSlot) ); address signaler = sequencerSelection.getCurrentProposer(); if (_sig.isEmpty()) { - require( - msg.sender == signaler, - Errors.GovernanceProposer__OnlyProposerCanSignal(msg.sender, signaler) - ); + require(msg.sender == signaler, Errors.GovernanceProposer__OnlyProposerCanSignal(msg.sender, signaler)); } else { bytes32 digest = getSignalSignatureDigest(_payload, signaler, roundNumber); nonces[signaler]++; // _sig.verify will throw if invalid, it is more my sanity that I am doing this for. - require( - _sig.verify(signaler, digest), - Errors.GovernanceProposer__OnlyProposerCanSignal(msg.sender, signaler) - ); + require(_sig.verify(signaler, digest), Errors.GovernanceProposer__OnlyProposerCanSignal(msg.sender, signaler)); } round.signalCount[_payload] += 1; diff --git a/l1-contracts/src/governance/proposer/GovernanceProposer.sol b/l1-contracts/src/governance/proposer/GovernanceProposer.sol index 88c0bb4e44c2..62a4273dba9e 100644 --- a/l1-contracts/src/governance/proposer/GovernanceProposer.sol +++ b/l1-contracts/src/governance/proposer/GovernanceProposer.sol @@ -38,12 +38,7 @@ contract GovernanceProposer is IGovernanceProposer, EmpireBase { GSE = _gse; } - function getProposalProposer(uint256 _proposalId) - external - view - override(IGovernanceProposer) - returns (address) - { + function getProposalProposer(uint256 _proposalId) external view override(IGovernanceProposer) returns (address) { return proposalProposer[_proposalId]; } diff --git a/l1-contracts/src/mock/MockVerifier.sol b/l1-contracts/src/mock/MockVerifier.sol index 77f84a9eede4..895761032ef6 100644 --- a/l1-contracts/src/mock/MockVerifier.sol +++ b/l1-contracts/src/mock/MockVerifier.sol @@ -17,12 +17,7 @@ contract MockVerifier is IVerifier { * @param - The public inputs, which are ignored * @return True always */ - function verify(bytes calldata, bytes32[] calldata) - external - pure - override(IVerifier) - returns (bool) - { + function verify(bytes calldata, bytes32[] calldata) external pure override(IVerifier) returns (bool) { return true; } } diff --git a/l1-contracts/src/mock/StakingAssetHandler.sol b/l1-contracts/src/mock/StakingAssetHandler.sol index 181c86431726..7ac7db9e36e0 100644 --- a/l1-contracts/src/mock/StakingAssetHandler.sol +++ b/l1-contracts/src/mock/StakingAssetHandler.sol @@ -57,11 +57,8 @@ interface IStakingAssetHandler { error MerkleProofInvalid(); // Add validator methods - function addValidator( - address _attester, - bytes32[] memory _merkleProof, - ProofVerificationParams memory _params - ) external; + function addValidator(address _attester, bytes32[] memory _merkleProof, ProofVerificationParams memory _params) + external; function reenterExitedValidator(address _attester) external; // Admin methods @@ -160,11 +157,10 @@ contract StakingAssetHandler is IStakingAssetHandler, Ownable { * * @param _attester - the validator's attester address */ - function addValidator( - address _attester, - bytes32[] memory _merkleProof, - ProofVerificationParams calldata _params - ) external override(IStakingAssetHandler) { + function addValidator(address _attester, bytes32[] memory _merkleProof, ProofVerificationParams calldata _params) + external + override(IStakingAssetHandler) + { IStaking rollup = IStaking(address(REGISTRY.getCanonicalRollup())); uint256 activationThreshold = rollup.getActivationThreshold(); @@ -210,21 +206,13 @@ contract StakingAssetHandler is IStakingAssetHandler, Ownable { emit IntervalUpdated(_interval); } - function setDepositsPerMint(uint256 _depositsPerMint) - external - override(IStakingAssetHandler) - onlyOwner - { + function setDepositsPerMint(uint256 _depositsPerMint) external override(IStakingAssetHandler) onlyOwner { require(_depositsPerMint > 0, CannotMintZeroAmount()); depositsPerMint = _depositsPerMint; emit DepositsPerMintUpdated(_depositsPerMint); } - function setZKPassportVerifier(address _zkPassportVerifier) - external - override(IStakingAssetHandler) - onlyOwner - { + function setZKPassportVerifier(address _zkPassportVerifier) external override(IStakingAssetHandler) onlyOwner { zkPassportVerifier = ZKPassportVerifier(_zkPassportVerifier); emit ZKPassportVerifierUpdated(_zkPassportVerifier); } @@ -259,11 +247,7 @@ contract StakingAssetHandler is IStakingAssetHandler, Ownable { emit SkipBindCheckUpdated(_skipBindCheck); } - function setSkipMerkleCheck(bool _skipMerkleCheck) - external - override(IStakingAssetHandler) - onlyOwner - { + function setSkipMerkleCheck(bool _skipMerkleCheck) external override(IStakingAssetHandler) onlyOwner { skipMerkleCheck = _skipMerkleCheck; emit SkipMerkleCheckUpdated(_skipMerkleCheck); } @@ -283,9 +267,7 @@ contract StakingAssetHandler is IStakingAssetHandler, Ownable { * @param _attester - The validator's attester address * @param _params - ZKPassport proof params */ - function _validatePassportProof(address _attester, ProofVerificationParams calldata _params) - internal - { + function _validatePassportProof(address _attester, ProofVerificationParams calldata _params) internal { // Must NOT be using dev mode - https://docs.zkpassport.id/getting-started/dev-mode // If active, nullifiers will end up being zero, but it is user provided input, so we are sanity checking it require(_params.devMode == false, InvalidProof()); @@ -299,8 +281,7 @@ contract StakingAssetHandler is IStakingAssetHandler, Ownable { require(!nullifiers[nullifier], SybilDetected(nullifier)); if (!skipBindCheck) { - bytes memory data = - zkPassportVerifier.getBindProofInputs(_params.committedInputs, _params.committedInputCounts); + bytes memory data = zkPassportVerifier.getBindProofInputs(_params.committedInputs, _params.committedInputCounts); // Use the getBoundData function to get the formatted data // which includes the user's address, chainId and any custom data (address boundAddress, uint256 chainId,) = zkPassportVerifier.getBoundData(data); @@ -318,8 +299,7 @@ contract StakingAssetHandler is IStakingAssetHandler, Ownable { function _topUpIfRequired(uint256 _activationThreshold) internal { if (STAKING_ASSET.balanceOf(address(this)) < _activationThreshold) { require( - block.timestamp - lastMintTimestamp >= mintInterval, - ValidatorQuotaFilledUntil(lastMintTimestamp + mintInterval) + block.timestamp - lastMintTimestamp >= mintInterval, ValidatorQuotaFilledUntil(lastMintTimestamp + mintInterval) ); STAKING_ASSET.mint(address(this), _activationThreshold * depositsPerMint); lastMintTimestamp = block.timestamp; @@ -336,9 +316,7 @@ contract StakingAssetHandler is IStakingAssetHandler, Ownable { * @param _activationThreshold - the deposit amount * @param _attester - the validator's attester address */ - function _triggerDeposit(IStaking _rollup, uint256 _activationThreshold, address _attester) - internal - { + function _triggerDeposit(IStaking _rollup, uint256 _activationThreshold, address _attester) internal { // If the attester is currently exiting, we finalize the exit for them. if (_rollup.getExit(_attester).exists) { _rollup.finaliseWithdraw(_attester); diff --git a/l1-contracts/src/mock/TestERC20.sol b/l1-contracts/src/mock/TestERC20.sol index d3dbdeea720f..4771c9286d97 100644 --- a/l1-contracts/src/mock/TestERC20.sol +++ b/l1-contracts/src/mock/TestERC20.sol @@ -14,10 +14,7 @@ contract TestERC20 is ERC20, IMintableERC20, Ownable2Step { _; } - constructor(string memory _name, string memory _symbol, address _owner) - ERC20(_name, _symbol) - Ownable(_owner) - { + constructor(string memory _name, string memory _symbol, address _owner) ERC20(_name, _symbol) Ownable(_owner) { minters[_owner] = true; emit MinterAdded(_owner); } diff --git a/l1-contracts/src/mock/staking_asset_handler/MockZKPassportVerifier.sol b/l1-contracts/src/mock/staking_asset_handler/MockZKPassportVerifier.sol index 8ce65926fbba..4e07094f355e 100644 --- a/l1-contracts/src/mock/staking_asset_handler/MockZKPassportVerifier.sol +++ b/l1-contracts/src/mock/staking_asset_handler/MockZKPassportVerifier.sol @@ -11,11 +11,9 @@ import {ProofVerificationParams} from "@zkpassport/ZKPassportVerifier.sol"; interface IZKPassportVerifier { function verifyProof(ProofVerificationParams calldata params) external returns (bool, bytes32); - function verifyScopes( - bytes32[] calldata publicInputs, - string calldata domain, - string calldata scope - ) external returns (bool); + function verifyScopes(bytes32[] calldata publicInputs, string calldata domain, string calldata scope) + external + returns (bool); } // A mock zk passport verifier that returns an incrementing unique identifier (nullifier) - for happy case tests @@ -26,11 +24,7 @@ contract MockZKPassportVerifier is IZKPassportVerifier { return (true, bytes32(uniqueIdentifier)); } - function verifyScopes(bytes32[] calldata, string calldata, string calldata) - external - pure - returns (bool) - { + function verifyScopes(bytes32[] calldata, string calldata, string calldata) external pure returns (bool) { return true; } diff --git a/l1-contracts/src/periphery/SlashFactory.sol b/l1-contracts/src/periphery/SlashFactory.sol index 6f53d008d5bc..bfc220036388 100644 --- a/l1-contracts/src/periphery/SlashFactory.sol +++ b/l1-contracts/src/periphery/SlashFactory.sol @@ -14,11 +14,11 @@ contract SlashFactory is ISlashFactory { VALIDATOR_SELECTION = _validatorSelection; } - function createSlashPayload( - address[] memory _validators, - uint96[] memory _amounts, - uint256[] memory _offenses - ) external override(ISlashFactory) returns (IPayload) { + function createSlashPayload(address[] memory _validators, uint96[] memory _amounts, uint256[] memory _offenses) + external + override(ISlashFactory) + returns (IPayload) + { require( _validators.length == _amounts.length, ISlashFactory.SlashPayloadAmountsLengthMismatch(_validators.length, _amounts.length) @@ -28,8 +28,7 @@ contract SlashFactory is ISlashFactory { ISlashFactory.SlashPayloadOffensesLengthMismatch(_validators.length, _offenses.length) ); - (address predictedAddress, bytes32 salt, bool isDeployed) = - getAddressAndIsDeployed(_validators, _amounts); + (address predictedAddress, bytes32 salt, bool isDeployed) = getAddressAndIsDeployed(_validators, _amounts); if (isDeployed) { return IPayload(predictedAddress); @@ -61,16 +60,10 @@ contract SlashFactory is ISlashFactory { bytes32 salt = keccak256(abi.encodePacked(_validators, _amounts)); bytes memory constructorArgs = abi.encode(_validators, _amounts, VALIDATOR_SELECTION); - bytes32 creationCodeHash = - keccak256(abi.encodePacked(type(SlashPayload).creationCode, constructorArgs)); + bytes32 creationCodeHash = keccak256(abi.encodePacked(type(SlashPayload).creationCode, constructorArgs)); return ( - address( - uint160( - uint256(keccak256(abi.encodePacked(bytes1(0xff), address(this), salt, creationCodeHash))) - ) - ), - salt + address(uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), address(this), salt, creationCodeHash))))), salt ); } } diff --git a/l1-contracts/src/periphery/SlashPayload.sol b/l1-contracts/src/periphery/SlashPayload.sol index 6cffbdfc2073..dda0a7ecbbde 100644 --- a/l1-contracts/src/periphery/SlashPayload.sol +++ b/l1-contracts/src/periphery/SlashPayload.sol @@ -18,11 +18,7 @@ contract SlashPayload is IPayload { IValidatorSelection public immutable VALIDATOR_SELECTION; Offender[] public offenders; - constructor( - address[] memory _validators, - uint96[] memory _amounts, - IValidatorSelection _validatorSelection - ) { + constructor(address[] memory _validators, uint96[] memory _amounts, IValidatorSelection _validatorSelection) { for (uint256 i = 0; i < _validators.length; i++) { offenders.push(Offender({validator: _validators[i], amount: _amounts[i]})); } @@ -39,9 +35,7 @@ contract SlashPayload is IPayload { for (uint256 i = 0; i < offenders.length; i++) { actions[i] = IPayload.Action({ target: address(VALIDATOR_SELECTION), - data: abi.encodeWithSelector( - IStakingCore.slash.selector, offenders[i].validator, offenders[i].amount - ) + data: abi.encodeWithSelector(IStakingCore.slash.selector, offenders[i].validator, offenders[i].amount) }); } return actions; diff --git a/l1-contracts/src/periphery/interfaces/ISlashFactory.sol b/l1-contracts/src/periphery/interfaces/ISlashFactory.sol index bf28e30266ac..f47ba0069d0e 100644 --- a/l1-contracts/src/periphery/interfaces/ISlashFactory.sol +++ b/l1-contracts/src/periphery/interfaces/ISlashFactory.sol @@ -5,18 +5,14 @@ pragma solidity >=0.8.27; import {IPayload} from "@aztec/governance/interfaces/IPayload.sol"; interface ISlashFactory { - event SlashPayloadCreated( - address payloadAddress, address[] validators, uint96[] amounts, uint256[] offenses - ); + event SlashPayloadCreated(address payloadAddress, address[] validators, uint96[] amounts, uint256[] offenses); error SlashPayloadAmountsLengthMismatch(uint256 expected, uint256 actual); error SlashPayloadOffensesLengthMismatch(uint256 expected, uint256 actual); - function createSlashPayload( - address[] memory _validators, - uint96[] memory _amounts, - uint256[] memory _offenses - ) external returns (IPayload); + function createSlashPayload(address[] memory _validators, uint96[] memory _amounts, uint256[] memory _offenses) + external + returns (IPayload); function getAddressAndIsDeployed(address[] memory _validators, uint96[] memory _amounts) external diff --git a/l1-contracts/src/shared/libraries/SignatureLib.sol b/l1-contracts/src/shared/libraries/SignatureLib.sol index 16d71d623363..bc5d4f2f8e31 100644 --- a/l1-contracts/src/shared/libraries/SignatureLib.sol +++ b/l1-contracts/src/shared/libraries/SignatureLib.sol @@ -20,7 +20,8 @@ struct Signature { } // A committee attestation can be made up of a signature and an address. -// Committee members that have attested will produce a signature, and if they have not attested, the signature will be empty and +// Committee members that have attested will produce a signature, and if they have not attested, the signature will be +// empty and // an address provided. struct CommitteeAttestation { address addr; @@ -43,8 +44,7 @@ library SignatureLib { * @return True if the committee attestations are empty, false otherwise */ function isEmpty(CommitteeAttestations memory _attestations) internal pure returns (bool) { - return - _attestations.signatureIndices.length == 0 && _attestations.signaturesOrAddresses.length == 0; + return _attestations.signatureIndices.length == 0 && _attestations.signaturesOrAddresses.length == 0; } /** @@ -59,11 +59,7 @@ library SignatureLib { * * See its use over in ValidatorSelectionLib.sol */ - function isSignature(CommitteeAttestations memory _attestations, uint256 _index) - internal - pure - returns (bool) - { + function isSignature(CommitteeAttestations memory _attestations, uint256 _index) internal pure returns (bool) { uint256 byteIndex = _index / 8; uint256 shift = 7 - (_index % 8); return (uint8(_attestations.signatureIndices[byteIndex]) >> shift) & 1 == 1; @@ -108,7 +104,8 @@ library SignatureLib { } /** - * Returns the addresses from the CommitteeAttestations, using the array of signers to populate where there are signatures. + * Returns the addresses from the CommitteeAttestations, using the array of signers to populate where there are + * signatures. * Indices with signatures will have a zero address. * @param _attestations - The committee attestations * @param _length - The number of addresses to return, should match the number of committee members @@ -167,11 +164,7 @@ library SignatureLib { * @param _signer - The expected signer of the signature * @param _digest - The digest that was signed */ - function verify(Signature memory _signature, address _signer, bytes32 _digest) - internal - pure - returns (bool) - { + function verify(Signature memory _signature, address _signer, bytes32 _digest) internal pure returns (bool) { address recovered = ECDSA.recover(_digest, _signature.v, _signature.r, _signature.s); require(_signer == recovered, SignatureLib__InvalidSignature(_signer, recovered)); return true; @@ -249,9 +242,6 @@ library SignatureLib { } } - return CommitteeAttestations({ - signatureIndices: signatureIndices, - signaturesOrAddresses: signaturesOrAddresses - }); + return CommitteeAttestations({signatureIndices: signatureIndices, signaturesOrAddresses: signaturesOrAddresses}); } } diff --git a/l1-contracts/test/Inbox.t.sol b/l1-contracts/test/Inbox.t.sol index 69c5edfc1fef..2434a4748832 100644 --- a/l1-contracts/test/Inbox.t.sol +++ b/l1-contracts/test/Inbox.t.sol @@ -108,8 +108,7 @@ contract InboxTest is Test { DataStructures.L1ToL2Msg memory message = _boundMessage(_message, globalLeafIndex); bytes32 leaf = message.sha256ToField(); - bytes16 expectedRollingHash = - bytes16(keccak256(abi.encodePacked(stateBefore.rollingHash, leaf))); + bytes16 expectedRollingHash = bytes16(keccak256(abi.encodePacked(stateBefore.rollingHash, leaf))); vm.expectEmit(true, true, true, true); // event we expect emit IInbox.MessageSent(FIRST_REAL_TREE_NUM, globalLeafIndex, leaf, expectedRollingHash); @@ -128,12 +127,9 @@ contract InboxTest is Test { function testSendDuplicateL2Messages() public checkInvariant { DataStructures.L1ToL2Msg memory message = _fakeMessage(); - (bytes32 leaf1, uint256 index1) = - inbox.sendL2Message(message.recipient, message.content, message.secretHash); - (bytes32 leaf2, uint256 index2) = - inbox.sendL2Message(message.recipient, message.content, message.secretHash); - (bytes32 leaf3, uint256 index3) = - inbox.sendL2Message(message.recipient, message.content, message.secretHash); + (bytes32 leaf1, uint256 index1) = inbox.sendL2Message(message.recipient, message.content, message.secretHash); + (bytes32 leaf2, uint256 index2) = inbox.sendL2Message(message.recipient, message.content, message.secretHash); + (bytes32 leaf3, uint256 index3) = inbox.sendL2Message(message.recipient, message.content, message.secretHash); // Only 1 tree should be non-zero assertEq(inbox.getNumTrees(), 1); @@ -150,20 +146,14 @@ contract InboxTest is Test { function testRevertIfActorTooLarge() public { DataStructures.L1ToL2Msg memory message = _fakeMessage(); message.recipient.actor = bytes32(Constants.P); - vm.expectRevert( - abi.encodeWithSelector(Errors.Inbox__ActorTooLarge.selector, message.recipient.actor) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Inbox__ActorTooLarge.selector, message.recipient.actor)); inbox.sendL2Message(message.recipient, message.content, message.secretHash); } function testRevertIfVersionMismatch() public { DataStructures.L1ToL2Msg memory message = _fakeMessage(); message.recipient.version = version + 1; - vm.expectRevert( - abi.encodeWithSelector( - Errors.Inbox__VersionMismatch.selector, message.recipient.version, version - ) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Inbox__VersionMismatch.selector, message.recipient.version, version)); inbox.sendL2Message(message.recipient, message.content, message.secretHash); } @@ -177,9 +167,7 @@ contract InboxTest is Test { function testRevertIfSecretHashTooLarge() public { DataStructures.L1ToL2Msg memory message = _fakeMessage(); message.secretHash = bytes32(Constants.P); - vm.expectRevert( - abi.encodeWithSelector(Errors.Inbox__SecretHashTooLarge.selector, message.secretHash) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Inbox__SecretHashTooLarge.selector, message.secretHash)); inbox.sendL2Message(message.recipient, message.content, message.secretHash); } @@ -207,8 +195,7 @@ contract InboxTest is Test { // We send the messages and then check that toConsume root did not change. for (uint256 i = 0; i < _messages.length; i++) { - DataStructures.L1ToL2Msg memory message = - _boundMessage(_messages[i], inbox.getNextMessageIndex()); + DataStructures.L1ToL2Msg memory message = _boundMessage(_messages[i], inbox.getNextMessageIndex()); // We check whether a new tree is correctly initialized when the one in progress is full uint256 numTrees = inbox.getNumTrees(); @@ -222,9 +209,7 @@ contract InboxTest is Test { // Root of a tree waiting to be consumed should not change because we introduced a 1 block lag to prevent sequencer // DOS attacks assertEq( - inbox.getToConsumeRoot(blockNumber), - toConsumeRoot, - "Root of a tree waiting to be consumed should not change" + inbox.getToConsumeRoot(blockNumber), toConsumeRoot, "Root of a tree waiting to be consumed should not change" ); } @@ -237,8 +222,7 @@ contract InboxTest is Test { // Now we consume the trees for (uint256 i = 0; i < numTreesToConsume; i++) { uint256 numTrees = inbox.getNumTrees(); - uint256 expectedNumTrees = - (blockNumber + 1 == inbox.getInProgress()) ? numTrees + 1 : numTrees; + uint256 expectedNumTrees = (blockNumber + 1 == inbox.getInProgress()) ? numTrees + 1 : numTrees; bytes32 root = inbox.consume(blockNumber); // We check whether a new tree is correctly initialized when the one which was in progress was set as to consume diff --git a/l1-contracts/test/MultiProof.t.sol b/l1-contracts/test/MultiProof.t.sol index 5694e53a0441..5efa7c5dbb44 100644 --- a/l1-contracts/test/MultiProof.t.sol +++ b/l1-contracts/test/MultiProof.t.sol @@ -64,8 +64,7 @@ contract MultiProofTest is RollupBase { { DecoderBase.Full memory full = load(_name); uint256 slotNumber = Slot.unwrap(full.block.header.slotNumber); - uint256 initialTime = - Timestamp.unwrap(full.block.header.timestamp) - slotNumber * SLOT_DURATION; + uint256 initialTime = Timestamp.unwrap(full.block.header.timestamp) - slotNumber * SLOT_DURATION; vm.warp(initialTime); } @@ -99,9 +98,7 @@ contract MultiProofTest is RollupBase { address[2] memory provers = [address(bytes20("alice")), address(bytes20("bob"))]; emit log_named_decimal_uint("sequencer rewards", rollup.getSequencerRewards(sequencer), 18); - emit log_named_decimal_uint( - "prover rewards", rollup.getCollectiveProverRewardsForEpoch(Epoch.wrap(0)), 18 - ); + emit log_named_decimal_uint("prover rewards", rollup.getCollectiveProverRewardsForEpoch(Epoch.wrap(0)), 18); for (uint256 i = 0; i < provers.length; i++) { for (uint256 j = 1; j <= provenBlockNumber; j++) { @@ -182,9 +179,7 @@ contract MultiProofTest is RollupBase { Epoch deadline = TimeLib.toDeadlineEpoch(epochs[0]); - vm.expectRevert( - abi.encodeWithSelector(Errors.Rollup__NotPastDeadline.selector, deadline, Epoch.wrap(0)) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Rollup__NotPastDeadline.selector, deadline, Epoch.wrap(0))); vm.prank(bob); rollup.claimProverRewards(bob, epochs); @@ -193,13 +188,9 @@ contract MultiProofTest is RollupBase { uint256 bobRewardsClaimed = rollup.claimProverRewards(bob, epochs); assertEq(bobRewardsClaimed, bobRewards, "Bob rewards not claimed"); - assertEq( - rollup.getSpecificProverRewardsForEpoch(Epoch.wrap(0), bob), 0, "Bob rewards not zeroed" - ); + assertEq(rollup.getSpecificProverRewardsForEpoch(Epoch.wrap(0), bob), 0, "Bob rewards not zeroed"); - vm.expectRevert( - abi.encodeWithSelector(Errors.Rollup__AlreadyClaimed.selector, bob, Epoch.wrap(0)) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Rollup__AlreadyClaimed.selector, bob, Epoch.wrap(0))); vm.prank(bob); rollup.claimProverRewards(bob, epochs); } @@ -219,31 +210,21 @@ contract MultiProofTest is RollupBase { ActivityScore memory activityScore = rewardBooster.getActivityScore(alice); - assertEq( - rollup.getSharesFor(alice), rollup.getSharesFor(bob), "Alice shares not equal to bob shares" - ); + assertEq(rollup.getSharesFor(alice), rollup.getSharesFor(bob), "Alice shares not equal to bob shares"); uint256 maxActivityScore = TestConstants.getRewardBoostConfig().maxScore; uint256 maxShares = TestConstants.getRewardBoostConfig().k; BoostedHelper(address(rewardBooster)).setActivityScore(alice, maxActivityScore); - assertGt( - rollup.getSharesFor(alice), - rollup.getSharesFor(bob), - "Alice shares not greater than bob shares" - ); + assertGt(rollup.getSharesFor(alice), rollup.getSharesFor(bob), "Alice shares not greater than bob shares"); activityScore = rewardBooster.getActivityScore(alice); assertEq(activityScore.value, maxActivityScore, "Activity score not set"); assertEq(rollup.getSharesFor(alice), maxShares, "Alice shares not set"); - assertEq( - rollup.getSpecificProverRewardsForEpoch(Epoch.wrap(0), alice), 0, "Alice rewards not zeroed" - ); - assertEq( - rollup.getSpecificProverRewardsForEpoch(Epoch.wrap(0), bob), 0, "Bob rewards not zeroed" - ); + assertEq(rollup.getSpecificProverRewardsForEpoch(Epoch.wrap(0), alice), 0, "Alice rewards not zeroed"); + assertEq(rollup.getSpecificProverRewardsForEpoch(Epoch.wrap(0), bob), 0, "Bob rewards not zeroed"); string memory name = "mixed_block_"; _proveBlocks(name, 1, 1, alice); @@ -260,17 +241,11 @@ contract MultiProofTest is RollupBase { { uint256 aliceRewards = rollup.getSpecificProverRewardsForEpoch(Epoch.wrap(0), alice); - assertEq( - aliceRewards, - totalRewards * rollup.getSharesFor(alice) / totalShares, - "Alice rewards not correct" - ); + assertEq(aliceRewards, totalRewards * rollup.getSharesFor(alice) / totalShares, "Alice rewards not correct"); } { uint256 bobRewards = rollup.getSpecificProverRewardsForEpoch(Epoch.wrap(0), bob); - assertEq( - bobRewards, totalRewards * rollup.getSharesFor(bob) / totalShares, "Bob rewards not correct" - ); + assertEq(bobRewards, totalRewards * rollup.getSharesFor(bob) / totalShares, "Bob rewards not correct"); } } @@ -280,11 +255,7 @@ contract MultiProofTest is RollupBase { string memory name = "mixed_block_"; _proveBlocksFail( - name, - 2, - 2, - address(bytes20("alice")), - abi.encodeWithSelector(Errors.Rollup__StartIsNotBuildingOnProven.selector) + name, 2, 2, address(bytes20("alice")), abi.encodeWithSelector(Errors.Rollup__StartIsNotBuildingOnProven.selector) ); } diff --git a/l1-contracts/test/Outbox.t.sol b/l1-contracts/test/Outbox.t.sol index bd83d2b44507..8445bb19b5cf 100644 --- a/l1-contracts/test/Outbox.t.sol +++ b/l1-contracts/test/Outbox.t.sol @@ -40,11 +40,7 @@ contract OutboxTest is Test { merkleTestUtil = new MerkleTestUtil(); } - function _fakeMessage(address _recipient, uint256 _content) - internal - view - returns (DataStructures.L2ToL1Msg memory) - { + function _fakeMessage(address _recipient, uint256 _content) internal view returns (DataStructures.L2ToL1Msg memory) { return DataStructures.L2ToL1Msg({ sender: DataStructures.L2Actor({ actor: 0x2000000000000000000000000000000000000000000000000000000000000000, @@ -72,8 +68,10 @@ contract OutboxTest is Test { } // This function tests the insertion of random arrays of L2 to L1 messages - // We make a naive tree with a computed height, insert the leafs into it, and compute a root. We then add the root as the root of the - // L2 to L1 message tree, expect for the correct event to be emitted, and then query for the root in the contract—making sure the roots, as well as the + // We make a naive tree with a computed height, insert the leafs into it, and compute a root. We then add the root as + // the root of the + // L2 to L1 message tree, expect for the correct event to be emitted, and then query for the root in the + // contract—making sure the roots, as well as the // the tree height (which is also the length of the sibling path) match function testInsertVariedLeafs(bytes32[] calldata _messageLeafs) public { uint256 treeHeight = merkleTestUtil.calculateTreeHeightFromSize(_messageLeafs.length); @@ -101,9 +99,7 @@ contract OutboxTest is Test { (bytes32[] memory path,) = zeroedTree.computeSiblingPath(0); vm.prank(NOT_RECIPIENT); - vm.expectRevert( - abi.encodeWithSelector(Errors.Outbox__InvalidRecipient.selector, address(this), NOT_RECIPIENT) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Outbox__InvalidRecipient.selector, address(this), NOT_RECIPIENT)); outbox.consume(fakeMessage, 1, 1, path); } @@ -124,9 +120,7 @@ contract OutboxTest is Test { message.sender.version = AZTEC_VERSION + 1; vm.expectRevert( - abi.encodeWithSelector( - Errors.Outbox__VersionMismatch.selector, message.sender.version, AZTEC_VERSION - ) + abi.encodeWithSelector(Errors.Outbox__VersionMismatch.selector, message.sender.version, AZTEC_VERSION) ); outbox.consume(message, 1, 1, path); } @@ -137,9 +131,7 @@ contract OutboxTest is Test { (bytes32[] memory path,) = zeroedTree.computeSiblingPath(0); - vm.expectRevert( - abi.encodeWithSelector(Errors.Outbox__NothingToConsumeAtBlock.selector, blockNumber) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Outbox__NothingToConsumeAtBlock.selector, blockNumber)); outbox.consume(fakeMessage, blockNumber, 1, path); } @@ -179,16 +171,14 @@ contract OutboxTest is Test { bytes32 smallerTreeRoot = smallerTree.computeRoot(); (bytes32[] memory path,) = smallerTree.computeSiblingPath(0); - vm.expectRevert( - abi.encodeWithSelector(Errors.MerkleLib__InvalidRoot.selector, root, smallerTreeRoot, leaf, 0) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.MerkleLib__InvalidRoot.selector, root, smallerTreeRoot, leaf, 0)); outbox.consume(fakeMessage, 1, 0, path); } function testRevertIfTryingToConsumeMessageNotInTree() public { DataStructures.L2ToL1Msg memory fakeMessage = _fakeMessage(address(this), 123); bytes32 leaf = fakeMessage.sha256ToField(); - fakeMessage.content = bytes32(uint256(42069)); + fakeMessage.content = bytes32(uint256(42_069)); bytes32 modifiedLeaf = fakeMessage.sha256ToField(); NaiveMerkle tree = new NaiveMerkle(DEFAULT_TREE_HEIGHT); @@ -204,11 +194,7 @@ contract OutboxTest is Test { (bytes32[] memory path,) = modifiedTree.computeSiblingPath(0); - vm.expectRevert( - abi.encodeWithSelector( - Errors.MerkleLib__InvalidRoot.selector, root, modifiedRoot, modifiedLeaf, 0 - ) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.MerkleLib__InvalidRoot.selector, root, modifiedRoot, modifiedLeaf, 0)); outbox.consume(fakeMessage, 1, 0, path); } @@ -398,9 +384,7 @@ contract OutboxTest is Test { } outbox.consume(fakeMessages[msgIndex], blockNumber, leafIndex, path); - vm.expectRevert( - abi.encodeWithSelector(Errors.Outbox__AlreadyNullified.selector, blockNumber, leafId) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Outbox__AlreadyNullified.selector, blockNumber, leafId)); outbox.consume(fakeMessages[msgIndex], blockNumber, leafIndex, path); } @@ -418,9 +402,7 @@ contract OutboxTest is Test { } outbox.consume(fakeMessages[msgIndex], blockNumber, leafIndex, path); - vm.expectRevert( - abi.encodeWithSelector(Errors.Outbox__AlreadyNullified.selector, blockNumber, leafId) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Outbox__AlreadyNullified.selector, blockNumber, leafId)); outbox.consume(fakeMessages[msgIndex], blockNumber, leafIndex, path); } @@ -432,9 +414,7 @@ contract OutboxTest is Test { (bytes32[] memory path,) = topTree.computeSiblingPath(1); outbox.consume(fakeMessages[msgIndex], blockNumber, leafIndex, path); - vm.expectRevert( - abi.encodeWithSelector(Errors.Outbox__AlreadyNullified.selector, blockNumber, leafId) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Outbox__AlreadyNullified.selector, blockNumber, leafId)); outbox.consume(fakeMessages[msgIndex], blockNumber, leafIndex, path); } } @@ -532,9 +512,7 @@ contract OutboxTest is Test { path[1] = txOutHashes[2]; outbox.consume(fakeMessages[msgIndex], blockNumber, leafIndex, path); - vm.expectRevert( - abi.encodeWithSelector(Errors.Outbox__AlreadyNullified.selector, blockNumber, leafId) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Outbox__AlreadyNullified.selector, blockNumber, leafId)); outbox.consume(fakeMessages[msgIndex], blockNumber, leafIndex, path); } @@ -559,9 +537,7 @@ contract OutboxTest is Test { path[3] = txOutHashes[2]; outbox.consume(fakeMessages[msgIndex], blockNumber, leafIndex, path); - vm.expectRevert( - abi.encodeWithSelector(Errors.Outbox__AlreadyNullified.selector, blockNumber, leafId) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Outbox__AlreadyNullified.selector, blockNumber, leafId)); outbox.consume(fakeMessages[msgIndex], blockNumber, leafIndex, path); } @@ -583,9 +559,7 @@ contract OutboxTest is Test { path[2] = subtreeRoot; outbox.consume(fakeMessages[msgIndex], blockNumber, leafIndex, path); - vm.expectRevert( - abi.encodeWithSelector(Errors.Outbox__AlreadyNullified.selector, blockNumber, leafId) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Outbox__AlreadyNullified.selector, blockNumber, leafId)); outbox.consume(fakeMessages[msgIndex], blockNumber, leafIndex, path); } @@ -604,9 +578,7 @@ contract OutboxTest is Test { path[1] = subtreeRoot; outbox.consume(fakeMessages[msgIndex], blockNumber, leafIndex, path); - vm.expectRevert( - abi.encodeWithSelector(Errors.Outbox__AlreadyNullified.selector, blockNumber, leafId) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Outbox__AlreadyNullified.selector, blockNumber, leafId)); outbox.consume(fakeMessages[msgIndex], blockNumber, leafIndex, path); } } diff --git a/l1-contracts/test/Parity.t.sol b/l1-contracts/test/Parity.t.sol index 6ffe4221967b..bfced6a386b0 100644 --- a/l1-contracts/test/Parity.t.sol +++ b/l1-contracts/test/Parity.t.sol @@ -22,11 +22,7 @@ contract ParityTest is Test { // We can't use Constants.NUM_MSGS_PER_BASE_PARITY directly when defining the array so we do the check here to // ensure it does not get outdated. - assertEq( - msgs.length, - Constants.NUM_MSGS_PER_BASE_PARITY, - "NUM_MSGS_PER_BASE_PARITY changed, update msgs." - ); + assertEq(msgs.length, Constants.NUM_MSGS_PER_BASE_PARITY, "NUM_MSGS_PER_BASE_PARITY changed, update msgs."); uint256 treeHeight = 2; // log_2(NUM_MSGS_PER_BASE_PARITY) // We don't have log_2 directly accessible in solidity so I just do the following check here to ensure diff --git a/l1-contracts/test/Rollup.t.sol b/l1-contracts/test/Rollup.t.sol index 2dcb712645f7..0265c6017420 100644 --- a/l1-contracts/test/Rollup.t.sol +++ b/l1-contracts/test/Rollup.t.sol @@ -77,8 +77,7 @@ contract RollupTest is RollupBase { { DecoderBase.Full memory full = load(_name); uint256 slotNumber = Slot.unwrap(full.block.header.slotNumber); - uint256 initialTime = - Timestamp.unwrap(full.block.header.timestamp) - slotNumber * SLOT_DURATION; + uint256 initialTime = Timestamp.unwrap(full.block.header.timestamp) - slotNumber * SLOT_DURATION; vm.warp(initialTime); } @@ -130,8 +129,7 @@ contract RollupTest is RollupBase { uint256 initialManaTarget = bound(_initialManaTarget, 0, type(uint64).max); uint256 newManaTarget = bound(_newManaTarget, initialManaTarget, type(uint64).max); - RollupBuilder builder = - new RollupBuilder(address(this)).setManaTarget(initialManaTarget).deploy(); + RollupBuilder builder = new RollupBuilder(address(this)).setManaTarget(initialManaTarget).deploy(); address governance = address(builder.getConfig().governance); rollup = IInstance(address(builder.getConfig().rollup)); @@ -153,8 +151,7 @@ contract RollupTest is RollupBase { uint256 initialManaTarget = bound(_initialManaTarget, 1, type(uint64).max); uint256 newManaTarget = bound(_newManaTarget, 0, initialManaTarget - 1); - RollupBuilder builder = - new RollupBuilder(address(this)).setManaTarget(initialManaTarget).deploy(); + RollupBuilder builder = new RollupBuilder(address(this)).setManaTarget(initialManaTarget).deploy(); address governance = address(builder.getConfig().governance); rollup = IInstance(address(builder.getConfig().rollup)); @@ -162,11 +159,7 @@ contract RollupTest is RollupBase { assertEq(rollup.getManaTarget(), initialManaTarget); // Cannot decrease the mana target - vm.expectRevert( - abi.encodeWithSelector( - Errors.Rollup__InvalidManaTarget.selector, initialManaTarget, newManaTarget - ) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Rollup__InvalidManaTarget.selector, initialManaTarget, newManaTarget)); vm.prank(governance); rollup.updateManaTarget(newManaTarget); assertEq(rollup.getManaTarget(), initialManaTarget); @@ -247,9 +240,7 @@ contract RollupTest is RollupBase { oracleInput: OracleInput(0) }); bytes32 realBlobHash = this.getBlobHashes(data.blobCommitments)[0]; - vm.expectRevert( - abi.encodeWithSelector(Errors.Rollup__InvalidBlobHash.selector, blobHashes[0], realBlobHash) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Rollup__InvalidBlobHash.selector, blobHashes[0], realBlobHash)); rollup.propose(args, SignatureLib.packAttestations(attestations), signers, data.blobCommitments); } @@ -257,8 +248,7 @@ contract RollupTest is RollupBase { bytes32[] memory extraBlobHashes = new bytes32[](6); for (uint256 i = 0; i < extraBlobHashes.length; i++) { extraBlobHashes[i] = bytes32( - uint256(sha256(abi.encode("extraBlob", i))) - & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF + uint256(sha256(abi.encode("extraBlob", i))) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ) | 0x0100000000000000000000000000000000000000000000000000000000000000; } @@ -287,8 +277,9 @@ contract RollupTest is RollupBase { warpToL2Slot(1); _proposeBlock("mixed_block_1", 1); // we prove epoch 0 - stdstore.enable_packed_slots().target(address(rollup)).sig("getProvenBlockNumber()") - .checked_write(rollup.getPendingBlockNumber()); + stdstore.enable_packed_slots().target(address(rollup)).sig("getProvenBlockNumber()").checked_write( + rollup.getPendingBlockNumber() + ); // jump to epoch 1 warpToL2Slot(EPOCH_DURATION); @@ -351,9 +342,7 @@ contract RollupTest is RollupBase { uint256 expectedFee = rollup.getManaBaseFeeAt(Timestamp.wrap(block.timestamp), true); // When not canonical, we expect the fee to be 0 - vm.expectRevert( - abi.encodeWithSelector(Errors.Rollup__InvalidManaBaseFee.selector, expectedFee, 1) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Rollup__InvalidManaBaseFee.selector, expectedFee, 1)); ProposeArgs memory args = ProposeArgs({ header: header, archive: data.archive, @@ -413,11 +402,7 @@ contract RollupTest is RollupBase { uint256 expectedProverRewards = rollup.getBlockReward() / 2 * 2 + proverFees; - assertEq( - rollup.getCollectiveProverRewardsForEpoch(Epoch.wrap(0)), - expectedProverRewards, - "invalid prover rewards" - ); + assertEq(rollup.getCollectiveProverRewardsForEpoch(Epoch.wrap(0)), expectedProverRewards, "invalid prover rewards"); } struct TestBlockFeeStruct { @@ -455,8 +440,7 @@ contract RollupTest is RollupBase { assertEq(coinbaseBalance, 0, "invalid initial coinbase balance"); skipBlobCheck(address(rollup)); - interim.baseFee = - SafeCast.toUint128(rollup.getManaBaseFeeAt(Timestamp.wrap(block.timestamp), true)); + interim.baseFee = SafeCast.toUint128(rollup.getManaBaseFeeAt(Timestamp.wrap(block.timestamp), true)); header.gasFees.feePerL2Gas = interim.baseFee; header.totalManaUsed = interim.manaUsed; @@ -471,9 +455,7 @@ contract RollupTest is RollupBase { stateReference: EMPTY_STATE_REFERENCE, oracleInput: OracleInput(0) }); - rollup.propose( - args, SignatureLib.packAttestations(attestations), signers, data.blobCommitments - ); + rollup.propose(args, SignatureLib.packAttestations(attestations), signers, data.blobCommitments); assertEq(testERC20.balanceOf(header.coinbase), 0, "invalid coinbase balance"); } @@ -493,14 +475,7 @@ contract RollupTest is RollupBase { ) ); _submitEpochProofWithFee( - 1, - 1, - blockLog.archive, - data.archive, - data.batchedBlobInputs, - prover, - header.coinbase, - interim.feeAmount + 1, 1, blockLog.archive, data.archive, data.batchedBlobInputs, prover, header.coinbase, interim.feeAmount ); } assertEq(testERC20.balanceOf(header.coinbase), 0, "invalid coinbase balance"); @@ -514,46 +489,26 @@ contract RollupTest is RollupBase { // When the block is proven we should have received the funds _submitEpochProofWithFee( - 1, - 1, - blockLog.archive, - data.archive, - data.batchedBlobInputs, - address(42), - header.coinbase, - interim.feeAmount + 1, 1, blockLog.archive, data.archive, data.batchedBlobInputs, address(42), header.coinbase, interim.feeAmount ); { FeeAssetPerEthE9 price = rollup.getFeeAssetPerEth(); - uint256 provingCosts = Math.mulDiv( - EthValue.unwrap(interim.provingCostPerManaInEth), FeeAssetPerEthE9.unwrap(price), 1e9 - ); - assertEq( - provingCosts, - FeeAssetValue.unwrap(interim.provingCostPerManaInFeeAsset), - "invalid proving costs" - ); + uint256 provingCosts = + Math.mulDiv(EthValue.unwrap(interim.provingCostPerManaInEth), FeeAssetPerEthE9.unwrap(price), 1e9); + assertEq(provingCosts, FeeAssetValue.unwrap(interim.provingCostPerManaInFeeAsset), "invalid proving costs"); } - uint256 expectedProverReward = rollup.getBlockReward() / 2 - + FeeAssetValue.unwrap(interim.provingCostPerManaInFeeAsset) * interim.manaUsed; + uint256 expectedProverReward = + rollup.getBlockReward() / 2 + FeeAssetValue.unwrap(interim.provingCostPerManaInFeeAsset) * interim.manaUsed; uint256 expectedSequencerReward = rollup.getBlockReward() / 2 + interim.feeAmount - FeeAssetValue.unwrap(interim.provingCostPerManaInFeeAsset) * interim.manaUsed; - assertEq( - rollup.getSequencerRewards(header.coinbase), - expectedSequencerReward, - "invalid sequencer rewards" - ); + assertEq(rollup.getSequencerRewards(header.coinbase), expectedSequencerReward, "invalid sequencer rewards"); Epoch epoch = rollup.getBlock(1).slotNumber.epochFromSlot(); - assertEq( - rollup.getCollectiveProverRewardsForEpoch(epoch), - expectedProverReward, - "invalid prover rewards" - ); + assertEq(rollup.getCollectiveProverRewardsForEpoch(epoch), expectedProverReward, "invalid prover rewards"); } } @@ -593,10 +548,7 @@ contract RollupTest is RollupBase { assertEq(rollup.getProvenBlockNumber(), _toProve ? 1 : 0, "Invalid proven block number"); } - function testConsecutiveSingleTxBlocks(uint256 _blocksToProve) - public - setUpFor("single_tx_block_1") - { + function testConsecutiveSingleTxBlocks(uint256 _blocksToProve) public setUpFor("single_tx_block_1") { uint256 toProve = bound(_blocksToProve, 0, 2); _proposeBlock("single_tx_block_1", 1); @@ -620,11 +572,8 @@ contract RollupTest is RollupBase { BlockLog memory blockLog = rollup.getBlock(0); - PublicInputArgs memory args = PublicInputArgs({ - previousArchive: blockLog.archive, - endArchive: data.archive, - proverId: address(0) - }); + PublicInputArgs memory args = + PublicInputArgs({previousArchive: blockLog.archive, endArchive: data.archive, proverId: address(0)}); bytes32[] memory fees = new bytes32[](Constants.AZTEC_MAX_EPOCH_DURATION * 2); @@ -634,9 +583,7 @@ contract RollupTest is RollupBase { bytes memory proof = ""; vm.expectRevert( - abi.encodeWithSelector( - Errors.Rollup__StartAndEndNotSameEpoch.selector, Epoch.wrap(0), Epoch.wrap(1) - ) + abi.encodeWithSelector(Errors.Rollup__StartAndEndNotSameEpoch.selector, Epoch.wrap(0), Epoch.wrap(1)) ); rollup.submitEpochRootProof( @@ -675,11 +622,7 @@ contract RollupTest is RollupBase { // Should fail here. _proveBlocksFail( - "mixed_block_", - 2, - 2, - address(0), - abi.encodeWithSelector(Errors.Rollup__StartIsNotFirstBlockOfEpoch.selector) + "mixed_block_", 2, 2, address(0), abi.encodeWithSelector(Errors.Rollup__StartIsNotFirstBlockOfEpoch.selector) ); assertEq(rollup.getPendingBlockNumber(), 2, "Invalid pending block number"); @@ -763,11 +706,7 @@ contract RollupTest is RollupBase { BlockLog memory blockLog = rollup.getBlock(0); bytes32 wrong = bytes32(uint256(0xdeadbeef)); - vm.expectRevert( - abi.encodeWithSelector( - Errors.Rollup__InvalidPreviousArchive.selector, blockLog.archive, wrong - ) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Rollup__InvalidPreviousArchive.selector, blockLog.archive, wrong)); _submitEpochProof(1, 1, wrong, data.archive, data.batchedBlobInputs, address(0)); } @@ -778,9 +717,7 @@ contract RollupTest is RollupBase { bytes32 wrongArchive = bytes32(uint256(0xdeadbeef)); BlockLog memory blockLog = rollup.getBlock(0); - vm.expectRevert( - abi.encodeWithSelector(Errors.Rollup__InvalidArchive.selector, data.archive, 0xdeadbeef) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Rollup__InvalidArchive.selector, data.archive, 0xdeadbeef)); _submitEpochProof(1, 1, blockLog.archive, wrongArchive, data.batchedBlobInputs, address(0)); } @@ -791,7 +728,8 @@ contract RollupTest is RollupBase { bytes memory blobProofInputs = data.batchedBlobInputs; // mess with the data blobProofInputs[100] = 0x01; - // The below is the "blob hash" == bytes [0:32] of batchedBlobInputs = VERSIONED_HASH_VERSION_KZG + sha256(batchedBlobCommitment)[1:] + // The below is the "blob hash" == bytes [0:32] of batchedBlobInputs = VERSIONED_HASH_VERSION_KZG + + // sha256(batchedBlobCommitment)[1:] bytes32 blobHash; assembly { blobHash := mload(add(blobProofInputs, 0x20)) @@ -806,9 +744,11 @@ contract RollupTest is RollupBase { _proposeBlock("mixed_block_1", 1); DecoderBase.Data memory data = load("mixed_block_1").block; - // Set the pending block number to be Constants.AZTEC_MAX_EPOCH_DURATION + 2, so we don't revert early with a different case - stdstore.enable_packed_slots().target(address(rollup)).sig("getPendingBlockNumber()") - .checked_write(Constants.AZTEC_MAX_EPOCH_DURATION + 2); + // Set the pending block number to be Constants.AZTEC_MAX_EPOCH_DURATION + 2, so we don't revert early with a + // different case + stdstore.enable_packed_slots().target(address(rollup)).sig("getPendingBlockNumber()").checked_write( + Constants.AZTEC_MAX_EPOCH_DURATION + 2 + ); BlockLog memory blockLog = rollup.getBlock(0); vm.expectRevert( @@ -819,12 +759,7 @@ contract RollupTest is RollupBase { ) ); _submitEpochProof( - 1, - Constants.AZTEC_MAX_EPOCH_DURATION + 2, - blockLog.archive, - data.archive, - data.batchedBlobInputs, - address(0) + 1, Constants.AZTEC_MAX_EPOCH_DURATION + 2, blockLog.archive, data.archive, data.batchedBlobInputs, address(0) ); } @@ -836,9 +771,7 @@ contract RollupTest is RollupBase { bytes memory _blobInputs, address _prover ) internal { - _submitEpochProofWithFee( - _start, _end, _prevArchive, _archive, _blobInputs, _prover, address(0), 0 - ); + _submitEpochProofWithFee(_start, _end, _prevArchive, _archive, _blobInputs, _prover, address(0), 0); } function _submitEpochProofWithFee( diff --git a/l1-contracts/test/RollupGetters.t.sol b/l1-contracts/test/RollupGetters.t.sol index a5b051ac4f83..d2e7fcc62141 100644 --- a/l1-contracts/test/RollupGetters.t.sol +++ b/l1-contracts/test/RollupGetters.t.sol @@ -280,17 +280,9 @@ contract RollupShouldBeGetters is ValidatorSelectionTestBase { blockReward: 100e18 }); - assertNotEq( - address(config.rewardDistributor), - address(updated.rewardDistributor), - "invalid reward distributor" - ); + assertNotEq(address(config.rewardDistributor), address(updated.rewardDistributor), "invalid reward distributor"); assertNotEq(address(config.booster), address(updated.booster), "invalid booster"); - assertEq( - Bps.unwrap(config.sequencerBps), - Bps.unwrap(defaultConfig.sequencerBps), - "invalid sequencerBps" - ); + assertEq(Bps.unwrap(config.sequencerBps), Bps.unwrap(defaultConfig.sequencerBps), "invalid sequencerBps"); assertEq(config.blockReward, defaultConfig.blockReward, "invalid initial blockReward"); address owner = rollup.owner(); @@ -301,14 +293,8 @@ contract RollupShouldBeGetters is ValidatorSelectionTestBase { rollup.setRewardConfig(updated); config = rollup.getRewardConfig(); - assertEq( - Bps.unwrap(config.sequencerBps), Bps.unwrap(updated.sequencerBps), "invalid sequencerBps" - ); - assertEq( - address(config.rewardDistributor), - address(updated.rewardDistributor), - "invalid reward distributor" - ); + assertEq(Bps.unwrap(config.sequencerBps), Bps.unwrap(updated.sequencerBps), "invalid sequencerBps"); + assertEq(address(config.rewardDistributor), address(updated.rewardDistributor), "invalid reward distributor"); assertEq(address(config.booster), address(updated.booster), "invalid booster"); assertEq(config.blockReward, updated.blockReward, "invalid blockReward"); } diff --git a/l1-contracts/test/base/Base.sol b/l1-contracts/test/base/Base.sol index a787ef3639e9..b3077e9a67a4 100644 --- a/l1-contracts/test/base/Base.sol +++ b/l1-contracts/test/base/Base.sol @@ -4,9 +4,7 @@ pragma solidity >=0.8.27; import {Timestamp, Slot, Epoch} from "@aztec/core/libraries/TimeLib.sol"; import {Test} from "forge-std/Test.sol"; import {stdStorage, StdStorage} from "forge-std/Test.sol"; -import { - AttesterView, Exit, Status, AttesterConfig -} from "@aztec/core/libraries/rollup/StakingLib.sol"; +import {AttesterView, Exit, Status, AttesterConfig} from "@aztec/core/libraries/rollup/StakingLib.sol"; import { AppendOnlyTreeSnapshot, PartialStateReference, diff --git a/l1-contracts/test/base/DecoderBase.sol b/l1-contracts/test/base/DecoderBase.sol index 4b70d8037c3e..23782ae90ec4 100644 --- a/l1-contracts/test/base/DecoderBase.sol +++ b/l1-contracts/test/base/DecoderBase.sol @@ -5,11 +5,7 @@ pragma solidity >=0.8.27; import {TestBase} from "../base/Base.sol"; import {Timestamp, Slot} from "@aztec/core/libraries/TimeLib.sol"; -import { - ProposedHeader, - ContentCommitment, - GasFees -} from "@aztec/core/libraries/rollup/ProposedHeaderLib.sol"; +import {ProposedHeader, ContentCommitment, GasFees} from "@aztec/core/libraries/rollup/ProposedHeaderLib.sol"; import {ProposedHeaderLib} from "@aztec/core/libraries/rollup/ProposedHeaderLib.sol"; // Many of the structs in here match what you see in `header` but with very important exceptions! @@ -62,9 +58,11 @@ contract DecoderBase is TestBase { struct Data { bytes32 archive; - // Note: batchedBlobInputs is usually per epoch, rather than per block. For testing, these batchedBlobInputs assume that + // Note: batchedBlobInputs is usually per epoch, rather than per block. For testing, these batchedBlobInputs assume + // that // an epoch contains blobs including and up to the 'current' block. - // e.g. mixed_block_2's batchedBlobInputs assumes that the epoch consists of 2 blocks, mixed_block_1 and mixed_block_2, and their blobs. + // e.g. mixed_block_2's batchedBlobInputs assumes that the epoch consists of 2 blocks, mixed_block_1 and + // mixed_block_2, and their blobs. // e.g. mixed_block_1's batchedBlobInputs assumes the epoch contains only mixed_block_1 and its blob(s). bytes batchedBlobInputs; // EVM point evaluation precompile inputs for verifying an epoch's batch of blobs bytes blobCommitments; // [numBlobs, ...blobCommitments], used in proposing blocks @@ -96,11 +94,7 @@ contract DecoderBase is TestBase { } // Decode does not support the custom types - function fromAlphabeticalToNormal(AlphabeticalFull memory full) - internal - pure - returns (Full memory) - { + function fromAlphabeticalToNormal(AlphabeticalFull memory full) internal pure returns (Full memory) { Full memory result = Full({ block: Data({ archive: full.block.archive, @@ -129,9 +123,7 @@ contract DecoderBase is TestBase { populate: full.populate }); - assertEq( - result.block.headerHash, result.block.header.hash(), "headerHash mismatch when loading" - ); + assertEq(result.block.headerHash, result.block.header.hash(), "headerHash mismatch when loading"); return result; } diff --git a/l1-contracts/test/base/RollupBase.sol b/l1-contracts/test/base/RollupBase.sol index 1c9ccde254da..56b436373dca 100644 --- a/l1-contracts/test/base/RollupBase.sol +++ b/l1-contracts/test/base/RollupBase.sol @@ -4,12 +4,7 @@ pragma solidity >=0.8.27; import {DecoderBase} from "./DecoderBase.sol"; import {IInstance} from "@aztec/core/interfaces/IInstance.sol"; -import { - IRollup, - BlockLog, - SubmitEpochRootProofArgs, - PublicInputArgs -} from "@aztec/core/interfaces/IRollup.sol"; +import {IRollup, BlockLog, SubmitEpochRootProofArgs, PublicInputArgs} from "@aztec/core/interfaces/IRollup.sol"; import {Constants} from "@aztec/core/libraries/ConstantsGen.sol"; import {CommitteeAttestations} from "@aztec/shared/libraries/SignatureLib.sol"; import {Strings} from "@oz/utils/Strings.sol"; @@ -21,11 +16,7 @@ import {Timestamp, Slot, Epoch, TimeLib} from "@aztec/core/libraries/TimeLib.sol import {DataStructures} from "@aztec/core/libraries/DataStructures.sol"; import {BlobLib} from "@aztec/core/libraries/rollup/BlobLib.sol"; import {ProposeArgs, OracleInput, ProposeLib} from "@aztec/core/libraries/rollup/ProposeLib.sol"; -import { - CommitteeAttestation, - CommitteeAttestations, - SignatureLib -} from "@aztec/shared/libraries/SignatureLib.sol"; +import {CommitteeAttestation, CommitteeAttestations, SignatureLib} from "@aztec/shared/libraries/SignatureLib.sol"; import {Inbox} from "@aztec/core/messagebridge/Inbox.sol"; import {Outbox} from "@aztec/core/messagebridge/Outbox.sol"; @@ -40,29 +31,19 @@ contract RollupBase is DecoderBase { mapping(uint256 => uint256) internal blockFees; - function _proveBlocks(string memory _name, uint256 _start, uint256 _end, address _prover) - internal - { + function _proveBlocks(string memory _name, uint256 _start, uint256 _end, address _prover) internal { _proveBlocks(_name, _start, _end, _prover, ""); } - function _proveBlocksFail( - string memory _name, - uint256 _start, - uint256 _end, - address _prover, - bytes memory _revertMsg - ) internal { + function _proveBlocksFail(string memory _name, uint256 _start, uint256 _end, address _prover, bytes memory _revertMsg) + internal + { _proveBlocks(_name, _start, _end, _prover, _revertMsg); } - function _proveBlocks( - string memory _name, - uint256 _start, - uint256 _end, - address _prover, - bytes memory _revertMsg - ) private { + function _proveBlocks(string memory _name, uint256 _start, uint256 _end, address _prover, bytes memory _revertMsg) + private + { DecoderBase.Full memory startFull = load(string.concat(_name, Strings.toString(_start))); DecoderBase.Full memory endFull = load(string.concat(_name, Strings.toString(_end))); @@ -76,17 +57,15 @@ contract RollupBase is DecoderBase { // What are these even? // ^ public inputs to the root proof? - PublicInputArgs memory args = PublicInputArgs({ - previousArchive: parentBlockLog.archive, - endArchive: endFull.block.archive, - proverId: _prover - }); + PublicInputArgs memory args = + PublicInputArgs({previousArchive: parentBlockLog.archive, endArchive: endFull.block.archive, proverId: _prover}); bytes32[] memory fees = new bytes32[](Constants.AZTEC_MAX_EPOCH_DURATION * 2); uint256 size = endBlockNumber - startBlockNumber + 1; for (uint256 i = 0; i < size; i++) { - fees[i * 2] = bytes32(uint256(uint160(bytes20(("sequencer"))))); // Need the address to be left padded within the bytes32 + fees[i * 2] = bytes32(uint256(uint160(bytes20(("sequencer"))))); // Need the address to be left padded within the + // bytes32 fees[i * 2 + 1] = bytes32(uint256(blockFees[startBlockNumber + i])); } @@ -118,12 +97,9 @@ contract RollupBase is DecoderBase { _proposeBlock(_name, _slotNumber, _manaUsed, extraBlobHashes, ""); } - function _proposeBlockFail( - string memory _name, - uint256 _slotNumber, - uint256 _manaUsed, - bytes memory _revertMsg - ) public { + function _proposeBlockFail(string memory _name, uint256 _slotNumber, uint256 _manaUsed, bytes memory _revertMsg) + public + { bytes32[] memory extraBlobHashes = new bytes32[](0); _proposeBlock(_name, _slotNumber, _manaUsed, extraBlobHashes, _revertMsg); } @@ -224,8 +200,7 @@ contract RollupBase is DecoderBase { uint256 subTreeHeight = full.messages.l2ToL1Messages.length == 0 ? 0 : merkleTestUtil.calculateTreeHeightFromSize(full.messages.l2ToL1Messages.length / numTxs); - uint256 outHashTreeHeight = - numTxs == 1 ? 0 : merkleTestUtil.calculateTreeHeightFromSize(numTxs); + uint256 outHashTreeHeight = numTxs == 1 ? 0 : merkleTestUtil.calculateTreeHeightFromSize(numTxs); uint256 numMessagesWithPadding = numTxs * Constants.MAX_L2_TO_L1_MSGS_PER_TX; uint256 treeHeight = subTreeHeight + outHashTreeHeight; @@ -265,17 +240,11 @@ contract RollupBase is DecoderBase { for (uint256 i = 0; i < _contents.length; i++) { vm.prank(_sender); - inbox.sendL2Message( - DataStructures.L2Actor({actor: _recipient, version: version}), _contents[i], bytes32(0) - ); + inbox.sendL2Message(DataStructures.L2Actor({actor: _recipient, version: version}), _contents[i], bytes32(0)); } } - function getBlobHashes(bytes calldata _blobCommitments) - public - pure - returns (bytes32[] memory blobHashes) - { + function getBlobHashes(bytes calldata _blobCommitments) public pure returns (bytes32[] memory blobHashes) { uint8 numBlobs = uint8(_blobCommitments[0]); blobHashes = new bytes32[](numBlobs); // Add 1 for the numBlobs prefix @@ -283,9 +252,7 @@ contract RollupBase is DecoderBase { for (uint256 i = 0; i < numBlobs; i++) { // blobInputs = [numBlobs, ...blobCommitments], numBlobs is one byte, each commitment is 48 blobHashes[i] = BlobLib.calculateBlobHash( - abi.encodePacked( - _blobCommitments[blobInputStart:blobInputStart + Constants.BLS12_POINT_COMPRESSED_BYTES] - ) + abi.encodePacked(_blobCommitments[blobInputStart:blobInputStart + Constants.BLS12_POINT_COMPRESSED_BYTES]) ); blobInputStart += Constants.BLS12_POINT_COMPRESSED_BYTES; } diff --git a/l1-contracts/test/benchmark/Multicall3.sol b/l1-contracts/test/benchmark/Multicall3.sol index e00df0a58c4b..18a9bb4aac16 100644 --- a/l1-contracts/test/benchmark/Multicall3.sol +++ b/l1-contracts/test/benchmark/Multicall3.sol @@ -38,11 +38,7 @@ contract Multicall3 { /// @param calls An array of Call structs /// @return blockNumber The block number where the calls were executed /// @return returnData An array of bytes containing the responses - function aggregate(Call[] calldata calls) - public - payable - returns (uint256 blockNumber, bytes[] memory returnData) - { + function aggregate(Call[] calldata calls) public payable returns (uint256 blockNumber, bytes[] memory returnData) { blockNumber = block.number; uint256 length = calls.length; returnData = new bytes[](length); @@ -63,11 +59,7 @@ contract Multicall3 { /// @param requireSuccess If true, require all calls to succeed /// @param calls An array of Call structs /// @return returnData An array of Result structs - function tryAggregate(bool requireSuccess, Call[] calldata calls) - public - payable - returns (Result[] memory returnData) - { + function tryAggregate(bool requireSuccess, Call[] calldata calls) public payable returns (Result[] memory returnData) { uint256 length = calls.length; returnData = new Result[](length); Call calldata call; @@ -148,11 +140,7 @@ contract Multicall3 { /// @notice Reverts if msg.value is less than the sum of the call values /// @param calls An array of Call3Value structs /// @return returnData An array of Result structs - function aggregate3Value(Call3Value[] calldata calls) - public - payable - returns (Result[] memory returnData) - { + function aggregate3Value(Call3Value[] calldata calls) public payable returns (Result[] memory returnData) { uint256 valAccumulator; uint256 length = calls.length; returnData = new Result[](length); diff --git a/l1-contracts/test/benchmark/happy.t.sol b/l1-contracts/test/benchmark/happy.t.sol index ef062c4e551a..fc5ae5c55173 100644 --- a/l1-contracts/test/benchmark/happy.t.sol +++ b/l1-contracts/test/benchmark/happy.t.sol @@ -41,12 +41,7 @@ import {IFeeJuicePortal} from "@aztec/core/interfaces/IFeeJuicePortal.sol"; import {IRewardDistributor} from "@aztec/governance/interfaces/IRewardDistributor.sol"; import {IRegistry} from "@aztec/governance/interfaces/IRegistry.sol"; import {ProposedHeaderLib} from "@aztec/core/libraries/rollup/ProposedHeaderLib.sol"; -import { - ProposeArgs, - ProposePayload, - OracleInput, - ProposeLib -} from "@aztec/core/libraries/rollup/ProposeLib.sol"; +import {ProposeArgs, ProposePayload, OracleInput, ProposeLib} from "@aztec/core/libraries/rollup/ProposeLib.sol"; import {IERC20} from "@oz/token/ERC20/IERC20.sol"; import { FeeLib, @@ -57,10 +52,7 @@ import { ManaBaseFeeComponents } from "@aztec/core/libraries/rollup/FeeLib.sol"; import { - FeeModelTestPoints, - TestPoint, - FeeHeaderModel, - ManaBaseFeeComponentsModel + FeeModelTestPoints, TestPoint, FeeHeaderModel, ManaBaseFeeComponentsModel } from "test/fees/FeeModelTestPoints.t.sol"; import {MessageHashUtils} from "@oz/utils/cryptography/MessageHashUtils.sol"; import {Timestamp, Slot, Epoch, TimeLib} from "@aztec/core/libraries/TimeLib.sol"; @@ -161,12 +153,12 @@ contract BenchmarkRollupTest is FeeModelTestPoints, DecoderBase { StakingQueueConfig memory stakingQueueConfig = TestConstants.getStakingQueueConfig(); stakingQueueConfig.normalFlushSizeMin = _validatorCount; - RollupBuilder builder = new RollupBuilder(address(this)).setProvingCostPerMana(provingCost) - .setManaTarget(MANA_TARGET).setSlotDuration(SLOT_DURATION).setEpochDuration(EPOCH_DURATION) - .setMintFeeAmount(1e30).setValidators(initialValidators).setTargetCommitteeSize( - _noValidators ? 0 : TARGET_COMMITTEE_SIZE - ).setStakingQueueConfig(stakingQueueConfig).setSlashingQuorum(VOTING_ROUND_SIZE) - .setSlashingRoundSize(VOTING_ROUND_SIZE); + RollupBuilder builder = new RollupBuilder(address(this)).setProvingCostPerMana(provingCost).setManaTarget( + MANA_TARGET + ).setSlotDuration(SLOT_DURATION).setEpochDuration(EPOCH_DURATION).setMintFeeAmount(1e30).setValidators( + initialValidators + ).setTargetCommitteeSize(_noValidators ? 0 : TARGET_COMMITTEE_SIZE).setStakingQueueConfig(stakingQueueConfig) + .setSlashingQuorum(VOTING_ROUND_SIZE).setSlashingRoundSize(VOTING_ROUND_SIZE); builder.deploy(); asset = builder.getConfig().testERC20; @@ -250,8 +242,7 @@ contract BenchmarkRollupTest is FeeModelTestPoints, DecoderBase { Timestamp ts = rollup.getTimestampForSlot(slotNumber); - uint128 manaBaseFee = - SafeCast.toUint128(rollup.getManaBaseFeeAt(Timestamp.wrap(block.timestamp), true)); + uint128 manaBaseFee = SafeCast.toUint128(rollup.getManaBaseFeeAt(Timestamp.wrap(block.timestamp), true)); uint256 manaSpent = point.block_header.mana_spent; address proposer = rollup.getCurrentProposer(); @@ -331,11 +322,7 @@ contract BenchmarkRollupTest is FeeModelTestPoints, DecoderBase { }); } - function createAttestation(address _signer, bytes32 _digest) - internal - view - returns (CommitteeAttestation memory) - { + function createAttestation(address _signer, bytes32 _digest) internal view returns (CommitteeAttestation memory) { uint256 privateKey = attesterPrivateKeys[_signer]; bytes32 digest = _digest.toEthSignedMessageHash(); @@ -346,12 +333,9 @@ contract BenchmarkRollupTest is FeeModelTestPoints, DecoderBase { return CommitteeAttestation({addr: _signer, signature: signature}); } - // This is used for attestations that are not signed - we include their address to help reconstruct the committee commitment - function createEmptyAttestation(address _signer) - internal - pure - returns (CommitteeAttestation memory) - { + // This is used for attestations that are not signed - we include their address to help reconstruct the committee + // commitment + function createEmptyAttestation(address _signer) internal pure returns (CommitteeAttestation memory) { Signature memory emptySignature = Signature({v: 0, r: 0, s: 0}); return CommitteeAttestation({addr: _signer, signature: emptySignature}); } @@ -418,8 +402,7 @@ contract BenchmarkRollupTest is FeeModelTestPoints, DecoderBase { calls[0] = Multicall3.Call3({ target: address(rollup), callData: abi.encodeCall( - rollup.propose, - (b.proposeArgs, SignatureLib.packAttestations(b.attestations), b.signers, b.blobInputs) + rollup.propose, (b.proposeArgs, SignatureLib.packAttestations(b.attestations), b.signers, b.blobInputs) ), allowFailure: false }); diff --git a/l1-contracts/test/boosted_rewards/BoostRewardHelper.sol b/l1-contracts/test/boosted_rewards/BoostRewardHelper.sol index 0d669eb024be..7466344ba713 100644 --- a/l1-contracts/test/boosted_rewards/BoostRewardHelper.sol +++ b/l1-contracts/test/boosted_rewards/BoostRewardHelper.sol @@ -17,9 +17,7 @@ contract BoostedHelper is RewardBooster { using SafeCast for uint256; using CompressedTimeMath for Epoch; - constructor(IValidatorSelection _rollup, RewardBoostConfig memory _config) - RewardBooster(_rollup, _config) - {} + constructor(IValidatorSelection _rollup, RewardBoostConfig memory _config) RewardBooster(_rollup, _config) {} // Usually we would be using cheatcodes directly, but with this in particular, it seems like the cheatcodes // is not having a good time and we end up overflowing it. Therefore we just update it directly instead diff --git a/l1-contracts/test/builder/GseBuilder.sol b/l1-contracts/test/builder/GseBuilder.sol index 9b8207e3a302..80d16e812daa 100644 --- a/l1-contracts/test/builder/GseBuilder.sol +++ b/l1-contracts/test/builder/GseBuilder.sol @@ -65,12 +65,8 @@ contract GSEBuilder is TestBase { } if (address(config.gse) == address(0)) { - config.gse = new GSE( - address(this), - config.testERC20, - TestConstants.ACTIVATION_THRESHOLD, - TestConstants.EJECTION_THRESHOLD - ); + config.gse = + new GSE(address(this), config.testERC20, TestConstants.ACTIVATION_THRESHOLD, TestConstants.EJECTION_THRESHOLD); vm.label(address(config.gse), "GSE"); } @@ -81,14 +77,10 @@ contract GSEBuilder is TestBase { vm.label(address(config.rewardDistributor), "RewardDistributor"); } - GovernanceProposer proposer = new GovernanceProposer( - config.registry, config.gse, config.values.govProposerN, config.values.govProposerM - ); + GovernanceProposer proposer = + new GovernanceProposer(config.registry, config.gse, config.values.govProposerN, config.values.govProposerM); config.governance = new Governance( - config.testERC20, - address(proposer), - address(config.gse), - TestConstants.getGovernanceConfiguration() + config.testERC20, address(proposer), address(config.gse), TestConstants.getGovernanceConfiguration() ); vm.label(address(config.governance), "Governance"); vm.label(address(proposer), "GovernanceProposer"); diff --git a/l1-contracts/test/builder/RollupBuilder.sol b/l1-contracts/test/builder/RollupBuilder.sol index 4a2625df143c..f4e2636d057b 100644 --- a/l1-contracts/test/builder/RollupBuilder.sol +++ b/l1-contracts/test/builder/RollupBuilder.sol @@ -92,18 +92,12 @@ contract RollupBuilder is Test { return this; } - function setRollupConfigInput(RollupConfigInput memory _rollupConfigInput) - public - returns (RollupBuilder) - { + function setRollupConfigInput(RollupConfigInput memory _rollupConfigInput) public returns (RollupBuilder) { config.rollupConfigInput = _rollupConfigInput; return this; } - function setRewardDistributor(RewardDistributor _rewardDistributor) - public - returns (RollupBuilder) - { + function setRewardDistributor(RewardDistributor _rewardDistributor) public returns (RollupBuilder) { config.rewardDistributor = _rewardDistributor; return this; } @@ -182,18 +176,12 @@ contract RollupBuilder is Test { return this; } - function setSlashingLifetimeInRounds(uint256 _slashingLifetimeInRounds) - public - returns (RollupBuilder) - { + function setSlashingLifetimeInRounds(uint256 _slashingLifetimeInRounds) public returns (RollupBuilder) { config.rollupConfigInput.slashingLifetimeInRounds = _slashingLifetimeInRounds; return this; } - function setSlashingExecutionDelayInRounds(uint256 _slashingExecutionDelayInRounds) - public - returns (RollupBuilder) - { + function setSlashingExecutionDelayInRounds(uint256 _slashingExecutionDelayInRounds) public returns (RollupBuilder) { config.rollupConfigInput.slashingExecutionDelayInRounds = _slashingExecutionDelayInRounds; return this; } @@ -203,10 +191,7 @@ contract RollupBuilder is Test { return this; } - function setStakingQueueConfig(StakingQueueConfig memory _stakingQueueConfig) - public - returns (RollupBuilder) - { + function setStakingQueueConfig(StakingQueueConfig memory _stakingQueueConfig) public returns (RollupBuilder) { config.rollupConfigInput.stakingQueueConfig = _stakingQueueConfig; return this; } @@ -232,12 +217,8 @@ contract RollupBuilder is Test { } if (address(config.gse) == address(0)) { - config.gse = new GSE( - address(this), - config.testERC20, - TestConstants.ACTIVATION_THRESHOLD, - TestConstants.EJECTION_THRESHOLD - ); + config.gse = + new GSE(address(this), config.testERC20, TestConstants.ACTIVATION_THRESHOLD, TestConstants.EJECTION_THRESHOLD); } if (address(config.registry) == address(0)) { @@ -248,14 +229,10 @@ contract RollupBuilder is Test { } if (config.flags.makeGovernance) { - GovernanceProposer proposer = new GovernanceProposer( - config.registry, config.gse, config.values.govProposerN, config.values.govProposerM - ); + GovernanceProposer proposer = + new GovernanceProposer(config.registry, config.gse, config.values.govProposerN, config.values.govProposerM); config.governance = new Governance( - config.testERC20, - address(proposer), - address(config.gse), - TestConstants.getGovernanceConfiguration() + config.testERC20, address(proposer), address(config.gse), TestConstants.getGovernanceConfiguration() ); vm.label(address(config.governance), "Governance"); vm.label(address(proposer), "GovernanceProposer"); @@ -302,9 +279,7 @@ contract RollupBuilder is Test { if (config.validators.length > 0) { MultiAdder multiAdder = new MultiAdder(address(config.rollup), address(this)); - config.testERC20.mint( - address(multiAdder), config.gse.ACTIVATION_THRESHOLD() * config.validators.length - ); + config.testERC20.mint(address(multiAdder), config.gse.ACTIVATION_THRESHOLD() * config.validators.length); multiAdder.addValidators(config.validators); } diff --git a/l1-contracts/test/compression/FeeConfig.t.sol b/l1-contracts/test/compression/FeeConfig.t.sol index 3b132159bef0..bbcc4ababb46 100644 --- a/l1-contracts/test/compression/FeeConfig.t.sol +++ b/l1-contracts/test/compression/FeeConfig.t.sol @@ -14,11 +14,10 @@ contract FeeConfigTest is Test { using FeeConfigLib for FeeConfig; using FeeConfigLib for CompressedFeeConfig; - function test_compressAndDecompress( - uint64 _manaTarget, - uint128 _congestionUpdateFraction, - uint64 _provingCostPerMana - ) public pure { + function test_compressAndDecompress(uint64 _manaTarget, uint128 _congestionUpdateFraction, uint64 _provingCostPerMana) + public + pure + { FeeConfig memory a = FeeConfig({ manaTarget: _manaTarget, congestionUpdateFraction: _congestionUpdateFraction, @@ -29,20 +28,10 @@ contract FeeConfigTest is Test { assertEq(c.manaTarget, a.manaTarget, "Mana target"); assertEq(c.congestionUpdateFraction, a.congestionUpdateFraction, "Congestion update fraction"); - assertEq( - EthValue.unwrap(c.provingCostPerMana), - EthValue.unwrap(a.provingCostPerMana), - "Proving cost per mana" - ); + assertEq(EthValue.unwrap(c.provingCostPerMana), EthValue.unwrap(a.provingCostPerMana), "Proving cost per mana"); assertEq(b.getManaTarget(), a.manaTarget, "Mana target"); - assertEq( - b.getCongestionUpdateFraction(), a.congestionUpdateFraction, "Congestion update fraction" - ); - assertEq( - EthValue.unwrap(b.getProvingCostPerMana()), - EthValue.unwrap(a.provingCostPerMana), - "Proving cost per mana" - ); + assertEq(b.getCongestionUpdateFraction(), a.congestionUpdateFraction, "Congestion update fraction"); + assertEq(EthValue.unwrap(b.getProvingCostPerMana()), EthValue.unwrap(a.provingCostPerMana), "Proving cost per mana"); } } diff --git a/l1-contracts/test/compression/FeeStructs.t.sol b/l1-contracts/test/compression/FeeStructs.t.sol index 8a4f987153c1..35b23bfca10c 100644 --- a/l1-contracts/test/compression/FeeStructs.t.sol +++ b/l1-contracts/test/compression/FeeStructs.t.sol @@ -3,11 +3,7 @@ pragma solidity >=0.8.27; import {Test} from "forge-std/Test.sol"; -import { - FeeHeader, - CompressedFeeHeader, - FeeHeaderLib -} from "@aztec/core/libraries/compressed-data/fees/FeeStructs.sol"; +import {FeeHeader, CompressedFeeHeader, FeeHeaderLib} from "@aztec/core/libraries/compressed-data/fees/FeeStructs.sol"; contract FeeStructsTest is Test { using FeeHeaderLib for FeeHeader; @@ -43,9 +39,7 @@ contract FeeStructsTest is Test { feeHeader.feeAssetPriceNumerator, "Getter Fee asset price numerator" ); - assertEq( - compressedFeeHeader.getCongestionCost(), feeHeader.congestionCost, "Getter Congestion cost" - ); + assertEq(compressedFeeHeader.getCongestionCost(), feeHeader.congestionCost, "Getter Congestion cost"); assertEq(compressedFeeHeader.getProverCost(), feeHeader.proverCost, "Getter Prover cost"); // Checke the decompressed value @@ -56,9 +50,7 @@ contract FeeStructsTest is Test { feeHeader.feeAssetPriceNumerator, "Decompressed Fee asset price numerator" ); - assertEq( - decompressedFeeHeader.congestionCost, feeHeader.congestionCost, "Decompressed Congestion cost" - ); + assertEq(decompressedFeeHeader.congestionCost, feeHeader.congestionCost, "Decompressed Congestion cost"); assertEq(decompressedFeeHeader.proverCost, feeHeader.proverCost, "Decompressed Prover cost"); } } diff --git a/l1-contracts/test/compression/PreHeating.t.sol b/l1-contracts/test/compression/PreHeating.t.sol index 1cd04b29322b..0715d20adb03 100644 --- a/l1-contracts/test/compression/PreHeating.t.sol +++ b/l1-contracts/test/compression/PreHeating.t.sol @@ -40,12 +40,7 @@ import {IFeeJuicePortal} from "@aztec/core/interfaces/IFeeJuicePortal.sol"; import {IRewardDistributor} from "@aztec/governance/interfaces/IRewardDistributor.sol"; import {IRegistry} from "@aztec/governance/interfaces/IRegistry.sol"; import {ProposedHeaderLib} from "@aztec/core/libraries/rollup/ProposedHeaderLib.sol"; -import { - ProposeArgs, - ProposePayload, - OracleInput, - ProposeLib -} from "@aztec/core/libraries/rollup/ProposeLib.sol"; +import {ProposeArgs, ProposePayload, OracleInput, ProposeLib} from "@aztec/core/libraries/rollup/ProposeLib.sol"; import {IERC20} from "@oz/token/ERC20/IERC20.sol"; import { FeeLib, @@ -56,10 +51,7 @@ import { ManaBaseFeeComponents } from "@aztec/core/libraries/rollup/FeeLib.sol"; import { - FeeModelTestPoints, - TestPoint, - FeeHeaderModel, - ManaBaseFeeComponentsModel + FeeModelTestPoints, TestPoint, FeeHeaderModel, ManaBaseFeeComponentsModel } from "test/fees/FeeModelTestPoints.t.sol"; import {MessageHashUtils} from "@oz/utils/cryptography/MessageHashUtils.sol"; import {Timestamp, Slot, Epoch, TimeLib} from "@aztec/core/libraries/TimeLib.sol"; @@ -159,12 +151,13 @@ contract PreHeatingTest is FeeModelTestPoints, DecoderBase { StakingQueueConfig memory stakingQueueConfig = TestConstants.getStakingQueueConfig(); stakingQueueConfig.normalFlushSizeMin = _validatorCount; - RollupBuilder builder = new RollupBuilder(address(this)).setProvingCostPerMana(provingCost) - .setManaTarget(MANA_TARGET).setSlotDuration(SLOT_DURATION).setEpochDuration(EPOCH_DURATION) - .setMintFeeAmount(1e30).setValidators(initialValidators).setTargetCommitteeSize( - _targetCommitteeSize - ).setStakingQueueConfig(stakingQueueConfig).setSlashingQuorum(VOTING_ROUND_SIZE) - .setSlashingRoundSize(VOTING_ROUND_SIZE); + RollupBuilder builder = new RollupBuilder(address(this)).setProvingCostPerMana(provingCost).setManaTarget( + MANA_TARGET + ).setSlotDuration(SLOT_DURATION).setEpochDuration(EPOCH_DURATION).setMintFeeAmount(1e30).setValidators( + initialValidators + ).setTargetCommitteeSize(_targetCommitteeSize).setStakingQueueConfig(stakingQueueConfig).setSlashingQuorum( + VOTING_ROUND_SIZE + ).setSlashingRoundSize(VOTING_ROUND_SIZE); builder.deploy(); asset = builder.getConfig().testERC20; @@ -234,9 +227,7 @@ contract PreHeatingTest is FeeModelTestPoints, DecoderBase { blockAttestations[currentBlockNumber] = SignatureLib.packAttestations(b.attestations); vm.prank(proposer); - rollup.propose( - b.proposeArgs, SignatureLib.packAttestations(b.attestations), b.signers, b.blobInputs - ); + rollup.propose(b.proposeArgs, SignatureLib.packAttestations(b.attestations), b.signers, b.blobInputs); nextSlot = nextSlot + Slot.wrap(1); } @@ -315,8 +306,7 @@ contract PreHeatingTest is FeeModelTestPoints, DecoderBase { Timestamp ts = rollup.getTimestampForSlot(slotNumber); - uint128 manaBaseFee = - SafeCast.toUint128(rollup.getManaBaseFeeAt(Timestamp.wrap(block.timestamp), true)); + uint128 manaBaseFee = SafeCast.toUint128(rollup.getManaBaseFeeAt(Timestamp.wrap(block.timestamp), true)); uint256 manaSpent = point.block_header.mana_spent; address proposer = rollup.getCurrentProposer(); @@ -392,11 +382,7 @@ contract PreHeatingTest is FeeModelTestPoints, DecoderBase { }); } - function createAttestation(address _signer, bytes32 _digest) - internal - view - returns (CommitteeAttestation memory) - { + function createAttestation(address _signer, bytes32 _digest) internal view returns (CommitteeAttestation memory) { uint256 privateKey = attesterPrivateKeys[_signer]; bytes32 digest = _digest.toEthSignedMessageHash(); @@ -407,12 +393,9 @@ contract PreHeatingTest is FeeModelTestPoints, DecoderBase { return CommitteeAttestation({addr: _signer, signature: signature}); } - // This is used for attestations that are not signed - we include their address to help reconstruct the committee commitment - function createEmptyAttestation(address _signer) - internal - pure - returns (CommitteeAttestation memory) - { + // This is used for attestations that are not signed - we include their address to help reconstruct the committee + // commitment + function createEmptyAttestation(address _signer) internal pure returns (CommitteeAttestation memory) { Signature memory emptySignature = Signature({v: 0, r: 0, s: 0}); return CommitteeAttestation({addr: _signer, signature: emptySignature}); } diff --git a/l1-contracts/test/compression/StakingQueueConfig.t.sol b/l1-contracts/test/compression/StakingQueueConfig.t.sol index 4dd4fc33743a..f8066edbdef4 100644 --- a/l1-contracts/test/compression/StakingQueueConfig.t.sol +++ b/l1-contracts/test/compression/StakingQueueConfig.t.sol @@ -29,9 +29,7 @@ contract StakingQueueConfigTest is Test { CompressedStakingQueueConfig b = a.compress(); StakingQueueConfig memory c = b.decompress(); - assertEq( - c.bootstrapValidatorSetSize, a.bootstrapValidatorSetSize, "Bootstrap validator set size" - ); + assertEq(c.bootstrapValidatorSetSize, a.bootstrapValidatorSetSize, "Bootstrap validator set size"); assertEq(c.bootstrapFlushSize, a.bootstrapFlushSize, "Bootstrap flush size"); assertEq(c.normalFlushSizeMin, a.normalFlushSizeMin, "Normal flush size min"); assertEq(c.normalFlushSizeQuotient, a.normalFlushSizeQuotient, "Normal flush size quotient"); diff --git a/l1-contracts/test/compression/Tips.t.sol b/l1-contracts/test/compression/Tips.t.sol index 6be85ab237f5..606f1b4c3143 100644 --- a/l1-contracts/test/compression/Tips.t.sol +++ b/l1-contracts/test/compression/Tips.t.sol @@ -3,56 +3,29 @@ pragma solidity >=0.8.27; import {Test} from "forge-std/Test.sol"; -import { - ChainTips, - CompressedChainTips, - ChainTipsLib -} from "@aztec/core/libraries/compressed-data/Tips.sol"; +import {ChainTips, CompressedChainTips, ChainTipsLib} from "@aztec/core/libraries/compressed-data/Tips.sol"; contract TipsTest is Test { using ChainTipsLib for CompressedChainTips; using ChainTipsLib for ChainTips; - function test_compress_uncompress(uint128 _pendingBlockNumber, uint128 _provenBlockNumber) - public - pure - { + function test_compress_uncompress(uint128 _pendingBlockNumber, uint128 _provenBlockNumber) public pure { ChainTips memory chainTips = ChainTips({pendingBlockNumber: _pendingBlockNumber, provenBlockNumber: _provenBlockNumber}); CompressedChainTips compressedChainTips = chainTips.compress(); ChainTips memory decompressedChainTips = compressedChainTips.decompress(); - assertEq( - compressedChainTips.getPendingBlockNumber(), - chainTips.pendingBlockNumber, - "getPendingBlockNumber" - ); - assertEq( - compressedChainTips.getProvenBlockNumber(), - chainTips.provenBlockNumber, - "getProvenBlockNumber" - ); + assertEq(compressedChainTips.getPendingBlockNumber(), chainTips.pendingBlockNumber, "getPendingBlockNumber"); + assertEq(compressedChainTips.getProvenBlockNumber(), chainTips.provenBlockNumber, "getProvenBlockNumber"); - assertEq( - decompressedChainTips.pendingBlockNumber, - chainTips.pendingBlockNumber, - "decompressed pendingBlockNumber" - ); - assertEq( - decompressedChainTips.provenBlockNumber, - chainTips.provenBlockNumber, - "decompressed provenBlockNumber" - ); + assertEq(decompressedChainTips.pendingBlockNumber, chainTips.pendingBlockNumber, "decompressed pendingBlockNumber"); + assertEq(decompressedChainTips.provenBlockNumber, chainTips.provenBlockNumber, "decompressed provenBlockNumber"); } - function test_updatePendingBlockNumber(uint128 _pendingBlockNumber, uint128 _provenBlockNumber) - public - pure - { + function test_updatePendingBlockNumber(uint128 _pendingBlockNumber, uint128 _provenBlockNumber) public pure { uint256 pendingBlockNumber = bound(_pendingBlockNumber, 0, type(uint128).max - 1); - ChainTips memory a = - ChainTips({pendingBlockNumber: pendingBlockNumber, provenBlockNumber: _provenBlockNumber}); + ChainTips memory a = ChainTips({pendingBlockNumber: pendingBlockNumber, provenBlockNumber: _provenBlockNumber}); CompressedChainTips b = a.compress(); CompressedChainTips c = b.updatePendingBlockNumber(pendingBlockNumber + 1); @@ -60,19 +33,13 @@ contract TipsTest is Test { assertEq(c.getPendingBlockNumber(), pendingBlockNumber + 1, "c.getPendingBlockNumber"); assertEq(c.getProvenBlockNumber(), _provenBlockNumber, "c.getProvenBlockNumber"); assertEq( - c.getPendingBlockNumber(), - b.getPendingBlockNumber() + 1, - "c.getPendingBlockNumber != b.getPendingBlockNumber + 1" + c.getPendingBlockNumber(), b.getPendingBlockNumber() + 1, "c.getPendingBlockNumber != b.getPendingBlockNumber + 1" ); } - function test_updateProvenBlockNumber(uint128 _pendingBlockNumber, uint128 _provenBlockNumber) - public - pure - { + function test_updateProvenBlockNumber(uint128 _pendingBlockNumber, uint128 _provenBlockNumber) public pure { uint256 provenBlockNumber = bound(_provenBlockNumber, 0, type(uint128).max - 1); - ChainTips memory a = - ChainTips({pendingBlockNumber: _pendingBlockNumber, provenBlockNumber: provenBlockNumber}); + ChainTips memory a = ChainTips({pendingBlockNumber: _pendingBlockNumber, provenBlockNumber: provenBlockNumber}); CompressedChainTips b = a.compress(); CompressedChainTips c = b.updateProvenBlockNumber(provenBlockNumber + 1); @@ -80,9 +47,7 @@ contract TipsTest is Test { assertEq(c.getPendingBlockNumber(), _pendingBlockNumber, "c.getPendingBlockNumber"); assertEq(c.getProvenBlockNumber(), provenBlockNumber + 1, "c.getProvenBlockNumber"); assertEq( - c.getProvenBlockNumber(), - b.getProvenBlockNumber() + 1, - "c.getProvenBlockNumber != b.getProvenBlockNumber + 1" + c.getProvenBlockNumber(), b.getProvenBlockNumber() + 1, "c.getProvenBlockNumber != b.getProvenBlockNumber + 1" ); } } diff --git a/l1-contracts/test/delegation/base.t.sol b/l1-contracts/test/delegation/base.t.sol index 0a767037a61f..1257d235fca0 100644 --- a/l1-contracts/test/delegation/base.t.sol +++ b/l1-contracts/test/delegation/base.t.sol @@ -22,8 +22,8 @@ contract GSEBase is TestBase { uint256 internal EPOCH_DURATION_SECONDS; function setUp() public virtual { - RollupBuilder builder = new RollupBuilder(address(this)).setSlashingQuorum(1) - .setSlashingRoundSize(1).setEpochDuration(1).setSlotDuration(1); + RollupBuilder builder = new RollupBuilder(address(this)).setSlashingQuorum(1).setSlashingRoundSize(1) + .setEpochDuration(1).setSlotDuration(1); builder.deploy(); registry = builder.getConfig().registry; @@ -32,8 +32,8 @@ contract GSEBase is TestBase { gse = builder.getConfig().gse; governance = builder.getConfig().governance; - EPOCH_DURATION_SECONDS = builder.getConfig().rollupConfigInput.aztecEpochDuration - * builder.getConfig().rollupConfigInput.aztecSlotDuration; + EPOCH_DURATION_SECONDS = + builder.getConfig().rollupConfigInput.aztecEpochDuration * builder.getConfig().rollupConfigInput.aztecSlotDuration; vm.label(address(governance), "governance"); vm.label(address(governance.governanceProposer()), "governance proposer"); @@ -43,9 +43,7 @@ contract GSEBase is TestBase { vm.label(address(registry), "registry"); } - function help__deposit(address _attester, address _withdrawer, bool _moveWithLatestRollup) - internal - { + function help__deposit(address _attester, address _withdrawer, bool _moveWithLatestRollup) internal { uint256 activationThreshold = ROLLUP.getActivationThreshold(); vm.prank(stakingAsset.owner()); stakingAsset.mint(address(this), activationThreshold); @@ -53,18 +51,10 @@ contract GSEBase is TestBase { uint256 balance = stakingAsset.balanceOf(address(governance)); - ROLLUP.deposit({ - _attester: _attester, - _withdrawer: _withdrawer, - _moveWithLatestRollup: _moveWithLatestRollup - }); + ROLLUP.deposit({_attester: _attester, _withdrawer: _withdrawer, _moveWithLatestRollup: _moveWithLatestRollup}); ROLLUP.flushEntryQueue(); - assertEq( - stakingAsset.balanceOf(address(governance)), - balance + activationThreshold, - "invalid gov balance" - ); + assertEq(stakingAsset.balanceOf(address(governance)), balance + activationThreshold, "invalid gov balance"); assertEq(stakingAsset.balanceOf(address(ROLLUP)), 0, "invalid rollup balance"); } } diff --git a/l1-contracts/test/delegation/minimal.t.sol b/l1-contracts/test/delegation/minimal.t.sol index ee77ba0f4567..9a01b9c018c5 100644 --- a/l1-contracts/test/delegation/minimal.t.sol +++ b/l1-contracts/test/delegation/minimal.t.sol @@ -50,13 +50,10 @@ contract MinimalDelegationTest is GSEBase { uint256 proposalId = governance.propose(IPayload(address(ROLLUP))); // Useless payload, just to get it in there. // Fake it till you make it - stdstore.target(proposer).sig("getProposalProposer(uint256)").with_key(proposalId).checked_write( - address(ROLLUP) - ); + stdstore.target(proposer).sig("getProposalProposer(uint256)").with_key(proposalId).checked_write(address(ROLLUP)); assertEq(GovernanceProposer(proposer).getProposalProposer(proposalId), address(ROLLUP)); - uint256 votingTime = - Timestamp.unwrap(ProposalLib.pendingThroughMemory(governance.getProposal(0))); + uint256 votingTime = Timestamp.unwrap(ProposalLib.pendingThroughMemory(governance.getProposal(0))); Timestamps memory ts; @@ -86,12 +83,8 @@ contract MinimalDelegationTest is GSEBase { vm.warp(ts.ts4); _checkInstanceCanonical(address(ROLLUP), 0, activationThreshold, Timestamp.wrap(ts.ts1)); - _checkInstanceCanonical( - address(ROLLUP), activationThreshold, activationThreshold, Timestamp.wrap(ts.ts2) - ); - _checkInstanceCanonical( - address(ROLLUP), activationThreshold, activationThreshold * 2, Timestamp.wrap(ts.ts3) - ); + _checkInstanceCanonical(address(ROLLUP), activationThreshold, activationThreshold, Timestamp.wrap(ts.ts2)); + _checkInstanceCanonical(address(ROLLUP), activationThreshold, activationThreshold * 2, Timestamp.wrap(ts.ts3)); assertEq(gse.getVotingPower(ATTESTER1), 0, "voting power user"); assertEq(gse.getVotingPower(ATTESTER2), 0, "voting power user"); @@ -138,19 +131,13 @@ contract MinimalDelegationTest is GSEBase { _checkInstanceCanonical(address(ROLLUP), 0, activationThreshold, Timestamp.wrap(ts.ts1)); _checkInstanceNonCanonical(address(dead), 0, Timestamp.wrap(ts.ts1)); - _checkInstanceCanonical( - address(ROLLUP), activationThreshold, activationThreshold, Timestamp.wrap(ts.ts2) - ); + _checkInstanceCanonical(address(ROLLUP), activationThreshold, activationThreshold, Timestamp.wrap(ts.ts2)); _checkInstanceNonCanonical(address(dead), 0, Timestamp.wrap(ts.ts2)); - _checkInstanceCanonical( - address(ROLLUP), activationThreshold, activationThreshold * 2, Timestamp.wrap(ts.ts3) - ); + _checkInstanceCanonical(address(ROLLUP), activationThreshold, activationThreshold * 2, Timestamp.wrap(ts.ts3)); _checkInstanceNonCanonical(address(dead), 0, Timestamp.wrap(ts.ts3)); - _checkInstanceCanonical( - address(ROLLUP), activationThreshold, activationThreshold, Timestamp.wrap(ts.ts4) - ); + _checkInstanceCanonical(address(ROLLUP), activationThreshold, activationThreshold, Timestamp.wrap(ts.ts4)); _checkInstanceNonCanonical(address(dead), 0, Timestamp.wrap(ts.ts4)); _checkInstanceNonCanonical(address(ROLLUP), activationThreshold, Timestamp.wrap(ts.ts5)); @@ -176,9 +163,7 @@ contract MinimalDelegationTest is GSEBase { // But if updated, we should instead break and explode! if (_updateRegistry) { - vm.expectRevert( - abi.encodeWithSelector(Errors.Staking__NotCanonical.selector, address(ROLLUP)) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Staking__NotCanonical.selector, address(ROLLUP))); } else { vm.expectEmit(true, true, true, true, address(governance)); emit IGovernance.VoteCast(proposalId, address(gse), true, activationThreshold); @@ -200,10 +185,7 @@ contract MinimalDelegationTest is GSEBase { vm.prank(address(ROLLUP)); vm.expectRevert( abi.encodeWithSelector( - GovErrors.Delegation__InsufficientPower.selector, - address(ROLLUP), - activationThreshold, - activationThreshold * 2 + GovErrors.Delegation__InsufficientPower.selector, address(ROLLUP), activationThreshold, activationThreshold * 2 ) ); gse.vote(proposalId, powerToVoteSelf, true); @@ -248,30 +230,22 @@ contract MinimalDelegationTest is GSEBase { assertEq(governance.getProposal(proposalId).summedBallot.nay, 0, "nays"); } - function _checkPowerUsed(address _delegatee, uint256 _used, uint256 _power, uint256 _votingTime) - internal - view - { + function _checkPowerUsed(address _delegatee, uint256 _used, uint256 _power, uint256 _votingTime) internal view { uint256 proposalId = 0; assertEq(gse.getPowerUsed(_delegatee, proposalId), _used, "power used"); assertEq(gse.getVotingPowerAt(_delegatee, Timestamp.wrap(_votingTime)), _power, "voting power"); } - function _checkInstanceCanonical( - address _instance, - uint256 _specific, - uint256 _canonical, - Timestamp _ts - ) internal view { + function _checkInstanceCanonical(address _instance, uint256 _specific, uint256 _canonical, Timestamp _ts) + internal + view + { assertEq(gse.getVotingPowerAt(bonus, _ts), _canonical, "voting power bonus"); assertEq(gse.getVotingPowerAt(_instance, _ts), _specific, "voting power specific"); assertEq(_instance, gse.getLatestRollupAt(_ts), "instance != bonus"); } - function _checkInstanceNonCanonical(address _instance, uint256 _specific, Timestamp _ts) - internal - view - { + function _checkInstanceNonCanonical(address _instance, uint256 _specific, Timestamp _ts) internal view { assertEq(gse.getVotingPowerAt(_instance, _ts), _specific, "voting power specific"); assertNotEq(_instance, gse.getLatestRollupAt(_ts), "instance == canonical"); } diff --git a/l1-contracts/test/external/ISwapRouter.sol b/l1-contracts/test/external/ISwapRouter.sol index daf041a19f0f..bbd4f682f18c 100644 --- a/l1-contracts/test/external/ISwapRouter.sol +++ b/l1-contracts/test/external/ISwapRouter.sol @@ -20,10 +20,7 @@ interface ISwapRouter { /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token - function exactInputSingle(ExactInputSingleParams calldata params) - external - payable - returns (uint256 amountOut); + function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; @@ -36,10 +33,7 @@ interface ISwapRouter { /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token - function exactInput(ExactInputParams calldata params) - external - payable - returns (uint256 amountOut); + function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; @@ -55,10 +49,7 @@ interface ISwapRouter { /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token - function exactOutputSingle(ExactOutputSingleParams calldata params) - external - payable - returns (uint256 amountIn); + function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; @@ -71,9 +62,6 @@ interface ISwapRouter { /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token - function exactOutput(ExactOutputParams calldata params) - external - payable - returns (uint256 amountIn); + function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // docs:end:iswaprouter diff --git a/l1-contracts/test/fee_portal/depositToAztecPublic.t.sol b/l1-contracts/test/fee_portal/depositToAztecPublic.t.sol index 8fcf19ccf10c..6389a145f318 100644 --- a/l1-contracts/test/fee_portal/depositToAztecPublic.t.sol +++ b/l1-contracts/test/fee_portal/depositToAztecPublic.t.sol @@ -44,16 +44,12 @@ contract DepositToAztecPublic is Test { function test_RevertGiven_InsufficientBalance() external { // it should revert vm.expectRevert( - abi.encodeWithSelector( - IERC20Errors.ERC20InsufficientAllowance.selector, address(feeJuicePortal), 0, 1 - ) + abi.encodeWithSelector(IERC20Errors.ERC20InsufficientAllowance.selector, address(feeJuicePortal), 0, 1) ); feeJuicePortal.depositToAztecPublic(bytes32(0x0), 1, bytes32(0x0)); token.approve(address(feeJuicePortal), 1); - vm.expectRevert( - abi.encodeWithSelector(IERC20Errors.ERC20InsufficientBalance.selector, address(this), 0, 1) - ); + vm.expectRevert(abi.encodeWithSelector(IERC20Errors.ERC20InsufficientBalance.selector, address(this), 0, 1)); feeJuicePortal.depositToAztecPublic(bytes32(0x0), 1, bytes32(0x0)); } @@ -90,8 +86,7 @@ contract DepositToAztecPublic is Test { Inbox inbox = Inbox(address(Rollup(address(registry.getCanonicalRollup())).getInbox())); assertEq(inbox.getTotalMessagesInserted(), 0); - bytes16 expectedHash = - bytes16(keccak256(abi.encodePacked(inbox.getState().rollingHash, expectedKey))); + bytes16 expectedHash = bytes16(keccak256(abi.encodePacked(inbox.getState().rollingHash, expectedKey))); vm.expectEmit(true, true, true, true, address(inbox)); emit IInbox.MessageSent(2, expectedIndex, expectedKey, expectedHash); vm.expectEmit(true, true, true, true, address(feeJuicePortal)); diff --git a/l1-contracts/test/fee_portal/distributeFees.t.sol b/l1-contracts/test/fee_portal/distributeFees.t.sol index 4977ced5373c..047377b7a40d 100644 --- a/l1-contracts/test/fee_portal/distributeFees.t.sol +++ b/l1-contracts/test/fee_portal/distributeFees.t.sol @@ -50,9 +50,7 @@ contract DistributeFees is Test { // it should revert vm.prank(address(rollup)); vm.expectRevert( - abi.encodeWithSelector( - IERC20Errors.ERC20InsufficientBalance.selector, address(feeJuicePortal), 0, 0 + 1 - ) + abi.encodeWithSelector(IERC20Errors.ERC20InsufficientBalance.selector, address(feeJuicePortal), 0, 0 + 1) ); feeJuicePortal.distributeFees(address(this), 1); } diff --git a/l1-contracts/test/fees/FeeModelTestPoints.t.sol b/l1-contracts/test/fees/FeeModelTestPoints.t.sol index 64b892f8bf83..0dba4dd2b27c 100644 --- a/l1-contracts/test/fees/FeeModelTestPoints.t.sol +++ b/l1-contracts/test/fees/FeeModelTestPoints.t.sol @@ -112,10 +112,7 @@ contract FeeModelTestPoints is TestBase { assertEq(a.blob_fee, b.blob_fee, "blob_fee mismatch"); } - function assertEq(L1FeesModel memory a, L1FeesModel memory b, string memory _message) - internal - pure - { + function assertEq(L1FeesModel memory a, L1FeesModel memory b, string memory _message) internal pure { assertEq(a.base_fee, b.base_fee, string.concat(_message, "base_fee mismatch")); assertEq(a.blob_fee, b.blob_fee, string.concat(_message, "blob_fee mismatch")); } @@ -127,35 +124,24 @@ contract FeeModelTestPoints is TestBase { } function assertEq(OracleInputModel memory a, OracleInput memory b) internal pure { - assertEq( - a.fee_asset_price_modifier, b.feeAssetPriceModifier, "fee_asset_price_modifier mismatch" - ); + assertEq(a.fee_asset_price_modifier, b.feeAssetPriceModifier, "fee_asset_price_modifier mismatch"); } function assertEq(FeeHeaderModel memory a, FeeHeaderModel memory b) internal pure { assertEq(a.excess_mana, b.excess_mana, "excess_mana mismatch"); - assertEq( - a.fee_asset_price_numerator, b.fee_asset_price_numerator, "fee_asset_price_numerator mismatch" - ); + assertEq(a.fee_asset_price_numerator, b.fee_asset_price_numerator, "fee_asset_price_numerator mismatch"); assertEq(a.mana_used, b.mana_used, "mana_used mismatch"); } - function assertEq( - ManaBaseFeeComponentsModel memory a, - ManaBaseFeeComponentsModel memory b, - string memory _message - ) internal pure { - assertEq( - a.congestion_cost, b.congestion_cost, string.concat(_message, " congestion_cost mismatch") - ); + function assertEq(ManaBaseFeeComponentsModel memory a, ManaBaseFeeComponentsModel memory b, string memory _message) + internal + pure + { + assertEq(a.congestion_cost, b.congestion_cost, string.concat(_message, " congestion_cost mismatch")); assertEq( - a.congestion_multiplier, - b.congestion_multiplier, - string.concat(_message, " congestion_multiplier mismatch") + a.congestion_multiplier, b.congestion_multiplier, string.concat(_message, " congestion_multiplier mismatch") ); assertEq(a.prover_cost, b.prover_cost, string.concat(_message, " prover_cost mismatch")); - assertEq( - a.sequencer_cost, b.sequencer_cost, string.concat(_message, " sequencer_cost mismatch") - ); + assertEq(a.sequencer_cost, b.sequencer_cost, string.concat(_message, " sequencer_cost mismatch")); } } diff --git a/l1-contracts/test/fees/FeeRollup.t.sol b/l1-contracts/test/fees/FeeRollup.t.sol index c0ba794edea1..11a24537f9cf 100644 --- a/l1-contracts/test/fees/FeeRollup.t.sol +++ b/l1-contracts/test/fees/FeeRollup.t.sol @@ -23,10 +23,7 @@ import {Outbox} from "@aztec/core/messagebridge/Outbox.sol"; import {Errors} from "@aztec/core/libraries/Errors.sol"; import {Rollup, BlockLog} from "@aztec/core/Rollup.sol"; import { - IRollup, - SubmitEpochRootProofArgs, - PublicInputArgs, - RollupConfigInput + IRollup, SubmitEpochRootProofArgs, PublicInputArgs, RollupConfigInput } from "@aztec/core/interfaces/IRollup.sol"; import {FeeJuicePortal} from "@aztec/core/messagebridge/FeeJuicePortal.sol"; import {NaiveMerkle} from "../merkle/Naive.sol"; @@ -50,12 +47,7 @@ import { } from "@aztec/core/libraries/rollup/FeeLib.sol"; import {Math} from "@oz/utils/math/Math.sol"; -import { - FeeModelTestPoints, - TestPoint, - FeeHeaderModel, - ManaBaseFeeComponentsModel -} from "./FeeModelTestPoints.t.sol"; +import {FeeModelTestPoints, TestPoint, FeeHeaderModel, ManaBaseFeeComponentsModel} from "./FeeModelTestPoints.t.sol"; import {Timestamp, Slot, Epoch} from "@aztec/core/libraries/TimeLib.sol"; import {ProposedHeader} from "@aztec/core/libraries/rollup/ProposedHeaderLib.sol"; @@ -65,7 +57,7 @@ import {RollupBuilder} from "../builder/RollupBuilder.sol"; // solhint-disable comprehensive-interface -uint256 constant MANA_TARGET = 100000000; +uint256 constant MANA_TARGET = 100_000_000; contract FeeRollupTest is FeeModelTestPoints, DecoderBase { using stdStorage for StdStorage; @@ -106,9 +98,9 @@ contract FeeRollupTest is FeeModelTestPoints, DecoderBase { vm.fee(l1Metadata[0].base_fee); vm.blobBaseFee(l1Metadata[0].blob_fee); - RollupBuilder builder = new RollupBuilder(address(this)).setProvingCostPerMana(provingCost) - .setManaTarget(MANA_TARGET).setSlotDuration(SLOT_DURATION).setEpochDuration(EPOCH_DURATION) - .setMintFeeAmount(1e30).setTargetCommitteeSize(0); + RollupBuilder builder = new RollupBuilder(address(this)).setProvingCostPerMana(provingCost).setManaTarget( + MANA_TARGET + ).setSlotDuration(SLOT_DURATION).setEpochDuration(EPOCH_DURATION).setMintFeeAmount(1e30).setTargetCommitteeSize(0); builder.deploy(); rollup = builder.getConfig().rollup; @@ -155,11 +147,7 @@ contract FeeRollupTest is FeeModelTestPoints, DecoderBase { + point.outputs.mana_base_fee_components_in_fee_asset.congestion_cost ); - assertEq( - rollup.getManaBaseFeeAt(Timestamp.wrap(block.timestamp), true), - manaBaseFee, - "mana base fee mismatch" - ); + assertEq(rollup.getManaBaseFeeAt(Timestamp.wrap(block.timestamp), true), manaBaseFee, "mana base fee mismatch"); uint256 manaSpent = point.block_header.mana_spent; @@ -201,9 +189,7 @@ contract FeeRollupTest is FeeModelTestPoints, DecoderBase { header: b.header, archive: b.archive, stateReference: EMPTY_STATE_REFERENCE, - oracleInput: OracleInput({ - feeAssetPriceModifier: point.oracle_input.fee_asset_price_modifier - }) + oracleInput: OracleInput({feeAssetPriceModifier: point.oracle_input.fee_asset_price_modifier}) }), SignatureLib.packAttestations(b.attestations), b.signers, @@ -214,13 +200,12 @@ contract FeeRollupTest is FeeModelTestPoints, DecoderBase { } FeeHeader memory parentFeeHeaderNoPrune = rollup.getFeeHeader(rollup.getPendingBlockNumber()); - uint256 excessManaNoPrune = ( - parentFeeHeaderNoPrune.excessMana + parentFeeHeaderNoPrune.manaUsed - ).clampedAdd(-int256(MANA_TARGET)); + uint256 excessManaNoPrune = + (parentFeeHeaderNoPrune.excessMana + parentFeeHeaderNoPrune.manaUsed).clampedAdd(-int256(MANA_TARGET)); FeeHeader memory parentFeeHeaderPrune = rollup.getFeeHeader(rollup.getProvenBlockNumber()); - uint256 excessManaPrune = (parentFeeHeaderPrune.excessMana + parentFeeHeaderPrune.manaUsed) - .clampedAdd(-int256(MANA_TARGET)); + uint256 excessManaPrune = + (parentFeeHeaderPrune.excessMana + parentFeeHeaderPrune.manaUsed).clampedAdd(-int256(MANA_TARGET)); assertGt(excessManaNoPrune, excessManaPrune, "excess mana should be lower if we prune"); @@ -231,12 +216,12 @@ contract FeeRollupTest is FeeModelTestPoints, DecoderBase { timeOfPrune += SLOT_DURATION; } - ManaBaseFeeComponents memory componentsPrune = - rollup.getManaBaseFeeComponentsAt(Timestamp.wrap(timeOfPrune), true); + ManaBaseFeeComponents memory componentsPrune = rollup.getManaBaseFeeComponentsAt(Timestamp.wrap(timeOfPrune), true); // If we assume that everything is proven, we will see what the fee would be if we did not prune. - stdstore.enable_packed_slots().target(address(rollup)).sig("getProvenBlockNumber()") - .checked_write(rollup.getPendingBlockNumber()); + stdstore.enable_packed_slots().target(address(rollup)).sig("getProvenBlockNumber()").checked_write( + rollup.getPendingBlockNumber() + ); ManaBaseFeeComponents memory componentsNoPrune = rollup.getManaBaseFeeComponentsAt(Timestamp.wrap(timeOfPrune), true); @@ -268,8 +253,7 @@ contract FeeRollupTest is FeeModelTestPoints, DecoderBase { // Loop through all of the L1 metadata for (uint256 i = 0; i < l1Metadata.length; i++) { // Predict what the fee will be before we jump in time! - uint256 baseFeePrediction = - rollup.getManaBaseFeeAt(Timestamp.wrap(l1Metadata[i].timestamp), true); + uint256 baseFeePrediction = rollup.getManaBaseFeeAt(Timestamp.wrap(l1Metadata[i].timestamp), true); _loadL1Metadata(i); @@ -296,9 +280,7 @@ contract FeeRollupTest is FeeModelTestPoints, DecoderBase { header: b.header, archive: b.archive, stateReference: EMPTY_STATE_REFERENCE, - oracleInput: OracleInput({ - feeAssetPriceModifier: point.oracle_input.fee_asset_price_modifier - }) + oracleInput: OracleInput({feeAssetPriceModifier: point.oracle_input.fee_asset_price_modifier}) }), SignatureLib.packAttestations(b.attestations), b.signers, @@ -309,9 +291,7 @@ contract FeeRollupTest is FeeModelTestPoints, DecoderBase { assertEq(baseFeePrediction, componentsFeeAsset.summedBaseFee(), "mana base fee mismatch"); - assertEq( - componentsFeeAsset.congestionCost, feeHeader.congestionCost, "congestion cost mismatch" - ); + assertEq(componentsFeeAsset.congestionCost, feeHeader.congestionCost, "congestion cost mismatch"); // Want to check the fee header to see if they are as we want them. assertEq(point.block_header.block_number, nextSlot, "invalid l2 block number"); @@ -321,16 +301,12 @@ contract FeeRollupTest is FeeModelTestPoints, DecoderBase { assertEq(point.fee_header, feeHeader); - assertEq( - point.outputs.fee_asset_price_at_execution, feeAssetPrice, "fee asset price mismatch" - ); + assertEq(point.outputs.fee_asset_price_at_execution, feeAssetPrice, "fee asset price mismatch"); assertEq(point.outputs.l1_fee_oracle_output.base_fee, fees.baseFee, "base fee mismatch"); assertEq(point.outputs.l1_fee_oracle_output.blob_fee, fees.blobFee, "blob fee mismatch"); assertEq(point.outputs.mana_base_fee_components_in_wei, components, "in_wei"); - assertEq( - point.outputs.mana_base_fee_components_in_fee_asset, componentsFeeAsset, "in_fee_asset" - ); + assertEq(point.outputs.mana_base_fee_components_in_fee_asset, componentsFeeAsset, "in_fee_asset"); assertEq(point.parent_fee_header, parentFeeHeader); @@ -367,13 +343,11 @@ contract FeeRollupTest is FeeModelTestPoints, DecoderBase { uint256 manaUsed = rollup.getFeeHeader(start + feeIndex).manaUsed; uint256 fee = manaUsed * baseFee; - uint256 burn = - manaUsed * point.outputs.mana_base_fee_components_in_fee_asset.congestion_cost; + uint256 burn = manaUsed * point.outputs.mana_base_fee_components_in_fee_asset.congestion_cost; burnSum += burn; - uint256 proverFee = Math.min( - manaUsed * point.outputs.mana_base_fee_components_in_fee_asset.prover_cost, fee - burn - ); + uint256 proverFee = + Math.min(manaUsed * point.outputs.mana_base_fee_components_in_fee_asset.prover_cost, fee - burn); proverFees += proverFee; sequencerFees += (fee - burn - proverFee); @@ -410,11 +384,7 @@ contract FeeRollupTest is FeeModelTestPoints, DecoderBase { // The reward is not yet distributed, but only accumulated. { uint256 newFees = rollup.getBlockReward() * epochSize / 2 + sequencerFees; - assertEq( - rollup.getSequencerRewards(coinbase), - sequencerRewardsBefore + newFees, - "sequencer rewards" - ); + assertEq(rollup.getSequencerRewards(coinbase), sequencerRewardsBefore + newFees, "sequencer rewards"); } { assertEq( @@ -436,11 +406,10 @@ contract FeeRollupTest is FeeModelTestPoints, DecoderBase { assertEq(a, bModel); } - function assertEq( - ManaBaseFeeComponentsModel memory a, - ManaBaseFeeComponents memory b, - string memory _message - ) internal pure { + function assertEq(ManaBaseFeeComponentsModel memory a, ManaBaseFeeComponents memory b, string memory _message) + internal + pure + { ManaBaseFeeComponentsModel memory bModel = ManaBaseFeeComponentsModel({ congestion_cost: b.congestionCost, congestion_multiplier: b.congestionMultiplier, diff --git a/l1-contracts/test/fees/MinimalFeeModel.sol b/l1-contracts/test/fees/MinimalFeeModel.sol index 63a2701533e7..15eb50f145f0 100644 --- a/l1-contracts/test/fees/MinimalFeeModel.sol +++ b/l1-contracts/test/fees/MinimalFeeModel.sol @@ -22,10 +22,7 @@ import { } from "@aztec/core/libraries/rollup/FeeLib.sol"; import {Vm} from "forge-std/Vm.sol"; import { - ManaBaseFeeComponentsModel, - L1FeesModel, - L1GasOracleValuesModel, - FeeHeaderModel + ManaBaseFeeComponentsModel, L1FeesModel, L1GasOracleValuesModel, FeeHeaderModel } from "./FeeModelTestPoints.t.sol"; import {Math} from "@oz/utils/math/Math.sol"; import {CompressedSlot, CompressedTimeMath} from "@aztec/shared/libraries/CompressedTimeMath.sol"; @@ -53,7 +50,7 @@ contract MinimalFeeModel { uint256 internal constant BLOB_GAS_PER_BLOB = 2 ** 17; uint256 internal constant GAS_PER_BLOB_POINT_EVALUATION = 50_000; - uint256 internal constant MANA_TARGET = 100000000; + uint256 internal constant MANA_TARGET = 100_000_000; Slot public constant LIFETIME = Slot.wrap(5); Slot public constant LAG = Slot.wrap(2); @@ -64,11 +61,7 @@ contract MinimalFeeModel { TimeLib.initialize(block.timestamp, _slotDuration, _epochDuration, _proofSubmissionEpochs); FeeLib.initialize(MANA_TARGET, EthValue.wrap(100)); STFLib.initialize( - GenesisState({ - vkTreeRoot: bytes32(0), - protocolContractTreeRoot: bytes32(0), - genesisArchiveRoot: bytes32(0) - }) + GenesisState({vkTreeRoot: bytes32(0), protocolContractTreeRoot: bytes32(0), genesisArchiveRoot: bytes32(0)}) ); } @@ -82,14 +75,9 @@ contract MinimalFeeModel { } // For all of the estimations we have been using `3` blobs. - function manaBaseFeeComponents(bool _inFeeAsset) - public - view - returns (ManaBaseFeeComponentsModel memory) - { - ManaBaseFeeComponents memory components = FeeLib.getManaBaseFeeComponentsAt( - populatedThrough, Timestamp.wrap(block.timestamp), _inFeeAsset - ); + function manaBaseFeeComponents(bool _inFeeAsset) public view returns (ManaBaseFeeComponentsModel memory) { + ManaBaseFeeComponents memory components = + FeeLib.getManaBaseFeeComponentsAt(populatedThrough, Timestamp.wrap(block.timestamp), _inFeeAsset); return ManaBaseFeeComponentsModel({ congestion_cost: components.congestionCost, @@ -123,9 +111,7 @@ contract MinimalFeeModel { attestationsHash: bytes32(0), payloadDigest: bytes32(0), slotNumber: Slot.wrap(0), - feeHeader: FeeLib.computeFeeHeader( - blockNumber, _oracleInput.feeAssetPriceModifier, _manaUsed, 0, 0 - ) + feeHeader: FeeLib.computeFeeHeader(blockNumber, _oracleInput.feeAssetPriceModifier, _manaUsed, 0, 0) }) ); // FeeLib.writeFeeHeader(++populatedThrough, _oracleInput.feeAssetPriceModifier, _manaUsed, 0, 0); diff --git a/l1-contracts/test/fees/MinimalFeeModel.t.sol b/l1-contracts/test/fees/MinimalFeeModel.t.sol index 8539ed2e5145..612c734ccc08 100644 --- a/l1-contracts/test/fees/MinimalFeeModel.t.sol +++ b/l1-contracts/test/fees/MinimalFeeModel.t.sol @@ -59,9 +59,7 @@ contract MinimalFeeModelTest is FeeModelTestPoints { points[i].outputs.fee_asset_price_at_execution, "Computed fee asset price does not match expected value" ); - model.addSlot( - OracleInput({feeAssetPriceModifier: points[i].oracle_input.fee_asset_price_modifier}) - ); + model.addSlot(OracleInput({feeAssetPriceModifier: points[i].oracle_input.fee_asset_price_modifier})); } } @@ -93,9 +91,7 @@ contract MinimalFeeModelTest is FeeModelTestPoints { L1FeesModel memory fees = model.getCurrentL1Fees(); assertEq(expected.block_header.l1_block_number, block.number, "invalid l1 block number"); - assertEq( - expected.block_header.block_number, Slot.unwrap(nextSlot), "invalid l2 block number" - ); + assertEq(expected.block_header.block_number, Slot.unwrap(nextSlot), "invalid l2 block number"); assertEq(expected.block_header.slot_number, Slot.unwrap(nextSlot), "invalid l2 slot number"); assertEq(expected.outputs.l1_fee_oracle_output.base_fee, fees.base_fee, "baseFee mismatch"); assertEq(expected.outputs.l1_fee_oracle_output.blob_fee, fees.blob_fee, "blobFee mismatch"); @@ -124,8 +120,7 @@ contract MinimalFeeModelTest is FeeModelTestPoints { // 3 blobs because that can fit ~360 txs, or 10 tps. ManaBaseFeeComponentsModel memory components = model.manaBaseFeeComponents(false); ManaBaseFeeComponentsModel memory componentsFeeAsset = model.manaBaseFeeComponents(true); - FeeHeaderModel memory parentFeeHeader = - model.getFeeHeader(point.block_header.slot_number - 1); + FeeHeaderModel memory parentFeeHeader = model.getFeeHeader(point.block_header.slot_number - 1); model.addSlot( OracleInput({feeAssetPriceModifier: point.oracle_input.fee_asset_price_modifier}), @@ -145,15 +140,11 @@ contract MinimalFeeModelTest is FeeModelTestPoints { assertEq(point.fee_header, feeHeader); - assertEq( - point.outputs.fee_asset_price_at_execution, feeAssetPrice, "feeAssetPrice mismatch" - ); + assertEq(point.outputs.fee_asset_price_at_execution, feeAssetPrice, "feeAssetPrice mismatch"); assertEq(point.outputs.l1_fee_oracle_output, fees, "l1 fee oracle output"); assertEq(point.outputs.l1_gas_oracle_values, model.getL1GasOracleValues()); assertEq(point.outputs.mana_base_fee_components_in_wei, components, "in_wei"); - assertEq( - point.outputs.mana_base_fee_components_in_fee_asset, componentsFeeAsset, "in_fee_asset" - ); + assertEq(point.outputs.mana_base_fee_components_in_fee_asset, componentsFeeAsset, "in_fee_asset"); assertEq(point.parent_fee_header, parentFeeHeader); diff --git a/l1-contracts/test/governance/coin-issuer/mint.t.sol b/l1-contracts/test/governance/coin-issuer/mint.t.sol index 229d2f52d91d..7602196c93c6 100644 --- a/l1-contracts/test/governance/coin-issuer/mint.t.sol +++ b/l1-contracts/test/governance/coin-issuer/mint.t.sol @@ -34,9 +34,7 @@ contract MintTest is CoinIssuerBase { function test_GivenAmountLargerThanMaxMint(uint256 _amount) external givenCallerIsOwner { // it reverts uint256 amount = bound(_amount, maxMint + 1, type(uint256).max); - vm.expectRevert( - abi.encodeWithSelector(Errors.CoinIssuer__InsufficientMintAvailable.selector, maxMint, amount) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.CoinIssuer__InsufficientMintAvailable.selector, maxMint, amount)); nom.mint(address(0xdead), amount); } diff --git a/l1-contracts/test/governance/governance-proposer/constructor.t.sol b/l1-contracts/test/governance/governance-proposer/constructor.t.sol index d7ee8f7a17c3..eba26de3ebb0 100644 --- a/l1-contracts/test/governance/governance-proposer/constructor.t.sol +++ b/l1-contracts/test/governance/governance-proposer/constructor.t.sol @@ -26,9 +26,7 @@ contract ConstructorTest is Test { uint256 n = bound(_n, 0, _m / 2); - vm.expectRevert( - abi.encodeWithSelector(Errors.GovernanceProposer__InvalidQuorumAndRoundSize.selector, n, _m) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GovernanceProposer__InvalidQuorumAndRoundSize.selector, n, _m)); new GovernanceProposer(REGISTRY, GSE, n, _m); } @@ -37,11 +35,7 @@ contract ConstructorTest is Test { uint256 m = bound(_m, 0, type(uint256).max - 1); uint256 n = bound(_n, m + 1, type(uint256).max); - vm.expectRevert( - abi.encodeWithSelector( - Errors.GovernanceProposer__QuorumCannotBeLargerThanRoundSize.selector, n, m - ) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GovernanceProposer__QuorumCannotBeLargerThanRoundSize.selector, n, m)); new GovernanceProposer(REGISTRY, GSE, n, m); } diff --git a/l1-contracts/test/governance/governance-proposer/scenario/15123.t.sol b/l1-contracts/test/governance/governance-proposer/scenario/15123.t.sol index 126d86c26427..ef6af535cf71 100644 --- a/l1-contracts/test/governance/governance-proposer/scenario/15123.t.sol +++ b/l1-contracts/test/governance/governance-proposer/scenario/15123.t.sol @@ -42,11 +42,7 @@ contract Test15123 is GovernanceProposerBase { vm.expectRevert(); governanceProposer.signalWithSig(proposal, signature); - assertEq( - governanceProposer.signalCount(address(validatorSelection), 0, proposal), - 0, - "invalid number of votes" - ); + assertEq(governanceProposer.signalCount(address(validatorSelection), 0, proposal), 0, "invalid number of votes"); } function test_replay() external { @@ -63,22 +59,14 @@ contract Test15123 is GovernanceProposerBase { governanceProposer.signalWithSig(proposal, signature); - assertEq( - governanceProposer.signalCount(address(validatorSelection), 0, proposal), - 1, - "invalid number of votes" - ); + assertEq(governanceProposer.signalCount(address(validatorSelection), 0, proposal), 1, "invalid number of votes"); vm.warp(Timestamp.unwrap(validatorSelection.getTimestampForSlot(Slot.wrap(2)))); vm.expectRevert(); governanceProposer.signalWithSig(proposal, signature); - assertEq( - governanceProposer.signalCount(address(validatorSelection), 0, proposal), - 1, - "invalid number of votes" - ); + assertEq(governanceProposer.signalCount(address(validatorSelection), 0, proposal), 1, "invalid number of votes"); } function createSignature(uint256 _privateKey, address _payload, uint256 _nonce, uint256 _round) @@ -86,17 +74,13 @@ contract Test15123 is GovernanceProposerBase { view returns (Signature memory) { - bytes32 TYPE_HASH = keccak256( - "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" - ); + bytes32 TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); bytes32 hashedName = keccak256(bytes("EmpireBase")); bytes32 hashedVersion = keccak256(bytes("1")); - bytes32 domainSeparator = keccak256( - abi.encode(TYPE_HASH, hashedName, hashedVersion, block.chainid, address(governanceProposer)) - ); + bytes32 domainSeparator = + keccak256(abi.encode(TYPE_HASH, hashedName, hashedVersion, block.chainid, address(governanceProposer))); bytes32 digest = MessageHashUtils.toTypedDataHash( - domainSeparator, - keccak256(abi.encode(governanceProposer.SIGNAL_TYPEHASH(), _payload, _nonce, _round)) + domainSeparator, keccak256(abi.encode(governanceProposer.SIGNAL_TYPEHASH(), _payload, _nonce, _round)) ); (uint8 v, bytes32 r, bytes32 s) = vm.sign(_privateKey, digest); diff --git a/l1-contracts/test/governance/governance-proposer/signal.t.sol b/l1-contracts/test/governance/governance-proposer/signal.t.sol index 48ff77df42aa..9b3582e7c61e 100644 --- a/l1-contracts/test/governance/governance-proposer/signal.t.sol +++ b/l1-contracts/test/governance/governance-proposer/signal.t.sol @@ -18,9 +18,7 @@ contract SignalTest is GovernanceProposerBase { // Skipping this test since the it matches the for now skipped check in `EmpireBase::signal` function skip__test_WhenProposalHoldNoCode() external { // it revert - vm.expectRevert( - abi.encodeWithSelector(Errors.GovernanceProposer__PayloadHaveNoCode.selector, proposal) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GovernanceProposer__PayloadHaveNoCode.selector, proposal)); governanceProposer.signal(proposal); } @@ -38,9 +36,7 @@ contract SignalTest is GovernanceProposerBase { registry.addRollup(IRollup(f)); vm.etch(f, ""); - vm.expectRevert( - abi.encodeWithSelector(Errors.GovernanceProposer__InstanceHaveNoCode.selector, address(f)) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GovernanceProposer__InstanceHaveNoCode.selector, address(f))); governanceProposer.signal(proposal); } @@ -56,11 +52,7 @@ contract SignalTest is GovernanceProposerBase { _; } - function test_GivenASignalAlreadyCastInTheSlot() - external - whenProposalHoldCode - givenCanonicalRollupHoldCode - { + function test_GivenASignalAlreadyCastInTheSlot() external whenProposalHoldCode givenCanonicalRollupHoldCode { // it revert Slot currentSlot = validatorSelection.getCurrentSlot(); @@ -68,18 +60,11 @@ contract SignalTest is GovernanceProposerBase { vm.prank(proposer); governanceProposer.signal(proposal); - vm.expectRevert( - abi.encodeWithSelector( - Errors.GovernanceProposer__SignalAlreadyCastForSlot.selector, currentSlot - ) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GovernanceProposer__SignalAlreadyCastForSlot.selector, currentSlot)); governanceProposer.signal(proposal); } - function test_GivenSignalIsForPriorRound() - external - whenProposalHoldCode - givenCanonicalRollupHoldCode + function test_GivenSignalIsForPriorRound() external whenProposalHoldCode givenCanonicalRollupHoldCode // solhint-disable-next-line no-empty-blocks { // it revert @@ -102,9 +87,7 @@ contract SignalTest is GovernanceProposerBase { vm.assume(_proposer != proposer); vm.prank(_proposer); vm.expectRevert( - abi.encodeWithSelector( - Errors.GovernanceProposer__OnlyProposerCanSignal.selector, _proposer, proposer - ) + abi.encodeWithSelector(Errors.GovernanceProposer__OnlyProposerCanSignal.selector, _proposer, proposer) ); governanceProposer.signal(proposal); } @@ -115,9 +98,7 @@ contract SignalTest is GovernanceProposerBase { for (uint256 i = 0; i < signalsOnProposal; i++) { vm.warp( - Timestamp.unwrap( - validatorSelection.getTimestampForSlot(validatorSelection.getCurrentSlot() + Slot.wrap(1)) - ) + Timestamp.unwrap(validatorSelection.getTimestampForSlot(validatorSelection.getCurrentSlot() + Slot.wrap(1))) ); vm.prank(proposer); governanceProposer.signal(proposal); @@ -136,9 +117,7 @@ contract SignalTest is GovernanceProposerBase { assertEq(Slot.unwrap(currentSlot), Slot.unwrap(r.lastSignalSlot)); vm.warp( - Timestamp.unwrap( - validatorSelection.getTimestampForSlot(validatorSelection.getCurrentSlot() + Slot.wrap(1)) - ) + Timestamp.unwrap(validatorSelection.getTimestampForSlot(validatorSelection.getCurrentSlot() + Slot.wrap(1))) ); _; @@ -159,8 +138,7 @@ contract SignalTest is GovernanceProposerBase { Slot validatorSelectionSlot = validatorSelection.getCurrentSlot(); uint256 validatorSelectionRound = governanceProposer.computeRound(validatorSelectionSlot); - uint256 yeaBefore = - governanceProposer.signalCount(address(validatorSelection), validatorSelectionRound, proposal); + uint256 yeaBefore = governanceProposer.signalCount(address(validatorSelection), validatorSelectionRound, proposal); Fakerollup freshInstance = new Fakerollup(); freshInstance.setProposer(proposer); @@ -192,21 +170,16 @@ contract SignalTest is GovernanceProposerBase { // The old instance { - RoundAccounting memory r = - governanceProposer.getRoundData(address(validatorSelection), validatorSelectionRound); + RoundAccounting memory r = governanceProposer.getRoundData(address(validatorSelection), validatorSelectionRound); assertEq( - governanceProposer.signalCount( - address(validatorSelection), validatorSelectionRound, proposal - ), + governanceProposer.signalCount(address(validatorSelection), validatorSelectionRound, proposal), yeaBefore, "invalid number of signals" ); assertFalse(r.executed); assertEq(address(r.payloadWithMostSignals), address(proposal)); assertEq( - Slot.unwrap(validatorSelectionSlot), - Slot.unwrap(r.lastSignalSlot) + 1, - "invalid slot [ValidatorSelection]" + Slot.unwrap(validatorSelectionSlot), Slot.unwrap(r.lastSignalSlot) + 1, "invalid slot [ValidatorSelection]" ); } } @@ -277,8 +250,7 @@ contract SignalTest is GovernanceProposerBase { Slot currentSlot = validatorSelection.getCurrentSlot(); uint256 round = governanceProposer.computeRound(currentSlot); - uint256 leaderYeaBefore = - governanceProposer.signalCount(address(validatorSelection), round, proposal); + uint256 leaderYeaBefore = governanceProposer.signalCount(address(validatorSelection), round, proposal); vm.prank(proposer); vm.expectEmit(true, true, true, true, address(governanceProposer)); @@ -292,9 +264,7 @@ contract SignalTest is GovernanceProposerBase { "invalid number of signals" ); assertEq( - governanceProposer.signalCount( - address(validatorSelection), round, IPayload(address(validatorSelection)) - ), + governanceProposer.signalCount(address(validatorSelection), round, IPayload(address(validatorSelection))), 1, "invalid number of signals" ); @@ -319,8 +289,7 @@ contract SignalTest is GovernanceProposerBase { Slot currentSlot = validatorSelection.getCurrentSlot(); uint256 round = governanceProposer.computeRound(currentSlot); - uint256 leaderYeaBefore = - governanceProposer.signalCount(address(validatorSelection), round, proposal); + uint256 leaderYeaBefore = governanceProposer.signalCount(address(validatorSelection), round, proposal); for (uint256 i = 0; i < leaderYeaBefore + 1; i++) { vm.prank(proposer); @@ -329,18 +298,14 @@ contract SignalTest is GovernanceProposerBase { assertTrue(governanceProposer.signal(IPayload(address(validatorSelection)))); vm.warp( - Timestamp.unwrap( - validatorSelection.getTimestampForSlot(validatorSelection.getCurrentSlot() + Slot.wrap(1)) - ) + Timestamp.unwrap(validatorSelection.getTimestampForSlot(validatorSelection.getCurrentSlot() + Slot.wrap(1))) ); } { RoundAccounting memory r = governanceProposer.getRoundData(address(validatorSelection), round); assertEq( - governanceProposer.signalCount( - address(validatorSelection), round, IPayload(address(validatorSelection)) - ), + governanceProposer.signalCount(address(validatorSelection), round, IPayload(address(validatorSelection))), leaderYeaBefore + 1, "invalid number of signals" ); diff --git a/l1-contracts/test/governance/governance-proposer/submitRoundWinner.t.sol b/l1-contracts/test/governance/governance-proposer/submitRoundWinner.t.sol index 45f47b6d053a..d8493f2b4e6c 100644 --- a/l1-contracts/test/governance/governance-proposer/submitRoundWinner.t.sol +++ b/l1-contracts/test/governance/governance-proposer/submitRoundWinner.t.sol @@ -27,9 +27,7 @@ contract ExecuteProposalTest is GovernanceProposerBase { registry.addRollup(IRollup(f)); vm.etch(f, ""); - vm.expectRevert( - abi.encodeWithSelector(Errors.GovernanceProposer__InstanceHaveNoCode.selector, address(f)) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GovernanceProposer__InstanceHaveNoCode.selector, address(f))); governanceProposer.submitRoundWinner(_roundNumber); } @@ -50,26 +48,17 @@ contract ExecuteProposalTest is GovernanceProposerBase { } modifier whenRoundInPast() { - vm.warp( - Timestamp.unwrap( - validatorSelection.getTimestampForSlot(Slot.wrap(governanceProposer.ROUND_SIZE())) - ) - ); + vm.warp(Timestamp.unwrap(validatorSelection.getTimestampForSlot(Slot.wrap(governanceProposer.ROUND_SIZE())))); _; } - function test_WhenRoundTooFarInPast(uint256 _slotToHit) - external - givenCanonicalInstanceHoldCode - whenRoundInPast - { + function test_WhenRoundTooFarInPast(uint256 _slotToHit) external givenCanonicalInstanceHoldCode whenRoundInPast { // it revert Slot lower = validatorSelection.getCurrentSlot() + Slot.wrap(governanceProposer.ROUND_SIZE() * governanceProposer.LIFETIME_IN_ROUNDS() + 1); Slot upper = Slot.wrap( - (type(uint64).max - Timestamp.unwrap(validatorSelection.getGenesisTime())) - / validatorSelection.getSlotDuration() + (type(uint64).max - Timestamp.unwrap(validatorSelection.getGenesisTime())) / validatorSelection.getSlotDuration() ); Slot slotToHit = Slot.wrap(bound(_slotToHit, Slot.unwrap(lower), Slot.unwrap(upper))); vm.warp(Timestamp.unwrap(validatorSelection.getTimestampForSlot(slotToHit))); @@ -102,11 +91,7 @@ contract ExecuteProposalTest is GovernanceProposerBase { vm.prank(proposer); assertTrue(governanceProposer.signal(proposal)); vm.warp( - Timestamp.unwrap( - validatorSelection.getTimestampForSlot( - validatorSelection.getCurrentSlot() + Slot.wrap(1) - ) - ) + Timestamp.unwrap(validatorSelection.getTimestampForSlot(validatorSelection.getCurrentSlot() + Slot.wrap(1))) ); } vm.warp( @@ -119,9 +104,7 @@ contract ExecuteProposalTest is GovernanceProposerBase { governanceProposer.submitRoundWinner(1); } - vm.expectRevert( - abi.encodeWithSelector(Errors.GovernanceProposer__PayloadAlreadySubmitted.selector, 1) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GovernanceProposer__PayloadAlreadySubmitted.selector, 1)); governanceProposer.submitRoundWinner(1); } @@ -144,17 +127,14 @@ contract ExecuteProposalTest is GovernanceProposerBase { // the last slot in the LIFETIME_IN_ROUNDS next round uint256 upper = Timestamp.unwrap( validatorSelection.getTimestampForSlot( - lowerSlot - + Slot.wrap(governanceProposer.ROUND_SIZE() * (governanceProposer.LIFETIME_IN_ROUNDS() - 1)) + lowerSlot + Slot.wrap(governanceProposer.ROUND_SIZE() * (governanceProposer.LIFETIME_IN_ROUNDS() - 1)) ) ); uint256 time = bound(_slotsToJump, lower, upper); vm.warp(time); - vm.expectRevert( - abi.encodeWithSelector(Errors.GovernanceProposer__PayloadCannotBeAddressZero.selector) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GovernanceProposer__PayloadCannotBeAddressZero.selector)); governanceProposer.submitRoundWinner(0); } @@ -184,11 +164,7 @@ contract ExecuteProposalTest is GovernanceProposerBase { ) ) ); - vm.expectRevert( - abi.encodeWithSelector( - Errors.GovernanceProposer__InsufficientSignals.selector, 1, votesNeeded - ) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GovernanceProposer__InsufficientSignals.selector, 1, votesNeeded)); governanceProposer.submitRoundWinner(1); } @@ -199,9 +175,7 @@ contract ExecuteProposalTest is GovernanceProposerBase { vm.prank(proposer); assertTrue(governanceProposer.signal(proposal)); vm.warp( - Timestamp.unwrap( - validatorSelection.getTimestampForSlot(validatorSelection.getCurrentSlot() + Slot.wrap(1)) - ) + Timestamp.unwrap(validatorSelection.getTimestampForSlot(validatorSelection.getCurrentSlot() + Slot.wrap(1))) ); } vm.warp( @@ -248,9 +222,7 @@ contract ExecuteProposalTest is GovernanceProposerBase { ) ) ); - vm.expectRevert( - abi.encodeWithSelector(Errors.GovernanceProposer__PayloadCannotBeAddressZero.selector) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GovernanceProposer__PayloadCannotBeAddressZero.selector)); governanceProposer.submitRoundWinner(1); } diff --git a/l1-contracts/test/governance/governance-proposer/voteWithsig.t.sol b/l1-contracts/test/governance/governance-proposer/voteWithsig.t.sol index 9be2e5682c10..05aebd761a4d 100644 --- a/l1-contracts/test/governance/governance-proposer/voteWithsig.t.sol +++ b/l1-contracts/test/governance/governance-proposer/voteWithsig.t.sol @@ -29,9 +29,7 @@ contract SignalWithSigTest is GovernanceProposerBase { // Skipping this test since the it matches the for now skipped check in `EmpireBase::signal` function skip__test_WhenProposalHoldNoCode() external { // it revert - vm.expectRevert( - abi.encodeWithSelector(Errors.GovernanceProposer__PayloadHaveNoCode.selector, proposal) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GovernanceProposer__PayloadHaveNoCode.selector, proposal)); governanceProposer.signalWithSig(proposal, signature); } @@ -51,9 +49,7 @@ contract SignalWithSigTest is GovernanceProposerBase { registry.addRollup(IRollup(f)); vm.etch(f, ""); - vm.expectRevert( - abi.encodeWithSelector(Errors.GovernanceProposer__InstanceHaveNoCode.selector, address(f)) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GovernanceProposer__InstanceHaveNoCode.selector, address(f))); governanceProposer.signalWithSig(proposal, signature); } @@ -70,22 +66,14 @@ contract SignalWithSigTest is GovernanceProposerBase { _; } - function test_GivenASignalAlreadyCastInTheSlot() - external - whenProposalHoldCode - givenCanonicalRollupHoldCode - { + function test_GivenASignalAlreadyCastInTheSlot() external whenProposalHoldCode givenCanonicalRollupHoldCode { // it revert Slot currentSlot = validatorSelection.getCurrentSlot(); assertEq(Slot.unwrap(currentSlot), 1); governanceProposer.signalWithSig(proposal, signature); - vm.expectRevert( - abi.encodeWithSelector( - Errors.GovernanceProposer__SignalAlreadyCastForSlot.selector, currentSlot - ) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GovernanceProposer__SignalAlreadyCastForSlot.selector, currentSlot)); governanceProposer.signalWithSig(proposal, signature); } @@ -97,8 +85,7 @@ contract SignalWithSigTest is GovernanceProposerBase { // it revert uint256 roundSize = governanceProposer.ROUND_SIZE(); - uint256 minSlotsToFastForward = - roundSize - (Slot.unwrap(validatorSelection.getCurrentSlot()) % roundSize); + uint256 minSlotsToFastForward = roundSize - (Slot.unwrap(validatorSelection.getCurrentSlot()) % roundSize); _slotsToFastForward = bound(_slotsToFastForward, minSlotsToFastForward, roundSize * 1e6); @@ -111,11 +98,7 @@ contract SignalWithSigTest is GovernanceProposerBase { // signal address expectedInvalidSigner = ecrecover(digest, signature.v, signature.r, signature.s); - vm.expectRevert( - abi.encodeWithSelector( - SignatureLib__InvalidSignature.selector, proposer, expectedInvalidSigner - ) - ); + vm.expectRevert(abi.encodeWithSelector(SignatureLib__InvalidSignature.selector, proposer, expectedInvalidSigner)); governanceProposer.signalWithSig(proposal, signature); } @@ -137,9 +120,7 @@ contract SignalWithSigTest is GovernanceProposerBase { vm.assume(_proposer != proposer); signature = createSignature(pk, proposal); - vm.expectRevert( - abi.encodeWithSelector(SignatureLib__InvalidSignature.selector, proposer, _proposer) - ); + vm.expectRevert(abi.encodeWithSelector(SignatureLib__InvalidSignature.selector, proposer, _proposer)); governanceProposer.signalWithSig(proposal, signature); } @@ -149,9 +130,7 @@ contract SignalWithSigTest is GovernanceProposerBase { for (uint256 i = 0; i < signalsOnProposal; i++) { vm.warp( - Timestamp.unwrap( - validatorSelection.getTimestampForSlot(validatorSelection.getCurrentSlot() + Slot.wrap(1)) - ) + Timestamp.unwrap(validatorSelection.getTimestampForSlot(validatorSelection.getCurrentSlot() + Slot.wrap(1))) ); signature = createSignature(privateKey, proposal); governanceProposer.signalWithSig(proposal, signature); @@ -170,9 +149,7 @@ contract SignalWithSigTest is GovernanceProposerBase { assertEq(Slot.unwrap(currentSlot), Slot.unwrap(r.lastSignalSlot)); vm.warp( - Timestamp.unwrap( - validatorSelection.getTimestampForSlot(validatorSelection.getCurrentSlot() + Slot.wrap(1)) - ) + Timestamp.unwrap(validatorSelection.getTimestampForSlot(validatorSelection.getCurrentSlot() + Slot.wrap(1))) ); _; @@ -193,8 +170,7 @@ contract SignalWithSigTest is GovernanceProposerBase { Slot validatorSelectionSlot = validatorSelection.getCurrentSlot(); uint256 validatorSelectionRound = governanceProposer.computeRound(validatorSelectionSlot); - uint256 yeaBefore = - governanceProposer.signalCount(address(validatorSelection), validatorSelectionRound, proposal); + uint256 yeaBefore = governanceProposer.signalCount(address(validatorSelection), validatorSelectionRound, proposal); Fakerollup freshInstance = new Fakerollup(); freshInstance.setProposer(proposer); @@ -228,21 +204,16 @@ contract SignalWithSigTest is GovernanceProposerBase { // The old instance { - RoundAccounting memory r = - governanceProposer.getRoundData(address(validatorSelection), validatorSelectionRound); + RoundAccounting memory r = governanceProposer.getRoundData(address(validatorSelection), validatorSelectionRound); assertEq( - governanceProposer.signalCount( - address(validatorSelection), validatorSelectionRound, proposal - ), + governanceProposer.signalCount(address(validatorSelection), validatorSelectionRound, proposal), yeaBefore, "invalid number of signals" ); assertFalse(r.executed); assertEq(address(r.payloadWithMostSignals), address(proposal)); assertEq( - Slot.unwrap(validatorSelectionSlot), - Slot.unwrap(r.lastSignalSlot) + 1, - "invalid slot [ValidatorSelection]" + Slot.unwrap(validatorSelectionSlot), Slot.unwrap(r.lastSignalSlot) + 1, "invalid slot [ValidatorSelection]" ); } } @@ -314,8 +285,7 @@ contract SignalWithSigTest is GovernanceProposerBase { Slot currentSlot = validatorSelection.getCurrentSlot(); uint256 round = governanceProposer.computeRound(currentSlot); - uint256 leaderYeaBefore = - governanceProposer.signalCount(address(validatorSelection), round, proposal); + uint256 leaderYeaBefore = governanceProposer.signalCount(address(validatorSelection), round, proposal); signature = createSignature(privateKey, IPayload(address(validatorSelection))); @@ -330,9 +300,7 @@ contract SignalWithSigTest is GovernanceProposerBase { "invalid number of signals" ); assertEq( - governanceProposer.signalCount( - address(validatorSelection), round, IPayload(address(validatorSelection)) - ), + governanceProposer.signalCount(address(validatorSelection), round, IPayload(address(validatorSelection))), 1, "invalid number of signals" ); @@ -357,8 +325,7 @@ contract SignalWithSigTest is GovernanceProposerBase { Slot currentSlot = validatorSelection.getCurrentSlot(); uint256 round = governanceProposer.computeRound(currentSlot); - uint256 leaderYeaBefore = - governanceProposer.signalCount(address(validatorSelection), round, proposal); + uint256 leaderYeaBefore = governanceProposer.signalCount(address(validatorSelection), round, proposal); for (uint256 i = 0; i < leaderYeaBefore + 1; i++) { signature = createSignature(privateKey, IPayload(address(validatorSelection))); @@ -368,18 +335,14 @@ contract SignalWithSigTest is GovernanceProposerBase { assertTrue(governanceProposer.signalWithSig(IPayload(address(validatorSelection)), signature)); vm.warp( - Timestamp.unwrap( - validatorSelection.getTimestampForSlot(validatorSelection.getCurrentSlot() + Slot.wrap(1)) - ) + Timestamp.unwrap(validatorSelection.getTimestampForSlot(validatorSelection.getCurrentSlot() + Slot.wrap(1))) ); } { RoundAccounting memory r = governanceProposer.getRoundData(address(validatorSelection), round); assertEq( - governanceProposer.signalCount( - address(validatorSelection), round, IPayload(address(validatorSelection)) - ), + governanceProposer.signalCount(address(validatorSelection), round, IPayload(address(validatorSelection))), leaderYeaBefore + 1, "invalid number of signals" ); @@ -394,18 +357,12 @@ contract SignalWithSigTest is GovernanceProposerBase { } } - function getDigest(uint256 _privateKey, IPayload _payload, uint256 _round) - internal - view - returns (bytes32) - { + function getDigest(uint256 _privateKey, IPayload _payload, uint256 _round) internal view returns (bytes32) { address p = vm.addr(_privateKey); uint256 nonce = governanceProposer.nonces(p); bytes32 domainSeparator = keccak256( abi.encode( - keccak256( - "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" - ), + keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes("EmpireBase")), keccak256(bytes("1")), block.chainid, @@ -413,17 +370,12 @@ contract SignalWithSigTest is GovernanceProposerBase { ) ); bytes32 digest = MessageHashUtils.toTypedDataHash( - domainSeparator, - keccak256(abi.encode(governanceProposer.SIGNAL_TYPEHASH(), _payload, nonce, _round)) + domainSeparator, keccak256(abi.encode(governanceProposer.SIGNAL_TYPEHASH(), _payload, nonce, _round)) ); return digest; } - function createSignature(uint256 _privateKey, IPayload _payload) - internal - view - returns (Signature memory) - { + function createSignature(uint256 _privateKey, IPayload _payload) internal view returns (Signature memory) { uint256 round = governanceProposer.getCurrentRound(); bytes32 digest = getDigest(_privateKey, _payload, round); diff --git a/l1-contracts/test/governance/governance/TestPayloads.sol b/l1-contracts/test/governance/governance/TestPayloads.sol index ba8bbb82cdae..2100232d6211 100644 --- a/l1-contracts/test/governance/governance/TestPayloads.sol +++ b/l1-contracts/test/governance/governance/TestPayloads.sol @@ -33,10 +33,7 @@ contract CallAssetPayload is IPayload { IPayload.Action[] memory res = new IPayload.Action[](1); uint256 balance = ASSET.balanceOf(GOVERNANCE); - res[0] = Action({ - target: address(ASSET), - data: abi.encodeWithSelector(ASSET.transfer.selector, OWNER, balance) - }); + res[0] = Action({target: address(ASSET), data: abi.encodeWithSelector(ASSET.transfer.selector, OWNER, balance)}); return res; } @@ -63,10 +60,7 @@ contract UpgradePayload is IPayload { function getActions() external view override(IPayload) returns (IPayload.Action[] memory) { IPayload.Action[] memory res = new IPayload.Action[](1); - res[0] = Action({ - target: address(REGISTRY), - data: abi.encodeWithSelector(REGISTRY.addRollup.selector, NEW_ROLLUP) - }); + res[0] = Action({target: address(REGISTRY), data: abi.encodeWithSelector(REGISTRY.addRollup.selector, NEW_ROLLUP)}); return res; } @@ -82,10 +76,7 @@ contract CallRevertingPayload is IPayload { function getActions() external view override(IPayload) returns (IPayload.Action[] memory) { IPayload.Action[] memory res = new IPayload.Action[](1); - res[0] = Action({ - target: address(TARGET), - data: abi.encodeWithSelector(TARGET.skibBobFlipFlop.selector) - }); + res[0] = Action({target: address(TARGET), data: abi.encodeWithSelector(TARGET.skibBobFlipFlop.selector)}); return res; } diff --git a/l1-contracts/test/governance/governance/address_snapshots/AddressSnapshotsBase.t.sol b/l1-contracts/test/governance/governance/address_snapshots/AddressSnapshotsBase.t.sol index 3aa392a2c00c..f744962c7498 100644 --- a/l1-contracts/test/governance/governance/address_snapshots/AddressSnapshotsBase.t.sol +++ b/l1-contracts/test/governance/governance/address_snapshots/AddressSnapshotsBase.t.sol @@ -2,10 +2,7 @@ // Copyright 2025 Aztec Labs. pragma solidity >=0.8.27; -import { - AddressSnapshotLib, - SnapshottedAddressSet -} from "@aztec/governance/libraries/AddressSnapshotLib.sol"; +import {AddressSnapshotLib, SnapshottedAddressSet} from "@aztec/governance/libraries/AddressSnapshotLib.sol"; import {Test} from "forge-std/Test.sol"; import {TimeLib, TimeStorage, Epoch, Timestamp} from "@aztec/core/libraries/TimeLib.sol"; @@ -34,11 +31,7 @@ contract AddressSetWrapper { return validatorSet.at(_index); } - function getAddressFromIndexAtTimestamp(uint256 _index, uint32 _timestamp) - public - view - returns (address) - { + function getAddressFromIndexAtTimestamp(uint256 _index, uint32 _timestamp) public view returns (address) { return validatorSet.getAddressFromIndexAtTimestamp(_index, _timestamp); } @@ -88,8 +81,7 @@ contract AddressSnapshotsBase is Test { GENESIS_TIME = block.timestamp; TimeLib.initialize(GENESIS_TIME, SLOT_DURATION, EPOCH_DURATION, PROOF_SUBMISSION_EPOCHS); validatorSet = new AddressSetWrapper(); - timeCheater = new TimeCheater( - address(validatorSet), GENESIS_TIME, SLOT_DURATION, EPOCH_DURATION, PROOF_SUBMISSION_EPOCHS - ); + timeCheater = + new TimeCheater(address(validatorSet), GENESIS_TIME, SLOT_DURATION, EPOCH_DURATION, PROOF_SUBMISSION_EPOCHS); } } diff --git a/l1-contracts/test/governance/governance/address_snapshots/add.t.sol b/l1-contracts/test/governance/governance/address_snapshots/add.t.sol index f16a222f17df..a2fddb271cf4 100644 --- a/l1-contracts/test/governance/governance/address_snapshots/add.t.sol +++ b/l1-contracts/test/governance/governance/address_snapshots/add.t.sol @@ -70,11 +70,7 @@ contract AddressSnapshotAddTest is AddressSnapshotsBase { assertEq(writes.length, 0); } - function test_WhenValidatorHasBeenRemovedFromTheSet( - address[] memory _addrs, - uint16 _add2, - uint16 _add3 - ) public { + function test_WhenValidatorHasBeenRemovedFromTheSet(address[] memory _addrs, uint16 _add2, uint16 _add3) public { // It can be added again _addrs = boundUnique(_addrs); diff --git a/l1-contracts/test/governance/governance/address_snapshots/at.t.sol b/l1-contracts/test/governance/governance/address_snapshots/at.t.sol index 98005b58dd66..4c59637afd35 100644 --- a/l1-contracts/test/governance/governance/address_snapshots/at.t.sol +++ b/l1-contracts/test/governance/governance/address_snapshots/at.t.sol @@ -16,23 +16,17 @@ contract AddressSnapshotAtTest is AddressSnapshotsBase { function test_WhenNoValidatorsAreRegistered(uint256 _index) public { // It reverts - vm.expectRevert( - abi.encodeWithSelector(AddressSnapshotLib__IndexOutOfBounds.selector, _index, 0) - ); + vm.expectRevert(abi.encodeWithSelector(AddressSnapshotLib__IndexOutOfBounds.selector, _index, 0)); validatorSet.at(_index); } function test_WhenIndexIsOutOfBounds(uint256 _index) public { vm.assume(_index >= 1); validatorSet.add(address(1)); - vm.expectRevert( - abi.encodeWithSelector(AddressSnapshotLib__IndexOutOfBounds.selector, _index, 1) - ); + vm.expectRevert(abi.encodeWithSelector(AddressSnapshotLib__IndexOutOfBounds.selector, _index, 1)); validatorSet.at(_index); - vm.expectRevert( - abi.encodeWithSelector(AddressSnapshotLib__IndexOutOfBounds.selector, _index, 1) - ); + vm.expectRevert(abi.encodeWithSelector(AddressSnapshotLib__IndexOutOfBounds.selector, _index, 1)); validatorSet.getAddressFromIndexAtTimestamp(_index, block.timestamp.toUint32()); } @@ -45,26 +39,21 @@ contract AddressSnapshotAtTest is AddressSnapshotsBase { for (uint256 i = 0; i < _addrs.length; i++) { validatorSet.add(_addrs[i]); assertEq(validatorSet.at(i), _addrs[i]); - assertEq( - validatorSet.getAddressFromIndexAtTimestamp(i, block.timestamp.toUint32()), _addrs[i] - ); + assertEq(validatorSet.getAddressFromIndexAtTimestamp(i, block.timestamp.toUint32()), _addrs[i]); } address last = validatorSet.at(_addrs.length - 1); // Remove a random index // -1 to not remove the last item - uint224 randomIndex = uint224( - uint256(keccak256(abi.encodePacked(block.timestamp, _addrs.length))) % (_addrs.length - 1) - ); + uint224 randomIndex = + uint224(uint256(keccak256(abi.encodePacked(block.timestamp, _addrs.length))) % (_addrs.length - 1)); address removedAddr = _addrs[randomIndex]; validatorSet.remove(randomIndex); // The item at the random index should be different, as it has been replaced assertNotEq(validatorSet.at(randomIndex), removedAddr); assertEq(validatorSet.at(randomIndex), last); - assertEq( - validatorSet.getAddressFromIndexAtTimestamp(randomIndex, block.timestamp.toUint32()), last - ); + assertEq(validatorSet.getAddressFromIndexAtTimestamp(randomIndex, block.timestamp.toUint32()), last); } } diff --git a/l1-contracts/test/governance/governance/address_snapshots/getAddressFromIndexAtTimestamp.t.sol b/l1-contracts/test/governance/governance/address_snapshots/getAddressFromIndexAtTimestamp.t.sol index 297836314e38..e887449b23da 100644 --- a/l1-contracts/test/governance/governance/address_snapshots/getAddressFromIndexAtTimestamp.t.sol +++ b/l1-contracts/test/governance/governance/address_snapshots/getAddressFromIndexAtTimestamp.t.sol @@ -29,17 +29,12 @@ contract GetAddressFromIndexAtTimestampTest is AddressSnapshotsBase { _; } - function test_whenQueryingCurrentTimestamp(address[] memory _addrs) - public - whenValidatorsExist(_addrs) - { + function test_whenQueryingCurrentTimestamp(address[] memory _addrs) public whenValidatorsExist(_addrs) { _addrs = boundUnique(_addrs); // It should return the current validator address for (uint256 i = 0; i < _addrs.length; i++) { - assertEq( - validatorSet.getAddressFromIndexAtTimestamp(i, block.timestamp.toUint32()), _addrs[i] - ); + assertEq(validatorSet.getAddressFromIndexAtTimestamp(i, block.timestamp.toUint32()), _addrs[i]); } } @@ -47,17 +42,11 @@ contract GetAddressFromIndexAtTimestampTest is AddressSnapshotsBase { _addrs = boundUnique(_addrs); // It should return the current validator address for (uint256 i = 0; i < _addrs.length; i++) { - assertEq( - validatorSet.getAddressFromIndexAtTimestamp(i, (1000 + block.timestamp).toUint32()), - _addrs[i] - ); + assertEq(validatorSet.getAddressFromIndexAtTimestamp(i, (1000 + block.timestamp).toUint32()), _addrs[i]); } } - function test_WhenQueryingPast(address[] memory _addrs, uint224 _index) - public - whenValidatorsExist(_addrs) - { + function test_WhenQueryingPast(address[] memory _addrs, uint224 _index) public whenValidatorsExist(_addrs) { _addrs = boundUnique(_addrs); _index = uint224(bound(_index, 0, _addrs.length - 1)); @@ -66,16 +55,12 @@ contract GetAddressFromIndexAtTimestampTest is AddressSnapshotsBase { // It should return the validator address from the snapshot assertEq( - validatorSet.getAddressFromIndexAtTimestamp( - _index, (block.timestamp - bound(_index, 1, 999)).toUint32() - ), + validatorSet.getAddressFromIndexAtTimestamp(_index, (block.timestamp - bound(_index, 1, 999)).toUint32()), _addrs[_index] ); // In a past epoch, it is out of bounds - vm.expectRevert( - abi.encodeWithSelector(AddressSnapshotLib__IndexOutOfBounds.selector, _index, 0) - ); + vm.expectRevert(abi.encodeWithSelector(AddressSnapshotLib__IndexOutOfBounds.selector, _index, 0)); validatorSet.getAddressFromIndexAtTimestamp(_index, (ts - 1).toUint32()); } @@ -88,16 +73,11 @@ contract GetAddressFromIndexAtTimestampTest is AddressSnapshotsBase { uint256 ts = block.timestamp; vm.warp(ts + 1); - assertEq( - validatorSet.getAddressFromIndexAtTimestamp(lastIndex, (block.timestamp).toUint32()), - lastValidator - ); + assertEq(validatorSet.getAddressFromIndexAtTimestamp(lastIndex, (block.timestamp).toUint32()), lastValidator); validatorSet.remove(lastIndex); - vm.expectRevert( - abi.encodeWithSelector(AddressSnapshotLib__IndexOutOfBounds.selector, lastIndex, lastIndex) - ); + vm.expectRevert(abi.encodeWithSelector(AddressSnapshotLib__IndexOutOfBounds.selector, lastIndex, lastIndex)); validatorSet.getAddressFromIndexAtTimestamp(lastIndex, (block.timestamp).toUint32()); assertEq(validatorSet.getAddressFromIndexAtTimestamp(lastIndex, (ts).toUint32()), lastValidator); @@ -105,11 +85,7 @@ contract GetAddressFromIndexAtTimestampTest is AddressSnapshotsBase { function test_WhenIndexIsOutOfBounds(address[] memory _addrs) public whenValidatorsExist(_addrs) { // It should throw out of bounds - vm.expectRevert( - abi.encodeWithSelector( - AddressSnapshotLib__IndexOutOfBounds.selector, _addrs.length, _addrs.length - ) - ); + vm.expectRevert(abi.encodeWithSelector(AddressSnapshotLib__IndexOutOfBounds.selector, _addrs.length, _addrs.length)); validatorSet.getAddressFromIndexAtTimestamp(_addrs.length, block.timestamp.toUint32()); } @@ -123,9 +99,8 @@ contract GetAddressFromIndexAtTimestampTest is AddressSnapshotsBase { uint32 t1 = block.timestamp.toUint32(); // Random index to remove - uint224 randomIndex = uint224( - uint256(keccak256(abi.encodePacked(block.timestamp, _addrs.length))) % (_addrs.length - 1) - ); + uint224 randomIndex = + uint224(uint256(keccak256(abi.encodePacked(block.timestamp, _addrs.length))) % (_addrs.length - 1)); uint32 t2 = t1 + 1; vm.warp(t2); @@ -134,9 +109,7 @@ contract GetAddressFromIndexAtTimestampTest is AddressSnapshotsBase { validatorSet.remove(randomIndex); // Check it now contains the last validators - assertEq( - validatorSet.getAddressFromIndexAtTimestamp(randomIndex, t2), _addrs[_addrs.length - 1] - ); + assertEq(validatorSet.getAddressFromIndexAtTimestamp(randomIndex, t2), _addrs[_addrs.length - 1]); // Check it still contains the old validator at random index at t1 assertEq(validatorSet.getAddressFromIndexAtTimestamp(randomIndex, t1), _addrs[randomIndex]); diff --git a/l1-contracts/test/governance/governance/address_snapshots/length.t.sol b/l1-contracts/test/governance/governance/address_snapshots/length.t.sol index 85160e6df2b7..bbbc869d8cb2 100644 --- a/l1-contracts/test/governance/governance/address_snapshots/length.t.sol +++ b/l1-contracts/test/governance/governance/address_snapshots/length.t.sol @@ -2,10 +2,7 @@ // Copyright 2025 Aztec Labs. pragma solidity >=0.8.27; -import { - AddressSnapshotLib, - SnapshottedAddressSet -} from "@aztec/governance/libraries/AddressSnapshotLib.sol"; +import {AddressSnapshotLib, SnapshottedAddressSet} from "@aztec/governance/libraries/AddressSnapshotLib.sol"; import {AddressSnapshotsBase} from "./AddressSnapshotsBase.t.sol"; import {Epoch} from "@aztec/core/libraries/TimeLib.sol"; diff --git a/l1-contracts/test/governance/governance/address_snapshots/values.t.sol b/l1-contracts/test/governance/governance/address_snapshots/values.t.sol index 4eaa53ebf4aa..5affd3c81541 100644 --- a/l1-contracts/test/governance/governance/address_snapshots/values.t.sol +++ b/l1-contracts/test/governance/governance/address_snapshots/values.t.sol @@ -34,10 +34,7 @@ contract AddressSnapshotValuesTest is AddressSnapshotsBase { } } - function test_WhenValidatorsHaveNotChangedForSomeTime( - address[] memory _addrs, - uint16 _epochsToJump - ) public { + function test_WhenValidatorsHaveNotChangedForSomeTime(address[] memory _addrs, uint16 _epochsToJump) public { _addrs = boundUnique(_addrs); uint32 ts = uint32(block.timestamp); diff --git a/l1-contracts/test/governance/governance/base.t.sol b/l1-contracts/test/governance/governance/base.t.sol index 92ed8bde81d6..428024c17f2a 100644 --- a/l1-contracts/test/governance/governance/base.t.sol +++ b/l1-contracts/test/governance/governance/base.t.sol @@ -12,15 +12,9 @@ import {TestConstants} from "@test/harnesses/TestConstants.sol"; import {Timestamp} from "@aztec/core/libraries/TimeLib.sol"; import {Math} from "@oz/utils/math/Math.sol"; import {IGSE} from "@aztec/governance/GSE.sol"; -import { - ProposalLib, - VoteTabulationReturn, - VoteTabulationInfo -} from "@aztec/governance/libraries/ProposalLib.sol"; +import {ProposalLib, VoteTabulationReturn, VoteTabulationInfo} from "@aztec/governance/libraries/ProposalLib.sol"; -import { - CallAssetPayload, UpgradePayload, CallRevertingPayload, EmptyPayload -} from "./TestPayloads.sol"; +import {CallAssetPayload, UpgradePayload, CallRevertingPayload, EmptyPayload} from "./TestPayloads.sol"; contract GovernanceBase is TestBase { using ProposalLib for Proposal; @@ -41,9 +35,8 @@ contract GovernanceBase is TestBase { registry = new Registry(address(this), token); governanceProposer = new GovernanceProposer(registry, IGSE(address(0x03)), 677, 1000); - governance = new Governance( - token, address(governanceProposer), address(this), TestConstants.getGovernanceConfiguration() - ); + governance = + new Governance(token, address(governanceProposer), address(this), TestConstants.getGovernanceConfiguration()); vm.prank(address(governance)); governance.openFloodgates(); @@ -124,13 +117,9 @@ contract GovernanceBase is TestBase { assertTrue(governance.getProposalState(proposalId) == ProposalState.Rejected); } - function _stateQueued( - bytes32 _proposalName, - address _voter, - uint256 _totalPower, - uint256 _votesCast, - uint256 _yeas - ) internal { + function _stateQueued(bytes32 _proposalName, address _voter, uint256 _totalPower, uint256 _votesCast, uint256 _yeas) + internal + { vm.assume(_voter != address(0)); proposal = proposals[_proposalName]; proposalId = proposalIds[_proposalName]; @@ -179,13 +168,9 @@ contract GovernanceBase is TestBase { assertEq(governance.getProposalState(proposalId), ProposalState.Executable, "invalid state"); } - function _stateExpired( - bytes32 _proposalName, - address _voter, - uint256 _totalPower, - uint256 _votesCast, - uint256 _yeas - ) internal { + function _stateExpired(bytes32 _proposalName, address _voter, uint256 _totalPower, uint256 _votesCast, uint256 _yeas) + internal + { proposal = proposals[_proposalName]; proposalId = proposalIds[_proposalName]; diff --git a/l1-contracts/test/governance/governance/checkpointedUintLib/add.t.sol b/l1-contracts/test/governance/governance/checkpointedUintLib/add.t.sol index 5aa4f7e7d61a..29dc74c84e36 100644 --- a/l1-contracts/test/governance/governance/checkpointedUintLib/add.t.sol +++ b/l1-contracts/test/governance/governance/checkpointedUintLib/add.t.sol @@ -2,9 +2,7 @@ pragma solidity >=0.8.27; import {CheckpointedUintLibBase} from "./base.t.sol"; -import { - Checkpoints, CheckpointedUintLib -} from "@aztec/governance/libraries/CheckpointedUintLib.sol"; +import {Checkpoints, CheckpointedUintLib} from "@aztec/governance/libraries/CheckpointedUintLib.sol"; import {Timestamp, TimeLib} from "@aztec/core/libraries/TimeLib.sol"; import {Checkpoints} from "@oz/utils/structs/Checkpoints.sol"; import {SafeCast} from "@oz/utils/math/SafeCast.sol"; @@ -29,10 +27,7 @@ contract AddTest is CheckpointedUintLibBase { assertEq(writes.length, 0); } - function test_GivenUserHaveNoCheckpoints(uint256 _amount, uint32 _time) - external - whenAmountGt0(_amount) - { + function test_GivenUserHaveNoCheckpoints(uint256 _amount, uint32 _time) external whenAmountGt0(_amount) { // it adds checkpoint with amount // it increases num checkpoints diff --git a/l1-contracts/test/governance/governance/checkpointedUintLib/base.t.sol b/l1-contracts/test/governance/governance/checkpointedUintLib/base.t.sol index ae154ccf99ce..9fb501324507 100644 --- a/l1-contracts/test/governance/governance/checkpointedUintLib/base.t.sol +++ b/l1-contracts/test/governance/governance/checkpointedUintLib/base.t.sol @@ -2,9 +2,7 @@ pragma solidity >=0.8.27; import {TestBase} from "@test/base/Base.sol"; -import { - Checkpoints, CheckpointedUintLib -} from "@aztec/governance/libraries/CheckpointedUintLib.sol"; +import {Checkpoints, CheckpointedUintLib} from "@aztec/governance/libraries/CheckpointedUintLib.sol"; contract CheckpointedUintLibBase is TestBase { using CheckpointedUintLib for Checkpoints.Trace224; diff --git a/l1-contracts/test/governance/governance/checkpointedUintLib/powerAt.t.sol b/l1-contracts/test/governance/governance/checkpointedUintLib/powerAt.t.sol index db2510697b78..e2e55a45ab57 100644 --- a/l1-contracts/test/governance/governance/checkpointedUintLib/powerAt.t.sol +++ b/l1-contracts/test/governance/governance/checkpointedUintLib/powerAt.t.sol @@ -2,9 +2,7 @@ pragma solidity >=0.8.27; import {CheckpointedUintLibBase} from "./base.t.sol"; -import { - Checkpoints, CheckpointedUintLib -} from "@aztec/governance/libraries/CheckpointedUintLib.sol"; +import {Checkpoints, CheckpointedUintLib} from "@aztec/governance/libraries/CheckpointedUintLib.sol"; import {Timestamp} from "@aztec/core/libraries/TimeLib.sol"; import {Errors} from "@aztec/governance/libraries/Errors.sol"; import {Checkpoints} from "@oz/utils/structs/Checkpoints.sol"; @@ -19,9 +17,7 @@ contract PowerAtTest is CheckpointedUintLibBase { function test_WhenTimeNotInPast() external { // it revert - vm.expectRevert( - abi.encodeWithSelector(Errors.Governance__CheckpointedUintLib__NotInPast.selector) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Governance__CheckpointedUintLib__NotInPast.selector)); this.callPowerAt(); } diff --git a/l1-contracts/test/governance/governance/checkpointedUintLib/powerNow.t.sol b/l1-contracts/test/governance/governance/checkpointedUintLib/powerNow.t.sol index a6f8e94c6027..7844e9b6ed44 100644 --- a/l1-contracts/test/governance/governance/checkpointedUintLib/powerNow.t.sol +++ b/l1-contracts/test/governance/governance/checkpointedUintLib/powerNow.t.sol @@ -2,9 +2,7 @@ pragma solidity >=0.8.27; import {CheckpointedUintLibBase} from "./base.t.sol"; -import { - Checkpoints, CheckpointedUintLib -} from "@aztec/governance/libraries/CheckpointedUintLib.sol"; +import {Checkpoints, CheckpointedUintLib} from "@aztec/governance/libraries/CheckpointedUintLib.sol"; import {Timestamp} from "@aztec/core/libraries/TimeLib.sol"; import {Errors} from "@aztec/governance/libraries/Errors.sol"; import {Checkpoints} from "@oz/utils/structs/Checkpoints.sol"; diff --git a/l1-contracts/test/governance/governance/checkpointedUintLib/sub.t.sol b/l1-contracts/test/governance/governance/checkpointedUintLib/sub.t.sol index aee327834d96..37d5e6fb3fb6 100644 --- a/l1-contracts/test/governance/governance/checkpointedUintLib/sub.t.sol +++ b/l1-contracts/test/governance/governance/checkpointedUintLib/sub.t.sol @@ -2,9 +2,7 @@ pragma solidity >=0.8.27; import {CheckpointedUintLibBase} from "./base.t.sol"; -import { - Checkpoints, CheckpointedUintLib -} from "@aztec/governance/libraries/CheckpointedUintLib.sol"; +import {Checkpoints, CheckpointedUintLib} from "@aztec/governance/libraries/CheckpointedUintLib.sol"; import {Timestamp} from "@aztec/core/libraries/TimeLib.sol"; import {Errors} from "@aztec/governance/libraries/Errors.sol"; import {Checkpoints} from "@oz/utils/structs/Checkpoints.sol"; @@ -32,9 +30,7 @@ contract SubTest is CheckpointedUintLibBase { function test_GivenUserHaveNoCheckpoints(uint256 _amount) external whenAmountGt0(_amount) { // it revert vm.expectRevert( - abi.encodeWithSelector( - Errors.Governance__CheckpointedUintLib__InsufficientValue.selector, msg.sender, 0, amount - ) + abi.encodeWithSelector(Errors.Governance__CheckpointedUintLib__InsufficientValue.selector, msg.sender, 0, amount) ); vm.prank(msg.sender); this.callSub(amount); @@ -52,10 +48,7 @@ contract SubTest is CheckpointedUintLibBase { vm.expectRevert( abi.encodeWithSelector( - Errors.Governance__CheckpointedUintLib__InsufficientValue.selector, - msg.sender, - sumBefore, - amount + Errors.Governance__CheckpointedUintLib__InsufficientValue.selector, msg.sender, sumBefore, amount ) ); vm.prank(msg.sender); diff --git a/l1-contracts/test/governance/governance/deposit.t.sol b/l1-contracts/test/governance/governance/deposit.t.sol index 0d018f832f33..82916239dffe 100644 --- a/l1-contracts/test/governance/governance/deposit.t.sol +++ b/l1-contracts/test/governance/governance/deposit.t.sol @@ -15,9 +15,7 @@ contract DepositTest is GovernanceBase { uint256 amount = bound(_amount, 1, type(uint256).max); vm.expectRevert( - abi.encodeWithSelector( - IERC20Errors.ERC20InsufficientAllowance.selector, address(governance), 0, amount - ) + abi.encodeWithSelector(IERC20Errors.ERC20InsufficientAllowance.selector, address(governance), 0, amount) ); governance.deposit(address(this), amount); } @@ -26,20 +24,13 @@ contract DepositTest is GovernanceBase { _; } - function test_WhenCallerHaveInsufficientFunds(uint256 _amount) - external - whenCallerHaveSufficientAllowance - { + function test_WhenCallerHaveInsufficientFunds(uint256 _amount) external whenCallerHaveSufficientAllowance { // it revert uint256 amount = bound(_amount, 1, type(uint256).max); token.approve(address(governance), amount); - vm.expectRevert( - abi.encodeWithSelector( - IERC20Errors.ERC20InsufficientBalance.selector, address(this), 0, amount - ) - ); + vm.expectRevert(abi.encodeWithSelector(IERC20Errors.ERC20InsufficientBalance.selector, address(this), 0, amount)); governance.deposit(address(this), amount); } @@ -73,10 +64,7 @@ contract DepositTest is GovernanceBase { emit IGovernance.Deposit(address(this), onBehalfOf, amount); governance.deposit(onBehalfOf, amount); - assertEq( - governance.powerAt(onBehalfOf, Timestamp.wrap(block.timestamp - 1)), - sums[onBehalfOf] - amount - ); + assertEq(governance.powerAt(onBehalfOf, Timestamp.wrap(block.timestamp - 1)), sums[onBehalfOf] - amount); assertEq(governance.powerAt(onBehalfOf, Timestamp.wrap(block.timestamp)), sums[onBehalfOf]); assertEq(governance.totalPowerAt(Timestamp.wrap(block.timestamp - 1)), sum - amount); assertEq(governance.totalPowerAt(Timestamp.wrap(block.timestamp)), sum); diff --git a/l1-contracts/test/governance/governance/dropProposal.t.sol b/l1-contracts/test/governance/governance/dropProposal.t.sol index c5471b2af72a..674986f87be9 100644 --- a/l1-contracts/test/governance/governance/dropProposal.t.sol +++ b/l1-contracts/test/governance/governance/dropProposal.t.sol @@ -22,12 +22,10 @@ contract DropProposalTest is GovernanceBase { governance.dropProposal(proposalId); } - function test_GivenProposalIsExecuted( - address _voter, - uint256 _totalPower, - uint256 _votesCast, - uint256 _yeas - ) external givenProposalIsStable { + function test_GivenProposalIsExecuted(address _voter, uint256 _totalPower, uint256 _votesCast, uint256 _yeas) + external + givenProposalIsStable + { // it revert _stateExecutable("empty", _voter, _totalPower, _votesCast, _yeas); assertTrue(governance.execute(proposalId)); @@ -47,85 +45,66 @@ contract DropProposalTest is GovernanceBase { governance.dropProposal(proposalId); } - function test_WhenGetProposalStateIsPending() - external - givenProposalIsUnstable - whenGetProposalStateIsNotDropped - { + function test_WhenGetProposalStateIsPending() external givenProposalIsUnstable whenGetProposalStateIsNotDropped { // it revert _statePending("empty"); assertEq(governance.getProposalState(proposalId), ProposalState.Pending); } - function test_WhenGetProposalStateIsActive() - external - givenProposalIsUnstable - whenGetProposalStateIsNotDropped - { + function test_WhenGetProposalStateIsActive() external givenProposalIsUnstable whenGetProposalStateIsNotDropped { // it revert _stateActive("empty"); assertEq(governance.getProposalState(proposalId), ProposalState.Active); } - function test_WhenGetProposalStateIsQueued( - address _voter, - uint256 _totalPower, - uint256 _votesCast, - uint256 _yeas - ) external givenProposalIsUnstable whenGetProposalStateIsNotDropped { + function test_WhenGetProposalStateIsQueued(address _voter, uint256 _totalPower, uint256 _votesCast, uint256 _yeas) + external + givenProposalIsUnstable + whenGetProposalStateIsNotDropped + { // it revert _stateQueued("empty", _voter, _totalPower, _votesCast, _yeas); assertEq(governance.getProposalState(proposalId), ProposalState.Queued); } - function test_WhenGetProposalStateIsExecutable( - address _voter, - uint256 _totalPower, - uint256 _votesCast, - uint256 _yeas - ) external givenProposalIsUnstable whenGetProposalStateIsNotDropped { + function test_WhenGetProposalStateIsExecutable(address _voter, uint256 _totalPower, uint256 _votesCast, uint256 _yeas) + external + givenProposalIsUnstable + whenGetProposalStateIsNotDropped + { // it revert _stateExecutable("empty", _voter, _totalPower, _votesCast, _yeas); assertEq(governance.getProposalState(proposalId), ProposalState.Executable); } - function test_WhenGetProposalStateIsRejected() - external - givenProposalIsUnstable - whenGetProposalStateIsNotDropped - { + function test_WhenGetProposalStateIsRejected() external givenProposalIsUnstable whenGetProposalStateIsNotDropped { // it revert _stateRejected("empty"); assertEq(governance.getProposalState(proposalId), ProposalState.Rejected); } - function test_WhenGetProposalStateIsExecuted( - address _voter, - uint256 _totalPower, - uint256 _votesCast, - uint256 _yeas - ) external givenProposalIsUnstable whenGetProposalStateIsNotDropped { + function test_WhenGetProposalStateIsExecuted(address _voter, uint256 _totalPower, uint256 _votesCast, uint256 _yeas) + external + givenProposalIsUnstable + whenGetProposalStateIsNotDropped + { // it revert _stateExecutable("empty", _voter, _totalPower, _votesCast, _yeas); assertTrue(governance.execute(proposalId)); assertEq(governance.getProposalState(proposalId), ProposalState.Executed); } - function test_WhenGetProposalStateIsExpired( - address _voter, - uint256 _totalPower, - uint256 _votesCast, - uint256 _yeas - ) external givenProposalIsUnstable whenGetProposalStateIsNotDropped { + function test_WhenGetProposalStateIsExpired(address _voter, uint256 _totalPower, uint256 _votesCast, uint256 _yeas) + external + givenProposalIsUnstable + whenGetProposalStateIsNotDropped + { // it revert _stateExpired("empty", _voter, _totalPower, _votesCast, _yeas); assertEq(governance.getProposalState(proposalId), ProposalState.Expired); } - function test_WhenGetProposalStateIsDropped(address _governanceProposer) - external - givenProposalIsUnstable - { + function test_WhenGetProposalStateIsDropped(address _governanceProposer) external givenProposalIsUnstable { // it updates state to Dropped // it return true diff --git a/l1-contracts/test/governance/governance/execute.t.sol b/l1-contracts/test/governance/governance/execute.t.sol index f7635c0a5600..c04c4c28258b 100644 --- a/l1-contracts/test/governance/governance/execute.t.sol +++ b/l1-contracts/test/governance/governance/execute.t.sol @@ -4,11 +4,7 @@ pragma solidity >=0.8.27; import {GovernanceBase} from "./base.t.sol"; import {Errors} from "@aztec/governance/libraries/Errors.sol"; import {Proposal, ProposalState, IGovernance} from "@aztec/governance/interfaces/IGovernance.sol"; -import { - ProposalLib, - VoteTabulationReturn, - VoteTabulationInfo -} from "@aztec/governance/libraries/ProposalLib.sol"; +import {ProposalLib, VoteTabulationReturn, VoteTabulationInfo} from "@aztec/governance/libraries/ProposalLib.sol"; import {CallAssetPayload, UpgradePayload, CallRevertingPayload} from "./TestPayloads.sol"; @@ -35,12 +31,10 @@ contract ExecuteTest is GovernanceBase { assertEq(governance.getProposalState(proposalId), ProposalState.Active); } - function test_GivenStateIsQueued( - address _voter, - uint256 _totalPower, - uint256 _votesCast, - uint256 _yeas - ) external givenStateIsNotExecutable { + function test_GivenStateIsQueued(address _voter, uint256 _totalPower, uint256 _votesCast, uint256 _yeas) + external + givenStateIsNotExecutable + { // it revert _stateQueued("empty", _voter, _totalPower, _votesCast, _yeas); assertEq(governance.getProposalState(proposalId), ProposalState.Queued); @@ -52,10 +46,7 @@ contract ExecuteTest is GovernanceBase { assertEq(governance.getProposalState(proposalId), ProposalState.Rejected); } - function test_GivenStateIsDroppable(address _governanceProposer) - external - givenStateIsNotExecutable - { + function test_GivenStateIsDroppable(address _governanceProposer) external givenStateIsNotExecutable { // it revert _stateDroppable("empty", _governanceProposer); governance.dropProposal(proposalId); @@ -68,24 +59,20 @@ contract ExecuteTest is GovernanceBase { assertEq(governance.getProposalState(proposalId), ProposalState.Droppable); } - function test_GivenStateIsExecuted( - address _voter, - uint256 _totalPower, - uint256 _votesCast, - uint256 _yeas - ) external givenStateIsNotExecutable { + function test_GivenStateIsExecuted(address _voter, uint256 _totalPower, uint256 _votesCast, uint256 _yeas) + external + givenStateIsNotExecutable + { // it revert _stateExecutable("empty", _voter, _totalPower, _votesCast, _yeas); assertTrue(governance.execute(proposalId)); assertEq(governance.getProposalState(proposalId), ProposalState.Executed); } - function test_GivenStateIsExpired( - address _voter, - uint256 _totalPower, - uint256 _votesCast, - uint256 _yeas - ) external givenStateIsNotExecutable { + function test_GivenStateIsExpired(address _voter, uint256 _totalPower, uint256 _votesCast, uint256 _yeas) + external + givenStateIsNotExecutable + { // it revert _stateExpired("empty", _voter, _totalPower, _votesCast, _yeas); assertEq(governance.getProposalState(proposalId), ProposalState.Expired); @@ -103,12 +90,10 @@ contract ExecuteTest is GovernanceBase { _; } - function test_GivenPayloadCallAsset( - address _voter, - uint256 _totalPower, - uint256 _votesCast, - uint256 _yeas - ) external givenStateIsExecutable(_voter, _totalPower, _votesCast, _yeas, "call_asset") { + function test_GivenPayloadCallAsset(address _voter, uint256 _totalPower, uint256 _votesCast, uint256 _yeas) + external + givenStateIsExecutable(_voter, _totalPower, _votesCast, _yeas, "call_asset") + { // it revert vm.expectRevert(abi.encodeWithSelector(Errors.Governance__CannotCallAsset.selector)); @@ -119,12 +104,7 @@ contract ExecuteTest is GovernanceBase { _; } - function test_GivenAPayloadCallFails( - address _voter, - uint256 _totalPower, - uint256 _votesCast, - uint256 _yeas - ) + function test_GivenAPayloadCallFails(address _voter, uint256 _totalPower, uint256 _votesCast, uint256 _yeas) external givenStateIsExecutable(_voter, _totalPower, _votesCast, _yeas, "revert") givenPayloadDontCallAsset @@ -133,19 +113,13 @@ contract ExecuteTest is GovernanceBase { vm.expectRevert( abi.encodeWithSelector( - Errors.Governance__CallFailed.selector, - address(CallRevertingPayload(address(proposal.payload)).TARGET()) + Errors.Governance__CallFailed.selector, address(CallRevertingPayload(address(proposal.payload)).TARGET()) ) ); governance.execute(proposalId); } - function test_GivenAllPayloadCallSucceeds( - address _voter, - uint256 _totalPower, - uint256 _votesCast, - uint256 _yeas - ) + function test_GivenAllPayloadCallSucceeds(address _voter, uint256 _totalPower, uint256 _votesCast, uint256 _yeas) external givenStateIsExecutable(_voter, _totalPower, _votesCast, _yeas, "upgrade") givenPayloadDontCallAsset diff --git a/l1-contracts/test/governance/governance/finaliseWithdraw.t.sol b/l1-contracts/test/governance/governance/finaliseWithdraw.t.sol index 7be8a2deff5e..dafda7e52e75 100644 --- a/l1-contracts/test/governance/governance/finaliseWithdraw.t.sol +++ b/l1-contracts/test/governance/governance/finaliseWithdraw.t.sol @@ -2,9 +2,7 @@ pragma solidity >=0.8.27; import {GovernanceBase} from "./base.t.sol"; -import { - IGovernance, Configuration, Withdrawal -} from "@aztec/governance/interfaces/IGovernance.sol"; +import {IGovernance, Configuration, Withdrawal} from "@aztec/governance/interfaces/IGovernance.sol"; import {IERC20Errors} from "@oz/interfaces/draft-IERC6093.sol"; import {Timestamp} from "@aztec/core/libraries/TimeLib.sol"; import {Errors} from "@aztec/governance/libraries/Errors.sol"; @@ -63,10 +61,7 @@ contract FinaliseWithdrawTest is GovernanceBase { address[WITHDRAWAL_COUNT] memory _recipient, uint256[WITHDRAWAL_COUNT] memory _withdrawals, uint256[WITHDRAWAL_COUNT] memory _timejumps - ) - external - whenItMatchPendingWithdrawal(_activationThreshold, _recipient, _withdrawals, _timejumps) - { + ) external whenItMatchPendingWithdrawal(_activationThreshold, _recipient, _withdrawals, _timejumps) { // it revert uint256 withdrawalCount = governance.withdrawalCount(); @@ -107,16 +102,13 @@ contract FinaliseWithdrawTest is GovernanceBase { } assertGt(withdrawal.unlocksAt, block.timestamp); - uint256 time = - bound(_timejumps2[i], block.timestamp, Timestamp.unwrap(withdrawal.unlocksAt) - 1); + uint256 time = bound(_timejumps2[i], block.timestamp, Timestamp.unwrap(withdrawal.unlocksAt) - 1); vm.warp(time); vm.expectRevert( abi.encodeWithSelector( - Errors.Governance__WithdrawalNotUnlockedYet.selector, - Timestamp.wrap(block.timestamp), - withdrawal.unlocksAt + Errors.Governance__WithdrawalNotUnlockedYet.selector, Timestamp.wrap(block.timestamp), withdrawal.unlocksAt ) ); governance.finaliseWithdraw(i); @@ -144,9 +136,8 @@ contract FinaliseWithdrawTest is GovernanceBase { for (uint256 i = 0; i < withdrawalCount; i++) { Withdrawal memory withdrawal = governance.getWithdrawal(i); - uint256 upper = i + 1 == withdrawalCount - ? type(uint64).max - : Timestamp.unwrap(governance.getWithdrawal(i + 1).unlocksAt); + uint256 upper = + i + 1 == withdrawalCount ? type(uint64).max : Timestamp.unwrap(governance.getWithdrawal(i + 1).unlocksAt); uint256 time = bound(_timejumps2[i], Timestamp.unwrap(withdrawal.unlocksAt), upper); vm.warp(time); @@ -162,9 +153,7 @@ contract FinaliseWithdrawTest is GovernanceBase { sums[withdrawal.recipient] += withdrawal.amount; assertEq(token.balanceOf(address(governance)), sum, "total balance"); - assertEq( - token.balanceOf(withdrawal.recipient), sums[withdrawal.recipient], "recipient balance" - ); + assertEq(token.balanceOf(withdrawal.recipient), sums[withdrawal.recipient], "recipient balance"); } } } diff --git a/l1-contracts/test/governance/governance/getProposalState.t.sol b/l1-contracts/test/governance/governance/getProposalState.t.sol index 76b8e05b62c5..176fbd48b0d6 100644 --- a/l1-contracts/test/governance/governance/getProposalState.t.sol +++ b/l1-contracts/test/governance/governance/getProposalState.t.sol @@ -16,9 +16,7 @@ contract GetProposalStateTest is GovernanceBase { function test_WhenProposalIsOutOfBounds(uint256 _index) external { // it revert uint256 index = bound(_index, governance.proposalCount(), type(uint256).max); - vm.expectRevert( - abi.encodeWithSelector(Errors.Governance__ProposalDoesNotExists.selector, index) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Governance__ProposalDoesNotExists.selector, index)); governance.getProposalState(index); } @@ -30,12 +28,11 @@ contract GetProposalStateTest is GovernanceBase { _; } - function test_GivenStateIsExecuted( - address _voter, - uint256 _totalPower, - uint256 _votesCast, - uint256 _yeas - ) external whenValidProposalId givenStateIsStable { + function test_GivenStateIsExecuted(address _voter, uint256 _totalPower, uint256 _votesCast, uint256 _yeas) + external + whenValidProposalId + givenStateIsStable + { // it return Executed _stateExecutable("empty", _voter, _totalPower, _votesCast, _yeas); governance.execute(proposalId); @@ -44,11 +41,7 @@ contract GetProposalStateTest is GovernanceBase { assertEq(governance.getProposalState(proposalId), ProposalState.Executed); } - function test_GivenStateIsDropped(address _governanceProposer) - external - whenValidProposalId - givenStateIsStable - { + function test_GivenStateIsDropped(address _governanceProposer) external whenValidProposalId givenStateIsStable { // it return Dropped _stateDroppable("empty", _governanceProposer); @@ -140,12 +133,7 @@ contract GetProposalStateTest is GovernanceBase { assertEq(governance.getProposalState(proposalId), ProposalState.Rejected); } - function test_GivenVoteTabulationIsInvalid( - address _voter, - uint256 _totalPower, - uint256 _votesCast, - uint256 _yeas - ) + function test_GivenVoteTabulationIsInvalid(address _voter, uint256 _totalPower, uint256 _votesCast, uint256 _yeas) external whenValidProposalId givenStateIsUnstable @@ -158,8 +146,9 @@ contract GetProposalStateTest is GovernanceBase { // We can overwrite the quorum to be 0 to hit an invalid case assertGt(governance.getProposal(proposalId).config.quorum, 0); - stdstore.target(address(governance)).sig("getProposal(uint256)").with_key(proposalId).depth(6) - .checked_write(uint256(0)); + stdstore.target(address(governance)).sig("getProposal(uint256)").with_key(proposalId).depth(6).checked_write( + uint256(0) + ); assertEq(governance.getProposal(proposalId).config.quorum, 0); uint256 totalPower = governance.totalPowerAt(Timestamp.wrap(block.timestamp)); @@ -170,12 +159,7 @@ contract GetProposalStateTest is GovernanceBase { assertEq(governance.getProposalState(proposalId), ProposalState.Rejected); } - modifier givenVoteTabulationIsAccepted( - address _voter, - uint256 _totalPower, - uint256 _votesCast, - uint256 _yeas - ) { + modifier givenVoteTabulationIsAccepted(address _voter, uint256 _totalPower, uint256 _votesCast, uint256 _yeas) { _stateQueued("empty", _voter, _totalPower, _votesCast, _yeas); _; } @@ -230,12 +214,7 @@ contract GetProposalStateTest is GovernanceBase { assertEq(governance.getProposalState(proposalId), ProposalState.Executable); } - function test_GivenGracePeriodHavePassed( - address _voter, - uint256 _totalPower, - uint256 _votesCast, - uint256 _yeas - ) + function test_GivenGracePeriodHavePassed(address _voter, uint256 _totalPower, uint256 _votesCast, uint256 _yeas) external whenValidProposalId givenStateIsUnstable diff --git a/l1-contracts/test/governance/governance/initiateWithdraw.t.sol b/l1-contracts/test/governance/governance/initiateWithdraw.t.sol index fd0f39c71296..3aa02a73a4f1 100644 --- a/l1-contracts/test/governance/governance/initiateWithdraw.t.sol +++ b/l1-contracts/test/governance/governance/initiateWithdraw.t.sol @@ -2,9 +2,7 @@ pragma solidity >=0.8.27; import {GovernanceBase} from "./base.t.sol"; -import { - IGovernance, Configuration, Withdrawal -} from "@aztec/governance/interfaces/IGovernance.sol"; +import {IGovernance, Configuration, Withdrawal} from "@aztec/governance/interfaces/IGovernance.sol"; import {Timestamp} from "@aztec/core/libraries/TimeLib.sol"; import {Errors} from "@aztec/governance/libraries/Errors.sol"; import {ConfigurationLib} from "@aztec/governance/libraries/ConfigurationLib.sol"; @@ -93,11 +91,7 @@ contract InitiateWithdrawTest is GovernanceBase { Withdrawal memory withdrawal = governance.getWithdrawal(withdrawalId); assertEq(withdrawal.amount, amount, "invalid amount"); - assertEq( - withdrawal.unlocksAt, - Timestamp.wrap(block.timestamp) + config.withdrawalDelay(), - "Invalid timestamp" - ); + assertEq(withdrawal.unlocksAt, Timestamp.wrap(block.timestamp) + config.withdrawalDelay(), "Invalid timestamp"); assertEq(withdrawal.recipient, recipient, "invalid recipient"); assertFalse(withdrawal.claimed, "already claimed"); assertEq(governance.totalPowerAt(Timestamp.wrap(block.timestamp)), sum); diff --git a/l1-contracts/test/governance/governance/limitedDeposit.t.sol b/l1-contracts/test/governance/governance/limitedDeposit.t.sol index 593cc6cb51fc..63af0c6a531a 100644 --- a/l1-contracts/test/governance/governance/limitedDeposit.t.sol +++ b/l1-contracts/test/governance/governance/limitedDeposit.t.sol @@ -14,11 +14,7 @@ import {Errors} from "@aztec/governance/libraries/Errors.sol"; import {IGSE} from "@aztec/governance/GSE.sol"; import {TestConstants} from "@test/harnesses/TestConstants.sol"; -import { - ProposalLib, - VoteTabulationReturn, - VoteTabulationInfo -} from "@aztec/governance/libraries/ProposalLib.sol"; +import {ProposalLib, VoteTabulationReturn, VoteTabulationInfo} from "@aztec/governance/libraries/ProposalLib.sol"; contract LimitedDepositTest is TestBase { IMintableERC20 internal token; @@ -37,9 +33,8 @@ contract LimitedDepositTest is TestBase { registry = new Registry(address(this), token); governanceProposer = new GovernanceProposer(registry, IGSE(address(0x03)), 677, 1000); - governance = new Governance( - token, address(governanceProposer), address(this), TestConstants.getGovernanceConfiguration() - ); + governance = + new Governance(token, address(governanceProposer), address(this), TestConstants.getGovernanceConfiguration()); } function test_WhenNotAllowedToDeposit(address _caller, address _depositor) external { diff --git a/l1-contracts/test/governance/governance/proposallib/static.t.sol b/l1-contracts/test/governance/governance/proposallib/static.t.sol index 6a73b7faf9ab..2cf855b50133 100644 --- a/l1-contracts/test/governance/governance/proposallib/static.t.sol +++ b/l1-contracts/test/governance/governance/proposallib/static.t.sol @@ -12,22 +12,17 @@ contract Static is TestBase { Proposal internal proposal; modifier limitConfig(Configuration memory _config) { - proposal.config.votingDelay = - Timestamp.wrap(bound(Timestamp.unwrap(_config.votingDelay), 0, type(uint32).max)); + proposal.config.votingDelay = Timestamp.wrap(bound(Timestamp.unwrap(_config.votingDelay), 0, type(uint32).max)); proposal.config.votingDuration = Timestamp.wrap(bound(Timestamp.unwrap(_config.votingDuration), 0, type(uint32).max)); proposal.config.executionDelay = Timestamp.wrap(bound(Timestamp.unwrap(_config.executionDelay), 0, type(uint32).max)); - proposal.config.gracePeriod = - Timestamp.wrap(bound(Timestamp.unwrap(_config.gracePeriod), 0, type(uint32).max)); + proposal.config.gracePeriod = Timestamp.wrap(bound(Timestamp.unwrap(_config.gracePeriod), 0, type(uint32).max)); _; } - function test_pendingThrough(Configuration memory _config, uint256 _creation) - external - limitConfig(_config) - { + function test_pendingThrough(Configuration memory _config, uint256 _creation) external limitConfig(_config) { proposal.creation = Timestamp.wrap(bound(_creation, 0, type(uint32).max)); assertEq(proposal.pendingThrough(), proposal.creation + proposal.config.votingDelay); @@ -35,38 +30,25 @@ contract Static is TestBase { assertEq(proposalMemory.pendingThroughMemory(), proposal.creation + proposal.config.votingDelay); } - function test_activeThrough(Configuration memory _config, uint256 _creation) - external - limitConfig(_config) - { + function test_activeThrough(Configuration memory _config, uint256 _creation) external limitConfig(_config) { proposal.creation = Timestamp.wrap(bound(_creation, 0, type(uint32).max)); - assertEq( - proposal.activeThrough(), - proposal.creation + proposal.config.votingDelay + proposal.config.votingDuration - ); + assertEq(proposal.activeThrough(), proposal.creation + proposal.config.votingDelay + proposal.config.votingDuration); } - function test_queuedThrough(Configuration memory _config, uint256 _creation) - external - limitConfig(_config) - { + function test_queuedThrough(Configuration memory _config, uint256 _creation) external limitConfig(_config) { proposal.creation = Timestamp.wrap(bound(_creation, 0, type(uint32).max)); assertEq( proposal.queuedThrough(), - proposal.creation + proposal.config.votingDelay + proposal.config.votingDuration - + proposal.config.executionDelay + proposal.creation + proposal.config.votingDelay + proposal.config.votingDuration + proposal.config.executionDelay ); } - function test_executableThrough(Configuration memory _config, uint256 _creation) - external - limitConfig(_config) - { + function test_executableThrough(Configuration memory _config, uint256 _creation) external limitConfig(_config) { proposal.creation = Timestamp.wrap(bound(_creation, 0, type(uint32).max)); assertEq( proposal.executableThrough(), - proposal.creation + proposal.config.votingDelay + proposal.config.votingDuration - + proposal.config.executionDelay + proposal.config.gracePeriod + proposal.creation + proposal.config.votingDelay + proposal.config.votingDuration + proposal.config.executionDelay + + proposal.config.gracePeriod ); } } diff --git a/l1-contracts/test/governance/governance/proposallib/voteTabulation.t.sol b/l1-contracts/test/governance/governance/proposallib/voteTabulation.t.sol index e975717f8a4e..5124df822eb2 100644 --- a/l1-contracts/test/governance/governance/proposallib/voteTabulation.t.sol +++ b/l1-contracts/test/governance/governance/proposallib/voteTabulation.t.sol @@ -3,11 +3,7 @@ pragma solidity >=0.8.27; import {GovernanceBase} from "../base.t.sol"; import {Configuration, Proposal} from "@aztec/governance/interfaces/IGovernance.sol"; -import { - ProposalLib, - VoteTabulationReturn, - VoteTabulationInfo -} from "@aztec/governance/libraries/ProposalLib.sol"; +import {ProposalLib, VoteTabulationReturn, VoteTabulationInfo} from "@aztec/governance/libraries/ProposalLib.sol"; import {ConfigurationLib} from "@aztec/governance/libraries/ConfigurationLib.sol"; import {Math, Panic} from "@oz/utils/math/Math.sol"; @@ -29,8 +25,7 @@ contract VoteTabulationTest is GovernanceBase { } modifier whenMinimumGt0(Configuration memory _config) { - proposal.config.minimumVotes = - bound(_config.minimumVotes, ConfigurationLib.VOTES_LOWER, type(uint256).max); + proposal.config.minimumVotes = bound(_config.minimumVotes, ConfigurationLib.VOTES_LOWER, type(uint256).max); _; } @@ -78,8 +73,7 @@ contract VoteTabulationTest is GovernanceBase { // Overwriting some limits such that we do not overflow uint256 upperLimit = Math.mulDiv(type(uint256).max, 1e18, proposal.config.quorum); - proposal.config.minimumVotes = - bound(_config.minimumVotes, ConfigurationLib.VOTES_LOWER, upperLimit); + proposal.config.minimumVotes = bound(_config.minimumVotes, ConfigurationLib.VOTES_LOWER, upperLimit); totalPower = bound(_totalPower, proposal.config.minimumVotes, upperLimit); (VoteTabulationReturn vtr, VoteTabulationInfo vti) = proposal.voteTabulation(totalPower); @@ -101,8 +95,7 @@ contract VoteTabulationTest is GovernanceBase { } modifier whenQuorumConfigValid(Configuration memory _config) { - proposal.config.quorum = - bound(_config.quorum, ConfigurationLib.QUORUM_LOWER, ConfigurationLib.QUORUM_UPPER); + proposal.config.quorum = bound(_config.quorum, ConfigurationLib.QUORUM_LOWER, ConfigurationLib.QUORUM_UPPER); votesNeeded = Math.mulDiv(totalPower, proposal.config.quorum, 1e18, Math.Rounding.Ceil); _; @@ -113,12 +106,7 @@ contract VoteTabulationTest is GovernanceBase { uint256 _totalPower, uint256 _votes, uint256 _yea - ) - external - whenMinimumGt0(_config) - whenTotalPowerGteMinimum(_totalPower) - whenQuorumConfigValid(_config) - { + ) external whenMinimumGt0(_config) whenTotalPowerGteMinimum(_totalPower) whenQuorumConfigValid(_config) { // it return (Rejected, VotesCastLtVotesNeeded) uint256 maxVotes = votesNeeded > 0 ? votesNeeded - 1 : votesNeeded; @@ -159,11 +147,7 @@ contract VoteTabulationTest is GovernanceBase { // which is already handled as `votesCast >= votesNeeded` and `votesNeeded > 0`. } - function test_WhenYeaLimitGtUint256Max( - Configuration memory _config, - uint256 _totalPower, - uint256 _votes - ) + function test_WhenYeaLimitGtUint256Max(Configuration memory _config, uint256 _totalPower, uint256 _votes) external whenMinimumGt0(_config) whenTotalPowerGteMinimum(_totalPower) @@ -180,11 +164,7 @@ contract VoteTabulationTest is GovernanceBase { this.callVoteTabulation(totalPower); } - function test_WhenYeaLimitGtVotesCast( - Configuration memory _config, - uint256 _totalPower, - uint256 _votes - ) + function test_WhenYeaLimitGtVotesCast(Configuration memory _config, uint256 _totalPower, uint256 _votes) external whenMinimumGt0(_config) whenTotalPowerGteMinimum(_totalPower) @@ -197,8 +177,7 @@ contract VoteTabulationTest is GovernanceBase { // Overwriting some limits such that we do not overflow uint256 upperLimit = Math.mulDiv(type(uint256).max, 1e18, proposal.config.requiredYeaMargin); - proposal.config.minimumVotes = - bound(_config.minimumVotes, ConfigurationLib.VOTES_LOWER, upperLimit); + proposal.config.minimumVotes = bound(_config.minimumVotes, ConfigurationLib.VOTES_LOWER, upperLimit); totalPower = bound(_totalPower, proposal.config.minimumVotes, upperLimit); votesNeeded = Math.mulDiv(totalPower, proposal.config.quorum, 1e18, Math.Rounding.Ceil); votes = bound(_votes, votesNeeded, totalPower); @@ -210,19 +189,14 @@ contract VoteTabulationTest is GovernanceBase { } modifier whenDifferentialConfigValid(Configuration memory _config) { - proposal.config.requiredYeaMargin = - bound(_config.requiredYeaMargin, 0, ConfigurationLib.REQUIRED_YEA_MARGIN_UPPER); + proposal.config.requiredYeaMargin = bound(_config.requiredYeaMargin, 0, ConfigurationLib.REQUIRED_YEA_MARGIN_UPPER); uint256 yeaFraction = Math.ceilDiv(1e18 + proposal.config.requiredYeaMargin, 2); yeaLimit = Math.mulDiv(votes, yeaFraction, 1e18, Math.Rounding.Ceil); _; } - function test_WhenYeaVotesEqVotesCast( - Configuration memory _config, - uint256 _totalPower, - uint256 _votes - ) + function test_WhenYeaVotesEqVotesCast(Configuration memory _config, uint256 _totalPower, uint256 _votes) external whenMinimumGt0(_config) whenTotalPowerGteMinimum(_totalPower) @@ -238,12 +212,7 @@ contract VoteTabulationTest is GovernanceBase { assertEq(vti, VoteTabulationInfo.YeaVotesEqVotesCast, "invalid info value"); } - function test_WhenYeaVotesLteYeaLimit( - Configuration memory _config, - uint256 _totalPower, - uint256 _votes, - uint256 _yea - ) + function test_WhenYeaVotesLteYeaLimit(Configuration memory _config, uint256 _totalPower, uint256 _votes, uint256 _yea) external whenMinimumGt0(_config) whenTotalPowerGteMinimum(_totalPower) @@ -270,12 +239,7 @@ contract VoteTabulationTest is GovernanceBase { assertEq(vti, VoteTabulationInfo.YeaVotesLeYeaLimit, "invalid info value"); } - function test_WhenYeaVotesGtYeaLimit( - Configuration memory _config, - uint256 _totalPower, - uint256 _votes, - uint256 _yea - ) + function test_WhenYeaVotesGtYeaLimit(Configuration memory _config, uint256 _totalPower, uint256 _votes, uint256 _yea) external whenMinimumGt0(_config) whenTotalPowerGteMinimum(_totalPower) diff --git a/l1-contracts/test/governance/governance/propose.t.sol b/l1-contracts/test/governance/governance/propose.t.sol index a71eb851ee25..a049a31ad48c 100644 --- a/l1-contracts/test/governance/governance/propose.t.sol +++ b/l1-contracts/test/governance/governance/propose.t.sol @@ -3,12 +3,7 @@ pragma solidity >=0.8.27; import {IPayload} from "@aztec/governance/interfaces/IPayload.sol"; import {GovernanceBase} from "./base.t.sol"; -import { - IGovernance, - Configuration, - Proposal, - ProposalState -} from "@aztec/governance/interfaces/IGovernance.sol"; +import {IGovernance, Configuration, Proposal, ProposalState} from "@aztec/governance/interfaces/IGovernance.sol"; import {Timestamp} from "@aztec/core/libraries/TimeLib.sol"; import {Errors} from "@aztec/governance/libraries/Errors.sol"; @@ -17,9 +12,7 @@ contract ProposeTest is GovernanceBase { // it revert vm.expectRevert( abi.encodeWithSelector( - Errors.Governance__CallerNotGovernanceProposer.selector, - address(this), - address(governanceProposer) + Errors.Governance__CallerNotGovernanceProposer.selector, address(this), address(governanceProposer) ) ); governance.propose(IPayload(address(0))); diff --git a/l1-contracts/test/governance/governance/proposeWithLock.t.sol b/l1-contracts/test/governance/governance/proposeWithLock.t.sol index 56490a357714..599b5dda200d 100644 --- a/l1-contracts/test/governance/governance/proposeWithLock.t.sol +++ b/l1-contracts/test/governance/governance/proposeWithLock.t.sol @@ -3,12 +3,7 @@ pragma solidity >=0.8.27; import {IPayload} from "@aztec/governance/interfaces/IPayload.sol"; import {GovernanceBase} from "./base.t.sol"; -import { - IGovernance, - Configuration, - Proposal, - ProposalState -} from "@aztec/governance/interfaces/IGovernance.sol"; +import {IGovernance, Configuration, Proposal, ProposalState} from "@aztec/governance/interfaces/IGovernance.sol"; import {Timestamp} from "@aztec/core/libraries/TimeLib.sol"; import {Errors} from "@aztec/governance/libraries/Errors.sol"; diff --git a/l1-contracts/test/governance/governance/scenarios/lockAndPass.t.sol b/l1-contracts/test/governance/governance/scenarios/lockAndPass.t.sol index 4dc072128c5c..6e8a6adb7712 100644 --- a/l1-contracts/test/governance/governance/scenarios/lockAndPass.t.sol +++ b/l1-contracts/test/governance/governance/scenarios/lockAndPass.t.sol @@ -4,12 +4,7 @@ pragma solidity >=0.8.27; import {IPayload} from "@aztec/governance/interfaces/IPayload.sol"; import {IRollup} from "@aztec/core/interfaces/IRollup.sol"; import {GovernanceBase} from "../base.t.sol"; -import { - IGovernance, - Proposal, - ProposalState, - Configuration -} from "@aztec/governance/interfaces/IGovernance.sol"; +import {IGovernance, Proposal, ProposalState, Configuration} from "@aztec/governance/interfaces/IGovernance.sol"; import {Timestamp} from "@aztec/core/libraries/TimeLib.sol"; import {Errors} from "@aztec/governance/libraries/Errors.sol"; import {UpgradePayload, FakeRollup} from "../TestPayloads.sol"; diff --git a/l1-contracts/test/governance/governance/scenarios/noVoteAndExit.t.sol b/l1-contracts/test/governance/governance/scenarios/noVoteAndExit.t.sol index 028bfe62a9c7..a30263969494 100644 --- a/l1-contracts/test/governance/governance/scenarios/noVoteAndExit.t.sol +++ b/l1-contracts/test/governance/governance/scenarios/noVoteAndExit.t.sol @@ -13,12 +13,7 @@ contract NoVoteAndExitTest is GovernanceBase { // Ensure that it is not possible to BOTH vote on proposal AND withdraw the funds before // it can be executed - function test_CannotVoteAndExit( - address _voter, - uint256 _totalPower, - uint256 _votesCast, - uint256 _yeas - ) external { + function test_CannotVoteAndExit(address _voter, uint256 _totalPower, uint256 _votesCast, uint256 _yeas) external { bytes32 _proposalName = "empty"; vm.assume(_voter != address(0)); @@ -64,9 +59,7 @@ contract NoVoteAndExitTest is GovernanceBase { vm.expectRevert( abi.encodeWithSelector( - Errors.Governance__WithdrawalNotUnlockedYet.selector, - Timestamp.wrap(block.timestamp), - withdrawal.unlocksAt + Errors.Governance__WithdrawalNotUnlockedYet.selector, Timestamp.wrap(block.timestamp), withdrawal.unlocksAt ) ); governance.finaliseWithdraw(withdrawalId); diff --git a/l1-contracts/test/governance/governance/updateConfiguration.t.sol b/l1-contracts/test/governance/governance/updateConfiguration.t.sol index ba859d36ec43..911ba8b77369 100644 --- a/l1-contracts/test/governance/governance/updateConfiguration.t.sol +++ b/l1-contracts/test/governance/governance/updateConfiguration.t.sol @@ -23,9 +23,7 @@ contract UpdateConfigurationTest is GovernanceBase { function test_WhenCallerIsNotSelf() external { // it revert vm.expectRevert( - abi.encodeWithSelector( - Errors.Governance__CallerNotSelf.selector, address(this), address(governance) - ) + abi.encodeWithSelector(Errors.Governance__CallerNotSelf.selector, address(this), address(governance)) ); governance.updateConfiguration(config); } @@ -38,213 +36,122 @@ contract UpdateConfigurationTest is GovernanceBase { _; } - function test_WhenQuorumLtMinOrGtMax(uint256 _val) - external - whenCallerIsSelf - whenConfigurationIsInvalid - { + function test_WhenQuorumLtMinOrGtMax(uint256 _val) external whenCallerIsSelf whenConfigurationIsInvalid { // it revert config.quorum = bound(_val, 0, ConfigurationLib.QUORUM_LOWER - 1); - vm.expectRevert( - abi.encodeWithSelector(Errors.Governance__ConfigurationLib__QuorumTooSmall.selector) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Governance__ConfigurationLib__QuorumTooSmall.selector)); vm.prank(address(governance)); governance.updateConfiguration(config); config.quorum = bound(_val, ConfigurationLib.QUORUM_UPPER + 1, type(uint256).max); - vm.expectRevert( - abi.encodeWithSelector(Errors.Governance__ConfigurationLib__QuorumTooBig.selector) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Governance__ConfigurationLib__QuorumTooBig.selector)); vm.prank(address(governance)); governance.updateConfiguration(config); } - function test_WhenDifferentialLtMinOrGtMax(uint256 _val) - external - whenCallerIsSelf - whenConfigurationIsInvalid - { + function test_WhenDifferentialLtMinOrGtMax(uint256 _val) external whenCallerIsSelf whenConfigurationIsInvalid { // it revert - config.requiredYeaMargin = - bound(_val, ConfigurationLib.REQUIRED_YEA_MARGIN_UPPER + 1, type(uint256).max); - vm.expectRevert( - abi.encodeWithSelector(Errors.Governance__ConfigurationLib__RequiredYeaMarginTooBig.selector) - ); + config.requiredYeaMargin = bound(_val, ConfigurationLib.REQUIRED_YEA_MARGIN_UPPER + 1, type(uint256).max); + vm.expectRevert(abi.encodeWithSelector(Errors.Governance__ConfigurationLib__RequiredYeaMarginTooBig.selector)); vm.prank(address(governance)); governance.updateConfiguration(config); } - function test_WhenMinimumVotesLtMin(uint256 _val) - external - whenCallerIsSelf - whenConfigurationIsInvalid - { + function test_WhenMinimumVotesLtMin(uint256 _val) external whenCallerIsSelf whenConfigurationIsInvalid { // it revert config.minimumVotes = bound(_val, 0, ConfigurationLib.VOTES_LOWER - 1); - vm.expectRevert( - abi.encodeWithSelector(Errors.Governance__ConfigurationLib__InvalidMinimumVotes.selector) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Governance__ConfigurationLib__InvalidMinimumVotes.selector)); vm.prank(address(governance)); governance.updateConfiguration(config); } - function test_WhenLockAmountLtMin(uint256 _val) - external - whenCallerIsSelf - whenConfigurationIsInvalid - { + function test_WhenLockAmountLtMin(uint256 _val) external whenCallerIsSelf whenConfigurationIsInvalid { // it revert config.proposeConfig.lockAmount = bound(_val, 0, ConfigurationLib.VOTES_LOWER - 1); - vm.expectRevert( - abi.encodeWithSelector(Errors.Governance__ConfigurationLib__LockAmountTooSmall.selector) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Governance__ConfigurationLib__LockAmountTooSmall.selector)); vm.prank(address(governance)); governance.updateConfiguration(config); } - function test_WhenLockDelayLtMinOrGtMax(uint256 _val) - external - whenCallerIsSelf - whenConfigurationIsInvalid - { + function test_WhenLockDelayLtMinOrGtMax(uint256 _val) external whenCallerIsSelf whenConfigurationIsInvalid { // it revert - config.proposeConfig.lockDelay = - Timestamp.wrap(bound(_val, 0, Timestamp.unwrap(ConfigurationLib.TIME_LOWER) - 1)); - vm.expectRevert( - abi.encodeWithSelector( - Errors.Governance__ConfigurationLib__TimeTooSmall.selector, "LockDelay" - ) - ); + config.proposeConfig.lockDelay = Timestamp.wrap(bound(_val, 0, Timestamp.unwrap(ConfigurationLib.TIME_LOWER) - 1)); + vm.expectRevert(abi.encodeWithSelector(Errors.Governance__ConfigurationLib__TimeTooSmall.selector, "LockDelay")); vm.prank(address(governance)); governance.updateConfiguration(config); - config.proposeConfig.lockDelay = Timestamp.wrap( - bound(_val, Timestamp.unwrap(ConfigurationLib.TIME_UPPER) + 1, type(uint256).max) - ); - vm.expectRevert( - abi.encodeWithSelector(Errors.Governance__ConfigurationLib__TimeTooBig.selector, "LockDelay") - ); + config.proposeConfig.lockDelay = + Timestamp.wrap(bound(_val, Timestamp.unwrap(ConfigurationLib.TIME_UPPER) + 1, type(uint256).max)); + vm.expectRevert(abi.encodeWithSelector(Errors.Governance__ConfigurationLib__TimeTooBig.selector, "LockDelay")); vm.prank(address(governance)); governance.updateConfiguration(config); } - function test_WhenVotingDelayLtMinOrGtMax(uint256 _val) - external - whenCallerIsSelf - whenConfigurationIsInvalid - { + function test_WhenVotingDelayLtMinOrGtMax(uint256 _val) external whenCallerIsSelf whenConfigurationIsInvalid { // it revert - config.votingDelay = - Timestamp.wrap(bound(_val, 0, Timestamp.unwrap(ConfigurationLib.TIME_LOWER) - 1)); - vm.expectRevert( - abi.encodeWithSelector( - Errors.Governance__ConfigurationLib__TimeTooSmall.selector, "VotingDelay" - ) - ); + config.votingDelay = Timestamp.wrap(bound(_val, 0, Timestamp.unwrap(ConfigurationLib.TIME_LOWER) - 1)); + vm.expectRevert(abi.encodeWithSelector(Errors.Governance__ConfigurationLib__TimeTooSmall.selector, "VotingDelay")); vm.prank(address(governance)); governance.updateConfiguration(config); - config.votingDelay = Timestamp.wrap( - bound(_val, Timestamp.unwrap(ConfigurationLib.TIME_UPPER) + 1, type(uint256).max) - ); - vm.expectRevert( - abi.encodeWithSelector( - Errors.Governance__ConfigurationLib__TimeTooBig.selector, "VotingDelay" - ) - ); + config.votingDelay = + Timestamp.wrap(bound(_val, Timestamp.unwrap(ConfigurationLib.TIME_UPPER) + 1, type(uint256).max)); + vm.expectRevert(abi.encodeWithSelector(Errors.Governance__ConfigurationLib__TimeTooBig.selector, "VotingDelay")); vm.prank(address(governance)); governance.updateConfiguration(config); } - function test_WhenVotingDurationLtMinOrGtMax(uint256 _val) - external - whenCallerIsSelf - whenConfigurationIsInvalid - { + function test_WhenVotingDurationLtMinOrGtMax(uint256 _val) external whenCallerIsSelf whenConfigurationIsInvalid { // it revert - config.votingDuration = - Timestamp.wrap(bound(_val, 0, Timestamp.unwrap(ConfigurationLib.TIME_LOWER) - 1)); + config.votingDuration = Timestamp.wrap(bound(_val, 0, Timestamp.unwrap(ConfigurationLib.TIME_LOWER) - 1)); vm.expectRevert( - abi.encodeWithSelector( - Errors.Governance__ConfigurationLib__TimeTooSmall.selector, "VotingDuration" - ) + abi.encodeWithSelector(Errors.Governance__ConfigurationLib__TimeTooSmall.selector, "VotingDuration") ); vm.prank(address(governance)); governance.updateConfiguration(config); - config.votingDuration = Timestamp.wrap( - bound(_val, Timestamp.unwrap(ConfigurationLib.TIME_UPPER) + 1, type(uint256).max) - ); - vm.expectRevert( - abi.encodeWithSelector( - Errors.Governance__ConfigurationLib__TimeTooBig.selector, "VotingDuration" - ) - ); + config.votingDuration = + Timestamp.wrap(bound(_val, Timestamp.unwrap(ConfigurationLib.TIME_UPPER) + 1, type(uint256).max)); + vm.expectRevert(abi.encodeWithSelector(Errors.Governance__ConfigurationLib__TimeTooBig.selector, "VotingDuration")); vm.prank(address(governance)); governance.updateConfiguration(config); } - function test_WhenExecutionDelayLtMinOrGtMax(uint256 _val) - external - whenCallerIsSelf - whenConfigurationIsInvalid - { + function test_WhenExecutionDelayLtMinOrGtMax(uint256 _val) external whenCallerIsSelf whenConfigurationIsInvalid { // it revert - config.executionDelay = - Timestamp.wrap(bound(_val, 0, Timestamp.unwrap(ConfigurationLib.TIME_LOWER) - 1)); + config.executionDelay = Timestamp.wrap(bound(_val, 0, Timestamp.unwrap(ConfigurationLib.TIME_LOWER) - 1)); vm.expectRevert( - abi.encodeWithSelector( - Errors.Governance__ConfigurationLib__TimeTooSmall.selector, "ExecutionDelay" - ) + abi.encodeWithSelector(Errors.Governance__ConfigurationLib__TimeTooSmall.selector, "ExecutionDelay") ); vm.prank(address(governance)); governance.updateConfiguration(config); - config.executionDelay = Timestamp.wrap( - bound(_val, Timestamp.unwrap(ConfigurationLib.TIME_UPPER) + 1, type(uint256).max) - ); - vm.expectRevert( - abi.encodeWithSelector( - Errors.Governance__ConfigurationLib__TimeTooBig.selector, "ExecutionDelay" - ) - ); + config.executionDelay = + Timestamp.wrap(bound(_val, Timestamp.unwrap(ConfigurationLib.TIME_UPPER) + 1, type(uint256).max)); + vm.expectRevert(abi.encodeWithSelector(Errors.Governance__ConfigurationLib__TimeTooBig.selector, "ExecutionDelay")); vm.prank(address(governance)); governance.updateConfiguration(config); } - function test_WhenGracePeriodLtMinOrGtMax(uint256 _val) - external - whenCallerIsSelf - whenConfigurationIsInvalid - { + function test_WhenGracePeriodLtMinOrGtMax(uint256 _val) external whenCallerIsSelf whenConfigurationIsInvalid { // it revert - config.gracePeriod = - Timestamp.wrap(bound(_val, 0, Timestamp.unwrap(ConfigurationLib.TIME_LOWER) - 1)); - vm.expectRevert( - abi.encodeWithSelector( - Errors.Governance__ConfigurationLib__TimeTooSmall.selector, "GracePeriod" - ) - ); + config.gracePeriod = Timestamp.wrap(bound(_val, 0, Timestamp.unwrap(ConfigurationLib.TIME_LOWER) - 1)); + vm.expectRevert(abi.encodeWithSelector(Errors.Governance__ConfigurationLib__TimeTooSmall.selector, "GracePeriod")); vm.prank(address(governance)); governance.updateConfiguration(config); - config.gracePeriod = Timestamp.wrap( - bound(_val, Timestamp.unwrap(ConfigurationLib.TIME_UPPER) + 1, type(uint256).max) - ); - vm.expectRevert( - abi.encodeWithSelector( - Errors.Governance__ConfigurationLib__TimeTooBig.selector, "GracePeriod" - ) - ); + config.gracePeriod = + Timestamp.wrap(bound(_val, Timestamp.unwrap(ConfigurationLib.TIME_UPPER) + 1, type(uint256).max)); + vm.expectRevert(abi.encodeWithSelector(Errors.Governance__ConfigurationLib__TimeTooBig.selector, "GracePeriod")); vm.prank(address(governance)); governance.updateConfiguration(config); } @@ -274,8 +181,7 @@ contract UpdateConfigurationTest is GovernanceBase { assertEq(config.withdrawalDelay(), fresh.withdrawalDelay()); assertEq( config.withdrawalDelay(), - Timestamp.wrap(Timestamp.unwrap(fresh.votingDelay) / 5) + fresh.votingDuration - + fresh.executionDelay + Timestamp.wrap(Timestamp.unwrap(fresh.votingDelay) / 5) + fresh.votingDuration + fresh.executionDelay ); assertEq(config.proposeConfig.lockAmount, fresh.proposeConfig.lockAmount); assertEq(config.proposeConfig.lockDelay, fresh.proposeConfig.lockDelay); @@ -285,17 +191,12 @@ contract UpdateConfigurationTest is GovernanceBase { old.executionDelay == fresh.executionDelay && old.gracePeriod == fresh.gracePeriod && old.minimumVotes == fresh.minimumVotes && old.quorum == fresh.quorum && old.requiredYeaMargin == fresh.requiredYeaMargin && old.votingDelay == fresh.votingDelay - && old.votingDuration == fresh.votingDuration - && old.proposeConfig.lockAmount == fresh.proposeConfig.lockAmount + && old.votingDuration == fresh.votingDuration && old.proposeConfig.lockAmount == fresh.proposeConfig.lockAmount && old.proposeConfig.lockDelay == fresh.proposeConfig.lockDelay ); } - function test_WhenQuorumGeMinAndLeMax(uint256 _val) - external - whenCallerIsSelf - whenConfigurationIsValid - { + function test_WhenQuorumGeMinAndLeMax(uint256 _val) external whenCallerIsSelf whenConfigurationIsValid { // it updates the configuration // it emits {ConfigurationUpdated} event @@ -305,11 +206,7 @@ contract UpdateConfigurationTest is GovernanceBase { config.quorum = val; } - function test_WhenRequiredYeaMarginGeMinAndLeMax(uint256 _val) - external - whenCallerIsSelf - whenConfigurationIsValid - { + function test_WhenRequiredYeaMarginGeMinAndLeMax(uint256 _val) external whenCallerIsSelf whenConfigurationIsValid { // it updates the configuration // it emits {ConfigurationUpdated} event @@ -319,11 +216,7 @@ contract UpdateConfigurationTest is GovernanceBase { config.requiredYeaMargin = val; } - function test_WhenMinimumVotesGeMin(uint256 _val) - external - whenCallerIsSelf - whenConfigurationIsValid - { + function test_WhenMinimumVotesGeMin(uint256 _val) external whenCallerIsSelf whenConfigurationIsValid { // it updates the configuration // it emits {ConfigurationUpdated} event @@ -333,11 +226,7 @@ contract UpdateConfigurationTest is GovernanceBase { config.minimumVotes = val; } - function test_WhenLockAmountGeMin(uint256 _val) - external - whenCallerIsSelf - whenConfigurationIsValid - { + function test_WhenLockAmountGeMin(uint256 _val) external whenCallerIsSelf whenConfigurationIsValid { // it updates the configuration // it emits {ConfigurationUpdated} event @@ -347,97 +236,57 @@ contract UpdateConfigurationTest is GovernanceBase { config.proposeConfig.lockAmount = val; } - function test_WhenLockDelayGeMinAndLeMax(uint256 _val) - external - whenCallerIsSelf - whenConfigurationIsValid - { + function test_WhenLockDelayGeMinAndLeMax(uint256 _val) external whenCallerIsSelf whenConfigurationIsValid { // it updates the configuration // it emits {ConfigurationUpdated} event Timestamp val = Timestamp.wrap( - bound( - _val, - Timestamp.unwrap(ConfigurationLib.TIME_LOWER), - Timestamp.unwrap(ConfigurationLib.TIME_UPPER) - ) + bound(_val, Timestamp.unwrap(ConfigurationLib.TIME_LOWER), Timestamp.unwrap(ConfigurationLib.TIME_UPPER)) ); vm.assume(val != config.proposeConfig.lockDelay); config.proposeConfig.lockDelay = val; } - function test_WhenVotingDelayGeMinAndLeMax(uint256 _val) - external - whenCallerIsSelf - whenConfigurationIsValid - { + function test_WhenVotingDelayGeMinAndLeMax(uint256 _val) external whenCallerIsSelf whenConfigurationIsValid { // it updates the configuration // it emits {ConfigurationUpdated} event Timestamp val = Timestamp.wrap( - bound( - _val, - Timestamp.unwrap(ConfigurationLib.TIME_LOWER), - Timestamp.unwrap(ConfigurationLib.TIME_UPPER) - ) + bound(_val, Timestamp.unwrap(ConfigurationLib.TIME_LOWER), Timestamp.unwrap(ConfigurationLib.TIME_UPPER)) ); vm.assume(val != config.votingDelay); config.votingDelay = val; } - function test_WhenVotingDurationGeMinAndLeMax(uint256 _val) - external - whenCallerIsSelf - whenConfigurationIsValid - { + function test_WhenVotingDurationGeMinAndLeMax(uint256 _val) external whenCallerIsSelf whenConfigurationIsValid { // it updates the configuration // it emits {ConfigurationUpdated} event Timestamp val = Timestamp.wrap( - bound( - _val, - Timestamp.unwrap(ConfigurationLib.TIME_LOWER), - Timestamp.unwrap(ConfigurationLib.TIME_UPPER) - ) + bound(_val, Timestamp.unwrap(ConfigurationLib.TIME_LOWER), Timestamp.unwrap(ConfigurationLib.TIME_UPPER)) ); vm.assume(val != config.votingDuration); config.votingDuration = val; } - function test_WhenExecutionDelayGeMinAndLeMax(uint256 _val) - external - whenCallerIsSelf - whenConfigurationIsValid - { + function test_WhenExecutionDelayGeMinAndLeMax(uint256 _val) external whenCallerIsSelf whenConfigurationIsValid { // it updates the configuration // it emits {ConfigurationUpdated} event Timestamp val = Timestamp.wrap( - bound( - _val, - Timestamp.unwrap(ConfigurationLib.TIME_LOWER), - Timestamp.unwrap(ConfigurationLib.TIME_UPPER) - ) + bound(_val, Timestamp.unwrap(ConfigurationLib.TIME_LOWER), Timestamp.unwrap(ConfigurationLib.TIME_UPPER)) ); vm.assume(val != config.executionDelay); config.executionDelay = val; } - function test_WhenGracePeriodGeMinAndLeMax(uint256 _val) - external - whenCallerIsSelf - whenConfigurationIsValid - { + function test_WhenGracePeriodGeMinAndLeMax(uint256 _val) external whenCallerIsSelf whenConfigurationIsValid { // it updates the configuration // it emits {ConfigurationUpdated} event Timestamp val = Timestamp.wrap( - bound( - _val, - Timestamp.unwrap(ConfigurationLib.TIME_LOWER), - Timestamp.unwrap(ConfigurationLib.TIME_UPPER) - ) + bound(_val, Timestamp.unwrap(ConfigurationLib.TIME_LOWER), Timestamp.unwrap(ConfigurationLib.TIME_UPPER)) ); vm.assume(val != config.gracePeriod); diff --git a/l1-contracts/test/governance/governance/updateGovernanceProposer.t.sol b/l1-contracts/test/governance/governance/updateGovernanceProposer.t.sol index b7cc3fc456d0..42e63c6d03a6 100644 --- a/l1-contracts/test/governance/governance/updateGovernanceProposer.t.sol +++ b/l1-contracts/test/governance/governance/updateGovernanceProposer.t.sol @@ -9,11 +9,7 @@ contract UpdateGovernanceProposerTest is GovernanceBase { function test_WhenCallerIsNotGovernance(address _caller, address _governanceProposer) external { // it revert vm.assume(_caller != address(governance)); - vm.expectRevert( - abi.encodeWithSelector( - Errors.Governance__CallerNotSelf.selector, _caller, address(governance) - ) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Governance__CallerNotSelf.selector, _caller, address(governance))); vm.prank(_caller); governance.updateGovernanceProposer(_governanceProposer); } @@ -26,16 +22,11 @@ contract UpdateGovernanceProposerTest is GovernanceBase { function test_WhenNewGovernanceProposerIsGovernance() external whenCallerIsGovernance { // it revert - vm.expectRevert( - abi.encodeWithSelector(Errors.Governance__GovernanceProposerCannotBeSelf.selector) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Governance__GovernanceProposerCannotBeSelf.selector)); governance.updateGovernanceProposer(address(governance)); } - function test_WhenNewGovernanceProposerIsNotGovernance(address _governanceProposer) - external - whenCallerIsGovernance - { + function test_WhenNewGovernanceProposerIsNotGovernance(address _governanceProposer) external whenCallerIsGovernance { // it updates the governanceProposer // it emit the {GovernanceProposerUpdated} event diff --git a/l1-contracts/test/governance/governance/vote.t.sol b/l1-contracts/test/governance/governance/vote.t.sol index bbd086068105..b45677f14573 100644 --- a/l1-contracts/test/governance/governance/vote.t.sol +++ b/l1-contracts/test/governance/governance/vote.t.sol @@ -72,12 +72,10 @@ contract VoteTest is GovernanceBase { assertEq(governance.getProposalState(proposalId), ProposalState.Rejected); } - function test_GivenStateIsDropped( - address _voter, - uint256 _amount, - bool _support, - address _proposer - ) external givenStateIsNotActive(_voter, _amount, _support) { + function test_GivenStateIsDropped(address _voter, uint256 _amount, bool _support, address _proposer) + external + givenStateIsNotActive(_voter, _amount, _support) + { // it revert _stateDroppable("empty", _proposer); governance.dropProposal(proposalId); @@ -125,11 +123,7 @@ contract VoteTest is GovernanceBase { uint256 power = bound(_votePower, depositPower + 1, type(uint256).max); - vm.expectRevert( - abi.encodeWithSelector( - Errors.Governance__InsufficientPower.selector, _voter, depositPower, power - ) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Governance__InsufficientPower.selector, _voter, depositPower, power)); vm.prank(_voter); governance.vote(proposalId, power, _support); } diff --git a/l1-contracts/test/governance/gse/gse/addRollup.t.sol b/l1-contracts/test/governance/gse/gse/addRollup.t.sol index 0f59f32617e4..9dcce422aa36 100644 --- a/l1-contracts/test/governance/gse/gse/addRollup.t.sol +++ b/l1-contracts/test/governance/gse/gse/addRollup.t.sol @@ -37,11 +37,7 @@ contract AddRollupTest is WithGSE { _; } - function test_GivenRollupAlreadyRegistered(address _rollup) - external - whenCallerEqOwner - givenRollupNeq0(_rollup) - { + function test_GivenRollupAlreadyRegistered(address _rollup) external whenCallerEqOwner givenRollupNeq0(_rollup) { // it reverts // We add it once @@ -54,12 +50,12 @@ contract AddRollupTest is WithGSE { gse.addRollup(_rollup); } - function test_GivenRollupNotRegistered( - address _rollup, - address _rollup2, - uint256 _ts1, - uint256 _ts2 - ) external whenCallerEqOwner givenRollupNeq0(_rollup) givenRollupNeq0(_rollup2) { + function test_GivenRollupNotRegistered(address _rollup, address _rollup2, uint256 _ts1, uint256 _ts2) + external + whenCallerEqOwner + givenRollupNeq0(_rollup) + givenRollupNeq0(_rollup2) + { // it adds rollup to instances // it sets rollup exists to true // it pushes rollup to latest with timestamp diff --git a/l1-contracts/test/governance/gse/gse/base.sol b/l1-contracts/test/governance/gse/gse/base.sol index 05dd1277e181..42101fb15b97 100644 --- a/l1-contracts/test/governance/gse/gse/base.sol +++ b/l1-contracts/test/governance/gse/gse/base.sol @@ -21,9 +21,7 @@ contract WithGSE is TestBase { governance = Governance(address(gse.getGovernance())); } - function cheat_deposit(address _instance, address _attester, address _withdrawer, bool _onBonus) - public - { + function cheat_deposit(address _instance, address _attester, address _withdrawer, bool _onBonus) public { uint256 activationThreshold = gse.ACTIVATION_THRESHOLD(); vm.prank(stakingAsset.owner()); diff --git a/l1-contracts/test/governance/gse/gse/delegate.t.sol b/l1-contracts/test/governance/gse/gse/delegate.t.sol index 11aab18af900..96e6ca218757 100644 --- a/l1-contracts/test/governance/gse/gse/delegate.t.sol +++ b/l1-contracts/test/governance/gse/gse/delegate.t.sol @@ -6,11 +6,7 @@ import {Errors} from "@aztec/governance/libraries/Errors.sol"; import {TestERC20} from "@aztec/mock/TestERC20.sol"; contract DelegateTest is WithGSE { - function test_GivenInstanceIsNotRegistered( - address _instance, - address _attester, - address _delegatee - ) external { + function test_GivenInstanceIsNotRegistered(address _instance, address _attester, address _delegatee) external { // it reverts vm.assume(gse.isRollupRegistered(_instance) == false); @@ -50,34 +46,26 @@ contract DelegateTest is WithGSE { // Checks on the specific instance { vm.prank(_attester); - vm.expectRevert( - abi.encodeWithSelector(Errors.GSE__NotWithdrawer.selector, _withdrawer, _attester) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GSE__NotWithdrawer.selector, _withdrawer, _attester)); gse.delegate(_instance, _attester, _delegatee); address bonus = gse.getBonusInstanceAddress(); vm.prank(_attester); - vm.expectRevert( - abi.encodeWithSelector(Errors.GSE__NotWithdrawer.selector, address(0), _attester) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GSE__NotWithdrawer.selector, address(0), _attester)); gse.delegate(bonus, _attester, _delegatee); } // Checks on the bonus address { vm.prank(_attester2); - vm.expectRevert( - abi.encodeWithSelector(Errors.GSE__NotWithdrawer.selector, address(0), _attester2) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GSE__NotWithdrawer.selector, address(0), _attester2)); gse.delegate(_instance, _attester2, _delegatee); address bonus = gse.getBonusInstanceAddress(); vm.prank(_attester2); - vm.expectRevert( - abi.encodeWithSelector(Errors.GSE__NotWithdrawer.selector, _withdrawer, _attester2) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GSE__NotWithdrawer.selector, _withdrawer, _attester2)); gse.delegate(bonus, _attester2, _delegatee); } } diff --git a/l1-contracts/test/governance/gse/gse/deposit.t.sol b/l1-contracts/test/governance/gse/gse/deposit.t.sol index 259c30284ac0..1d1de1336860 100644 --- a/l1-contracts/test/governance/gse/gse/deposit.t.sol +++ b/l1-contracts/test/governance/gse/gse/deposit.t.sol @@ -69,17 +69,16 @@ contract DepositTest is WithGSE { vm.stopPrank(); vm.prank(_instance); - vm.expectRevert( - abi.encodeWithSelector(Errors.GSE__AlreadyRegistered.selector, _instance, _attester) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GSE__AlreadyRegistered.selector, _instance, _attester)); gse.deposit(_attester, _withdrawer, onBonus); } - function test_GivenAttesterAlreadyRegisteredOnBonus( - address _instance, - address _attester, - address _withdrawer - ) external whenCallerIsRegisteredRollup(_instance) givenOnBonusEqTrue givenCallerIsLatest { + function test_GivenAttesterAlreadyRegisteredOnBonus(address _instance, address _attester, address _withdrawer) + external + whenCallerIsRegisteredRollup(_instance) + givenOnBonusEqTrue + givenCallerIsLatest + { // it reverts uint256 activationThreshold = gse.ACTIVATION_THRESHOLD(); @@ -95,17 +94,16 @@ contract DepositTest is WithGSE { address bonus = gse.BONUS_INSTANCE_ADDRESS(); vm.prank(_instance); - vm.expectRevert( - abi.encodeWithSelector(Errors.GSE__AlreadyRegistered.selector, bonus, _attester) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GSE__AlreadyRegistered.selector, bonus, _attester)); gse.deposit(_attester, _withdrawer, onBonus); } - function test_GivenAttesterNotRegisteredAnywhere( - address _instance, - address _attester, - address _withdrawer - ) external whenCallerIsRegisteredRollup(_instance) givenOnBonusEqTrue givenCallerIsLatest { + function test_GivenAttesterNotRegisteredAnywhere(address _instance, address _attester, address _withdrawer) + external + whenCallerIsRegisteredRollup(_instance) + givenOnBonusEqTrue + givenCallerIsLatest + { // it adds attester to bonus instance // it sets attester config with withdrawer // it delegates attester to bonus if not delegated @@ -177,9 +175,7 @@ contract DepositTest is WithGSE { vm.stopPrank(); vm.prank(_instance); - vm.expectRevert( - abi.encodeWithSelector(Errors.GSE__AlreadyRegistered.selector, _instance, _attester) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GSE__AlreadyRegistered.selector, _instance, _attester)); gse.deposit(_attester, _withdrawer, onBonus); } @@ -205,9 +201,7 @@ contract DepositTest is WithGSE { address bonus = gse.BONUS_INSTANCE_ADDRESS(); vm.prank(_instance); - vm.expectRevert( - abi.encodeWithSelector(Errors.GSE__AlreadyRegistered.selector, bonus, _attester) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GSE__AlreadyRegistered.selector, bonus, _attester)); gse.deposit(_attester, _withdrawer, onBonus); } @@ -219,12 +213,7 @@ contract DepositTest is WithGSE { address _instance, address _attester, address _withdrawer - ) - external - whenCallerIsRegisteredRollup(_instance) - givenOnBonusEqFalse - givenAttesterNotRegisteredOnSpecificInstance - { + ) external whenCallerIsRegisteredRollup(_instance) givenOnBonusEqFalse givenAttesterNotRegisteredOnSpecificInstance { // it adds attester to specific instance // it sets attester config with withdrawer // it delegates attester to instance if not delegated @@ -269,12 +258,7 @@ contract DepositTest is WithGSE { assertEq(gse.totalSupply(), activationThreshold); } - function test_GivenCallerIsNotLatest2( - address _instance, - address _instance2, - address _attester, - address _withdrawer - ) + function test_GivenCallerIsNotLatest2(address _instance, address _instance2, address _attester, address _withdrawer) external whenCallerIsRegisteredRollup(_instance) whenCallerIsRegisteredRollup(_instance2) diff --git a/l1-contracts/test/governance/gse/gse/proposeWithLock.t.sol b/l1-contracts/test/governance/gse/gse/proposeWithLock.t.sol index f52a6d54bb11..d5a675107c1a 100644 --- a/l1-contracts/test/governance/gse/gse/proposeWithLock.t.sol +++ b/l1-contracts/test/governance/gse/gse/proposeWithLock.t.sol @@ -6,11 +6,7 @@ import {Errors} from "@aztec/governance/libraries/Errors.sol"; import {IGSECore} from "@aztec/governance/GSE.sol"; import {IPayload} from "@aztec/governance/interfaces/IPayload.sol"; import { - Configuration, - Proposal, - ProposalState, - IGovernance, - Withdrawal + Configuration, Proposal, ProposalState, IGovernance, Withdrawal } from "@aztec/governance/interfaces/IGovernance.sol"; import {Timestamp} from "@aztec/shared/libraries/TimeMath.sol"; import {IERC20Errors} from "@oz/interfaces/draft-IERC6093.sol"; @@ -21,10 +17,7 @@ contract ProposeWithLockTest is WithGSE { Configuration memory config = governance.getConfiguration(); vm.expectRevert( abi.encodeWithSelector( - IERC20Errors.ERC20InsufficientAllowance.selector, - address(gse), - 0, - config.proposeConfig.lockAmount + IERC20Errors.ERC20InsufficientAllowance.selector, address(gse), 0, config.proposeConfig.lockAmount ) ); gse.proposeWithLock(IPayload(address(0)), address(this)); diff --git a/l1-contracts/test/governance/gse/gse/setGovernance.t.sol b/l1-contracts/test/governance/gse/gse/setGovernance.t.sol index c9fc01699e11..201ab1666404 100644 --- a/l1-contracts/test/governance/gse/gse/setGovernance.t.sol +++ b/l1-contracts/test/governance/gse/gse/setGovernance.t.sol @@ -13,12 +13,8 @@ contract SetGovernanceTest is WithGSE { address internal caller; function setUp() public override(WithGSE) { - gse = new GSE( - address(this), - IERC20(address(0)), - TestConstants.ACTIVATION_THRESHOLD, - TestConstants.EJECTION_THRESHOLD - ); + gse = + new GSE(address(this), IERC20(address(0)), TestConstants.ACTIVATION_THRESHOLD, TestConstants.EJECTION_THRESHOLD); } function test_WhenCallerNeqOwner(address _caller) external { diff --git a/l1-contracts/test/governance/gse/gse/static.t.sol b/l1-contracts/test/governance/gse/gse/static.t.sol index 6dd6722fd5fa..a607bf46b560 100644 --- a/l1-contracts/test/governance/gse/gse/static.t.sol +++ b/l1-contracts/test/governance/gse/gse/static.t.sol @@ -8,9 +8,7 @@ import {Timestamp} from "@aztec/shared/libraries/TimeMath.sol"; import {Errors} from "@aztec/governance/libraries/Errors.sol"; contract StaticTest is WithGSE { - function test_getWithdrawer(address[2] memory _instances, address _attester, address _withdrawer) - external - { + function test_getWithdrawer(address[2] memory _instances, address _attester, address _withdrawer) external { vm.assume(_instances[0] != _instances[1]); vm.assume(_instances[0] != address(0) && _instances[0] != gse.getBonusInstanceAddress()); vm.assume(_instances[1] != address(0) && _instances[1] != gse.getBonusInstanceAddress()); @@ -25,8 +23,7 @@ contract StaticTest is WithGSE { { cheat_deposit(_instances[0], _attester, _withdrawer, false); - (address actualWithdrawer, bool exists, address instance) = - gse.getWithdrawer(_instances[0], _attester); + (address actualWithdrawer, bool exists, address instance) = gse.getWithdrawer(_instances[0], _attester); assertEq(actualWithdrawer, _withdrawer, "invalid withdrawer"); assertTrue(exists, "withdrawer should exist"); @@ -37,8 +34,7 @@ contract StaticTest is WithGSE { { cheat_deposit(_instances[1], _attester, _withdrawer, true); - (address actualWithdrawer, bool exists, address instance) = - gse.getWithdrawer(_instances[1], _attester); + (address actualWithdrawer, bool exists, address instance) = gse.getWithdrawer(_instances[1], _attester); assertEq(actualWithdrawer, _withdrawer, "invalid withdrawer"); assertTrue(exists, "withdrawer should exist"); @@ -47,8 +43,7 @@ contract StaticTest is WithGSE { // Withdrawer is not an attester, so should not be able to get a withdrawer { - (address actualWithdrawer, bool exists, address instance) = - gse.getWithdrawer(_instances[1], _withdrawer); + (address actualWithdrawer, bool exists, address instance) = gse.getWithdrawer(_instances[1], _withdrawer); assertEq(actualWithdrawer, address(0), "invalid withdrawer"); assertFalse(exists, "withdrawer should not exist"); @@ -69,9 +64,7 @@ contract StaticTest is WithGSE { assertEq(gse.getVotingPower(_instance), gse.ACTIVATION_THRESHOLD(), "invalid voting power"); } - function test_getAttesterFromIndexAtTime(address _instance, address[4] memory _attesters) - external - { + function test_getAttesterFromIndexAtTime(address _instance, address[4] memory _attesters) external { vm.assume(_instance != address(0) && _instance != gse.getBonusInstanceAddress()); for (uint256 i = 0; i < _attesters.length; i++) { for (uint256 j = i + 1; j < _attesters.length; j++) { diff --git a/l1-contracts/test/governance/gse/gse/vote.t.sol b/l1-contracts/test/governance/gse/gse/vote.t.sol index 95323c2c05b6..76add02a3877 100644 --- a/l1-contracts/test/governance/gse/gse/vote.t.sol +++ b/l1-contracts/test/governance/gse/gse/vote.t.sol @@ -31,9 +31,7 @@ contract VoteTest is WithGSE { vm.prank(voter); vm.expectRevert( - abi.encodeWithSelector( - Errors.Delegation__InsufficientPower.selector, voter, availablePower, amount - ) + abi.encodeWithSelector(Errors.Delegation__InsufficientPower.selector, voter, availablePower, amount) ); gse.vote(0, amount, true); } diff --git a/l1-contracts/test/governance/gse/gse/voteWithBonus.t.sol b/l1-contracts/test/governance/gse/gse/voteWithBonus.t.sol index 5fa4fc084371..e13d38cb8636 100644 --- a/l1-contracts/test/governance/gse/gse/voteWithBonus.t.sol +++ b/l1-contracts/test/governance/gse/gse/voteWithBonus.t.sol @@ -40,11 +40,10 @@ contract VoteWithBonusTest is WithGSE { _; } - function test_GivenAmountGreaterThanAvailableBonusPower( - address _instance, - address _attester, - uint256 _amount - ) external givenCallerIsLatestAtProposalTime(_instance) { + function test_GivenAmountGreaterThanAvailableBonusPower(address _instance, address _attester, uint256 _amount) + external + givenCallerIsLatestAtProposalTime(_instance) + { // it reverts uint256 availablePower = _prepare(_instance, _attester); @@ -52,9 +51,7 @@ contract VoteWithBonusTest is WithGSE { vm.prank(_instance); vm.expectRevert( - abi.encodeWithSelector( - Errors.Delegation__InsufficientPower.selector, BONUS_ADDRESS, availablePower, amount - ) + abi.encodeWithSelector(Errors.Delegation__InsufficientPower.selector, BONUS_ADDRESS, availablePower, amount) ); gse.voteWithBonus(0, amount, true); } diff --git a/l1-contracts/test/governance/gse/gse/withdraw.t.sol b/l1-contracts/test/governance/gse/gse/withdraw.t.sol index fd60c55501d3..a0adaf010ab6 100644 --- a/l1-contracts/test/governance/gse/gse/withdraw.t.sol +++ b/l1-contracts/test/governance/gse/gse/withdraw.t.sol @@ -111,9 +111,7 @@ contract WithdrawTest is WithGSE { amount = bound(_amount, balance + 1, type(uint256).max); vm.prank(_instance); - vm.expectRevert( - abi.encodeWithSelector(Errors.GSE__InsufficientBalance.selector, balance, amount) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GSE__InsufficientBalance.selector, balance, amount)); gse.withdraw(_attester, amount); } @@ -123,11 +121,7 @@ contract WithdrawTest is WithGSE { _; } - function test_GivenBalanceMinusAmountLessThanejectionThreshold( - address _instance, - address _attester, - uint256 _amount - ) + function test_GivenBalanceMinusAmountLessThanejectionThreshold(address _instance, address _attester, uint256 _amount) external whenCallerIsRegisteredRollup(_instance) givenAttesterNotFoundInCallerInstance(_instance, _attester) @@ -154,8 +148,7 @@ contract WithdrawTest is WithGSE { // He will be removed entirely { vm.prank(_instance); - (uint256 amountWithdrawn, bool isRemoved, uint256 withdrawalId) = - gse.withdraw(_attester, amount); + (uint256 amountWithdrawn, bool isRemoved, uint256 withdrawalId) = gse.withdraw(_attester, amount); assertEq(amountWithdrawn, balance); assertEq(isRemoved, true); assertEq(withdrawalId, 0); @@ -203,8 +196,7 @@ contract WithdrawTest is WithGSE { // He will not be removed { vm.prank(_instance); - (uint256 amountWithdrawn, bool isRemoved, uint256 withdrawalId) = - gse.withdraw(_attester, amount); + (uint256 amountWithdrawn, bool isRemoved, uint256 withdrawalId) = gse.withdraw(_attester, amount); assertEq(amountWithdrawn, amount); assertEq(isRemoved, false); assertEq(withdrawalId, 0); @@ -244,28 +236,18 @@ contract WithdrawTest is WithGSE { amount = bound(_amount, balance + 1, type(uint256).max); vm.prank(_instance); - vm.expectRevert( - abi.encodeWithSelector(Errors.GSE__InsufficientBalance.selector, balance, amount) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.GSE__InsufficientBalance.selector, balance, amount)); gse.withdraw(_attester, amount); } - modifier givenBalanceGreaterOrEqualToAmount2( - address _instance, - address _attester, - uint256 _amount - ) { + modifier givenBalanceGreaterOrEqualToAmount2(address _instance, address _attester, uint256 _amount) { uint256 balance = gse.balanceOf(_instance, _attester); amount = bound(_amount, 0, balance); _; } - function test_GivenBalanceMinusAmountLessThanejectionThreshold2( - address _instance, - address _attester, - uint256 _amount - ) + function test_GivenBalanceMinusAmountLessThanejectionThreshold2(address _instance, address _attester, uint256 _amount) external whenCallerIsRegisteredRollup(_instance) givenAttesterFoundInCallerInstance(_instance, _attester) @@ -291,8 +273,7 @@ contract WithdrawTest is WithGSE { // He will be removed entirely { vm.prank(_instance); - (uint256 amountWithdrawn, bool isRemoved, uint256 withdrawalId) = - gse.withdraw(_attester, amount); + (uint256 amountWithdrawn, bool isRemoved, uint256 withdrawalId) = gse.withdraw(_attester, amount); assertEq(amountWithdrawn, balance); assertEq(isRemoved, true); assertEq(withdrawalId, 0); @@ -338,8 +319,7 @@ contract WithdrawTest is WithGSE { // He will not be removed { vm.prank(_instance); - (uint256 amountWithdrawn, bool isRemoved, uint256 withdrawalId) = - gse.withdraw(_attester, amount); + (uint256 amountWithdrawn, bool isRemoved, uint256 withdrawalId) = gse.withdraw(_attester, amount); assertEq(amountWithdrawn, amount); assertEq(isRemoved, false); assertEq(withdrawalId, 0); diff --git a/l1-contracts/test/governance/gse/stakedelegationlib/StakeDelegationLibWrapper.sol b/l1-contracts/test/governance/gse/stakedelegationlib/StakeDelegationLibWrapper.sol index a1181a18c486..87001e4119c4 100644 --- a/l1-contracts/test/governance/gse/stakedelegationlib/StakeDelegationLibWrapper.sol +++ b/l1-contracts/test/governance/gse/stakedelegationlib/StakeDelegationLibWrapper.sol @@ -3,8 +3,7 @@ pragma solidity >=0.8.27; import { - DepositDelegationLib, - DepositAndDelegationAccounting + DepositDelegationLib, DepositAndDelegationAccounting } from "@aztec/governance/libraries/DepositDelegationLib.sol"; import {Timestamp} from "@aztec/shared/libraries/TimeMath.sol"; @@ -25,9 +24,7 @@ contract StakeDelegationLibWrapper { self.delegate(_instance, _attester, _newDelegatee); } - function usePower(address _delegatee, uint256 _proposalId, Timestamp _timestamp, uint256 _amount) - external - { + function usePower(address _delegatee, uint256 _proposalId, Timestamp _timestamp, uint256 _amount) external { self.usePower(_delegatee, _proposalId, _timestamp, _amount); } @@ -55,11 +52,7 @@ contract StakeDelegationLibWrapper { return self.getVotingPower(_delegatee); } - function getVotingPowerAt(address _delegatee, Timestamp _timestamp) - external - view - returns (uint256) - { + function getVotingPowerAt(address _delegatee, Timestamp _timestamp) external view returns (uint256) { return self.getVotingPowerAt(_delegatee, _timestamp); } } diff --git a/l1-contracts/test/governance/gse/stakedelegationlib/decreaseBalance.t.sol b/l1-contracts/test/governance/gse/stakedelegationlib/decreaseBalance.t.sol index a791542addf1..2ef823fb421f 100644 --- a/l1-contracts/test/governance/gse/stakedelegationlib/decreaseBalance.t.sol +++ b/l1-contracts/test/governance/gse/stakedelegationlib/decreaseBalance.t.sol @@ -17,12 +17,10 @@ contract DecreaseBalanceTest is WithDelegationLib { _; } - function test_GivenNoDelegatee( - address[2] memory _instances, - address _attester, - uint256 _amount, - uint256 _balance - ) external whenAmountGt0 { + function test_GivenNoDelegatee(address[2] memory _instances, address _attester, uint256 _amount, uint256 _balance) + external + whenAmountGt0 + { // it decrease balance by amount // it decrease instance supply by amount // it decrease supply by amount diff --git a/l1-contracts/test/governance/gse/stakedelegationlib/delegate.t.sol b/l1-contracts/test/governance/gse/stakedelegationlib/delegate.t.sol index 078f8f604dd9..6ee30f9dbab6 100644 --- a/l1-contracts/test/governance/gse/stakedelegationlib/delegate.t.sol +++ b/l1-contracts/test/governance/gse/stakedelegationlib/delegate.t.sol @@ -8,11 +8,7 @@ import {StakeDelegationLibWrapper} from "./StakeDelegationLibWrapper.sol"; import {WithDelegationLib} from "./base.sol"; contract DelegateTest is WithDelegationLib { - function test_WhenNewDelegateeEqOldDelegatee( - address _instance, - address _attester, - address _newDelegatee - ) external { + function test_WhenNewDelegateeEqOldDelegatee(address _instance, address _attester, address _newDelegatee) external { // it changes no state vm.assume(_newDelegatee != address(0)); @@ -36,12 +32,10 @@ contract DelegateTest is WithDelegationLib { _; } - function test_GivenOldDelegateeEq0( - address _instance, - address _attester, - address _newDelegatee, - uint256 _balance - ) external whenNewDelegateeNeqOldDelegatee { + function test_GivenOldDelegateeEq0(address _instance, address _attester, address _newDelegatee, uint256 _balance) + external + whenNewDelegateeNeqOldDelegatee + { // it updates the delegatee // it increases power of the new delegatee @@ -68,12 +62,10 @@ contract DelegateTest is WithDelegationLib { assertEq(delegationLib.getBalanceOf(_instance, _attester), balance); } - function test_WhenNewDelegateeEq0( - address _instance, - address _attester, - address _tempDelegatee, - uint256 _balance - ) external whenNewDelegateeNeqOldDelegatee { + function test_WhenNewDelegateeEq0(address _instance, address _attester, address _tempDelegatee, uint256 _balance) + external + whenNewDelegateeNeqOldDelegatee + { // it updates the delegatee // it decreases power of the old delegatee vm.assume(_tempDelegatee != address(0)); diff --git a/l1-contracts/test/governance/gse/stakedelegationlib/increaseBalance.t.sol b/l1-contracts/test/governance/gse/stakedelegationlib/increaseBalance.t.sol index bc70944d3a60..1cd37034550d 100644 --- a/l1-contracts/test/governance/gse/stakedelegationlib/increaseBalance.t.sol +++ b/l1-contracts/test/governance/gse/stakedelegationlib/increaseBalance.t.sol @@ -17,12 +17,10 @@ contract IncreaseBalanceTest is WithDelegationLib { _; } - function test_GivenNoDelegatee( - address[2] memory _instances, - address _attester, - uint256 _amount, - uint256 _balance - ) external whenAmountGt0 { + function test_GivenNoDelegatee(address[2] memory _instances, address _attester, uint256 _amount, uint256 _balance) + external + whenAmountGt0 + { // it increase balance by amount // it increase instance supply by amount // it increase supply by amount diff --git a/l1-contracts/test/governance/gse/stakedelegationlib/usePower.t.sol b/l1-contracts/test/governance/gse/stakedelegationlib/usePower.t.sol index 75a78f7ed5fe..a62d4dba096f 100644 --- a/l1-contracts/test/governance/gse/stakedelegationlib/usePower.t.sol +++ b/l1-contracts/test/governance/gse/stakedelegationlib/usePower.t.sol @@ -41,9 +41,7 @@ contract UsePowerTest is Test { // At this point, we expect a failure when we are trying to vote with move than we have available vm.expectRevert( - abi.encodeWithSelector( - Errors.Delegation__InsufficientPower.selector, _delegatee, powerAt, preAmount + amount - ) + abi.encodeWithSelector(Errors.Delegation__InsufficientPower.selector, _delegatee, powerAt, preAmount + amount) ); delegationLib.usePower(_delegatee, _proposalId, Timestamp.wrap(timestamp - 1), amount); } diff --git a/l1-contracts/test/governance/registry/addRollup.t.sol b/l1-contracts/test/governance/registry/addRollup.t.sol index 35b16a0c1fdf..418152ff6c89 100644 --- a/l1-contracts/test/governance/registry/addRollup.t.sol +++ b/l1-contracts/test/governance/registry/addRollup.t.sol @@ -33,9 +33,7 @@ contract UpgradeTest is RegistryBase { registry.addRollup(IRollup(address(new FakeRollup()))); address rollup = address(registry.getCanonicalRollup()); - vm.expectRevert( - abi.encodeWithSelector(Errors.Registry__RollupAlreadyRegistered.selector, rollup) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Registry__RollupAlreadyRegistered.selector, rollup)); registry.addRollup(IRollup(rollup)); } diff --git a/l1-contracts/test/governance/reward-distributor/claim.t.sol b/l1-contracts/test/governance/reward-distributor/claim.t.sol index f105116d4c1c..0f51b4e2377f 100644 --- a/l1-contracts/test/governance/reward-distributor/claim.t.sol +++ b/l1-contracts/test/governance/reward-distributor/claim.t.sol @@ -13,9 +13,7 @@ contract ClaimTest is RewardDistributorBase { address canonical = address(registry.getCanonicalRollup()); vm.assume(_caller != canonical); - vm.expectRevert( - abi.encodeWithSelector(Errors.RewardDistributor__InvalidCaller.selector, _caller, canonical) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.RewardDistributor__InvalidCaller.selector, _caller, canonical)); vm.prank(_caller); rewardDistributor.claim(_caller, 1e18); } diff --git a/l1-contracts/test/governance/scenario/AddRollup.t.sol b/l1-contracts/test/governance/scenario/AddRollup.t.sol index e5841075f47e..677fecac9c68 100644 --- a/l1-contracts/test/governance/scenario/AddRollup.t.sol +++ b/l1-contracts/test/governance/scenario/AddRollup.t.sol @@ -71,7 +71,7 @@ contract AddRollupTest is TestBase { stakingQueueConfig.normalFlushSizeMin = VALIDATOR_COUNT * 2; // We need to make a timejump that is far enough that we can go at least 2 epochs in the past - vm.warp(100000); + vm.warp(100_000); RollupBuilder builder = new RollupBuilder(address(this)).setGovProposerN(7).setGovProposerM(10) .setStakingQueueConfig(stakingQueueConfig).setTargetCommitteeSize(0); builder.deploy(); @@ -103,9 +103,7 @@ contract AddRollupTest is TestBase { function test_AddRollup(bool _break) external { BadRollup newRollup = new BadRollup(gse); - payload = IPayload( - address(new RegisterNewRollupVersionPayload(registry, IInstance(address(newRollup)))) - ); + payload = IPayload(address(new RegisterNewRollupVersionPayload(registry, IInstance(address(newRollup))))); vm.warp(Timestamp.unwrap(rollup.getTimestampForSlot(Slot.wrap(1)))); for (uint256 i = 0; i < 10; i++) { @@ -125,18 +123,18 @@ contract AddRollupTest is TestBase { assertEq(gsePayload.getURI(), payload.getURI()); vm.prank(token.owner()); - token.mint(EMPEROR, 10000 ether); + token.mint(EMPEROR, 10_000 ether); vm.startPrank(EMPEROR); - token.approve(address(governance), 10000 ether); - governance.deposit(EMPEROR, 10000 ether); + token.approve(address(governance), 10_000 ether); + governance.deposit(EMPEROR, 10_000 ether); vm.stopPrank(); vm.warp(Timestamp.unwrap(proposal.pendingThrough()) + 1); assertTrue(governance.getProposalState(0) == ProposalState.Active); vm.prank(EMPEROR); - governance.vote(0, 10000 ether, true); + governance.vote(0, 10_000 ether, true); vm.warp(Timestamp.unwrap(proposal.activeThrough()) + 1); assertTrue(governance.getProposalState(0) == ProposalState.Queued); @@ -167,9 +165,7 @@ contract AddRollupTest is TestBase { // While Errors.GovernanceProposer__GSEPayloadInvalid.selector is the error, we are catching it // So the expected error is that the call failed and the address of it. - vm.expectRevert( - abi.encodeWithSelector(Errors.Governance__CallFailed.selector, address(gsePayload)) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Governance__CallFailed.selector, address(gsePayload))); } governance.execute(0); diff --git a/l1-contracts/test/governance/scenario/NewGovernanceProposerPayload.sol b/l1-contracts/test/governance/scenario/NewGovernanceProposerPayload.sol index ae6d37714a41..a1e6413bd575 100644 --- a/l1-contracts/test/governance/scenario/NewGovernanceProposerPayload.sol +++ b/l1-contracts/test/governance/scenario/NewGovernanceProposerPayload.sol @@ -32,9 +32,7 @@ contract NewGovernanceProposerPayload is IPayload { res[0] = Action({ target: address(governance), - data: abi.encodeWithSelector( - governance.updateGovernanceProposer.selector, NEW_GOVERNANCE_PROPOSER - ) + data: abi.encodeWithSelector(governance.updateGovernanceProposer.selector, NEW_GOVERNANCE_PROPOSER) }); return res; diff --git a/l1-contracts/test/governance/scenario/RegisterNewRollupVersionPayload.sol b/l1-contracts/test/governance/scenario/RegisterNewRollupVersionPayload.sol index 431334dc0ef5..44ff161cc909 100644 --- a/l1-contracts/test/governance/scenario/RegisterNewRollupVersionPayload.sol +++ b/l1-contracts/test/governance/scenario/RegisterNewRollupVersionPayload.sol @@ -27,10 +27,8 @@ contract RegisterNewRollupVersionPayload is IPayload { function getActions() external view override(IPayload) returns (IPayload.Action[] memory) { IPayload.Action[] memory res = new IPayload.Action[](2); - res[0] = Action({ - target: address(REGISTRY), - data: abi.encodeWithSelector(IRegistry.addRollup.selector, address(ROLLUP)) - }); + res[0] = + Action({target: address(REGISTRY), data: abi.encodeWithSelector(IRegistry.addRollup.selector, address(ROLLUP))}); res[1] = Action({ target: address(ROLLUP.getGSE()), diff --git a/l1-contracts/test/governance/scenario/UpgradeGovernanceProposerTest.t.sol b/l1-contracts/test/governance/scenario/UpgradeGovernanceProposerTest.t.sol index 52e9438a7c4d..183342608aaa 100644 --- a/l1-contracts/test/governance/scenario/UpgradeGovernanceProposerTest.t.sol +++ b/l1-contracts/test/governance/scenario/UpgradeGovernanceProposerTest.t.sol @@ -62,8 +62,9 @@ contract UpgradeGovernanceProposerTest is TestBase { initialValidators[i - 1] = CheatDepositArgs({attester: validator, withdrawer: validator}); } - RollupBuilder builder = new RollupBuilder(address(this)).setGovProposerN(7).setGovProposerM(10) - .setValidators(initialValidators).setTargetCommitteeSize(4).setEpochDuration(1); + RollupBuilder builder = new RollupBuilder(address(this)).setGovProposerN(7).setGovProposerM(10).setValidators( + initialValidators + ).setTargetCommitteeSize(4).setEpochDuration(1); builder.deploy(); rollup = builder.getConfig().rollup; @@ -105,18 +106,18 @@ contract UpgradeGovernanceProposerTest is TestBase { assertEq(gsePayload.getURI(), payload.getURI()); vm.prank(token.owner()); - token.mint(EMPEROR, 10000 ether); + token.mint(EMPEROR, 10_000 ether); vm.startPrank(EMPEROR); - token.approve(address(governance), 10000 ether); - governance.deposit(EMPEROR, 10000 ether); + token.approve(address(governance), 10_000 ether); + governance.deposit(EMPEROR, 10_000 ether); vm.stopPrank(); vm.warp(Timestamp.unwrap(proposal.pendingThrough()) + 1); assertTrue(governance.getProposalState(0) == ProposalState.Active); vm.prank(EMPEROR); - governance.vote(0, 10000 ether, true); + governance.vote(0, 10_000 ether, true); vm.warp(Timestamp.unwrap(proposal.activeThrough()) + 1); assertTrue(governance.getProposalState(0) == ProposalState.Queued); @@ -128,16 +129,13 @@ contract UpgradeGovernanceProposerTest is TestBase { governance.execute(0); assertNotEq(governance.governanceProposer(), address(governanceProposer)); - address newGovernanceProposer = - address(NewGovernanceProposerPayload(address(payload)).NEW_GOVERNANCE_PROPOSER()); + address newGovernanceProposer = address(NewGovernanceProposerPayload(address(payload)).NEW_GOVERNANCE_PROPOSER()); assertEq(governance.governanceProposer(), newGovernanceProposer); // Ensure that we cannot push a proposal after the upgrade. vm.expectRevert( abi.encodeWithSelector( - Errors.Governance__CallerNotGovernanceProposer.selector, - address(governanceProposer), - newGovernanceProposer + Errors.Governance__CallerNotGovernanceProposer.selector, address(governanceProposer), newGovernanceProposer ) ); vm.prank(address(governanceProposer)); diff --git a/l1-contracts/test/governance/scenario/slashing/Slashing.t.sol b/l1-contracts/test/governance/scenario/slashing/Slashing.t.sol index 93e27d8242f5..74e1dcbee012 100644 --- a/l1-contracts/test/governance/scenario/slashing/Slashing.t.sol +++ b/l1-contracts/test/governance/scenario/slashing/Slashing.t.sol @@ -73,15 +73,13 @@ contract SlashingTest is TestBase { function _setupCommitteeForSlashing() internal { _setupCommitteeForSlashing( - TestConstants.AZTEC_SLASHING_LIFETIME_IN_ROUNDS, - TestConstants.AZTEC_SLASHING_EXECUTION_DELAY_IN_ROUNDS + TestConstants.AZTEC_SLASHING_LIFETIME_IN_ROUNDS, TestConstants.AZTEC_SLASHING_EXECUTION_DELAY_IN_ROUNDS ); } - function _setupCommitteeForSlashing( - uint256 _slashingLifetimeInRounds, - uint256 _slashingExecutionDelayInRounds - ) internal { + function _setupCommitteeForSlashing(uint256 _slashingLifetimeInRounds, uint256 _slashingExecutionDelayInRounds) + internal + { uint256 validatorCount = 4; CheatDepositArgs[] memory initialValidators = new CheatDepositArgs[](validatorCount); @@ -93,9 +91,10 @@ contract SlashingTest is TestBase { initialValidators[i - 1] = CheatDepositArgs({attester: attester, withdrawer: address(this)}); } - RollupBuilder builder = new RollupBuilder(address(this)).setValidators(initialValidators) - .setTargetCommitteeSize(4).setSlashingLifetimeInRounds(_slashingLifetimeInRounds) - .setSlashingExecutionDelayInRounds(_slashingExecutionDelayInRounds); + RollupBuilder builder = new RollupBuilder(address(this)).setValidators(initialValidators).setTargetCommitteeSize(4) + .setSlashingLifetimeInRounds(_slashingLifetimeInRounds).setSlashingExecutionDelayInRounds( + _slashingExecutionDelayInRounds + ); builder.deploy(); rollup = builder.getConfig().rollup; @@ -120,11 +119,9 @@ contract SlashingTest is TestBase { assertEq(rollup.getActiveAttesterCount(), validatorCount, "Invalid attester count"); } - function test_CannotSlashBeforeDelay( - uint256 _lifetimeInRounds, - uint256 _executionDelayInRounds, - uint256 _jumpToSlot - ) public { + function test_CannotSlashBeforeDelay(uint256 _lifetimeInRounds, uint256 _executionDelayInRounds, uint256 _jumpToSlot) + public + { _executionDelayInRounds = bound(_executionDelayInRounds, 1, 1e3); _lifetimeInRounds = bound(_lifetimeInRounds, _executionDelayInRounds + 1, 1e4); @@ -133,27 +130,22 @@ contract SlashingTest is TestBase { uint96 slashAmount = 10e18; (uint256 firstSlashingRound,) = _createPayloadAndSignalForSlashing(attesters, slashAmount); - uint256 firstExecutableSlot = - (firstSlashingRound + _executionDelayInRounds + 1) * slashingProposer.ROUND_SIZE(); + uint256 firstExecutableSlot = (firstSlashingRound + _executionDelayInRounds + 1) * slashingProposer.ROUND_SIZE(); _jumpToSlot = bound(_jumpToSlot, timeCheater.currentSlot(), firstExecutableSlot - 1); timeCheater.cheat__jumpToSlot(_jumpToSlot); vm.expectRevert( abi.encodeWithSelector( - Errors.GovernanceProposer__RoundTooNew.selector, - firstSlashingRound, - slashingProposer.getCurrentRound() + Errors.GovernanceProposer__RoundTooNew.selector, firstSlashingRound, slashingProposer.getCurrentRound() ) ); slashingProposer.submitRoundWinner(firstSlashingRound); } - function test_CanSlashAfterDelay( - uint256 _lifetimeInRounds, - uint256 _executionDelayInRounds, - uint256 _jumpToSlot - ) public { + function test_CanSlashAfterDelay(uint256 _lifetimeInRounds, uint256 _executionDelayInRounds, uint256 _jumpToSlot) + public + { _executionDelayInRounds = bound(_executionDelayInRounds, 1, 1e3); _lifetimeInRounds = bound(_lifetimeInRounds, _executionDelayInRounds + 1, 1e4); @@ -162,10 +154,8 @@ contract SlashingTest is TestBase { uint96 slashAmount = 10e18; (uint256 firstSlashingRound,) = _createPayloadAndSignalForSlashing(attesters, slashAmount); - uint256 firstExecutableSlot = - (firstSlashingRound + _executionDelayInRounds + 1) * slashingProposer.ROUND_SIZE(); - uint256 lastExecutableSlot = - (firstSlashingRound + _lifetimeInRounds) * slashingProposer.ROUND_SIZE(); + uint256 firstExecutableSlot = (firstSlashingRound + _executionDelayInRounds + 1) * slashingProposer.ROUND_SIZE(); + uint256 lastExecutableSlot = (firstSlashingRound + _lifetimeInRounds) * slashingProposer.ROUND_SIZE(); _jumpToSlot = bound(_jumpToSlot, firstExecutableSlot, lastExecutableSlot); timeCheater.cheat__jumpToSlot(_jumpToSlot); @@ -185,34 +175,27 @@ contract SlashingTest is TestBase { } } - function test_CannotSlashIfVetoed( - uint256 _lifetimeInRounds, - uint256 _executionDelayInRounds, - uint256 _jumpToSlot - ) public { + function test_CannotSlashIfVetoed(uint256 _lifetimeInRounds, uint256 _executionDelayInRounds, uint256 _jumpToSlot) + public + { _executionDelayInRounds = bound(_executionDelayInRounds, 1, 1e3); _lifetimeInRounds = bound(_lifetimeInRounds, _executionDelayInRounds + 1, 1e4); _setupCommitteeForSlashing(_lifetimeInRounds, _executionDelayInRounds); address[] memory attesters = rollup.getEpochCommittee(Epoch.wrap(2)); uint96 slashAmount = 10e18; - (uint256 firstSlashingRound, IPayload payload) = - _createPayloadAndSignalForSlashing(attesters, slashAmount); + (uint256 firstSlashingRound, IPayload payload) = _createPayloadAndSignalForSlashing(attesters, slashAmount); vm.prank(address(slasher.VETOER())); slasher.vetoPayload(payload); - uint256 firstExecutableSlot = - (firstSlashingRound + _executionDelayInRounds + 1) * slashingProposer.ROUND_SIZE(); - uint256 lastExecutableSlot = - (firstSlashingRound + _lifetimeInRounds) * slashingProposer.ROUND_SIZE(); + uint256 firstExecutableSlot = (firstSlashingRound + _executionDelayInRounds + 1) * slashingProposer.ROUND_SIZE(); + uint256 lastExecutableSlot = (firstSlashingRound + _lifetimeInRounds) * slashingProposer.ROUND_SIZE(); _jumpToSlot = bound(_jumpToSlot, firstExecutableSlot, lastExecutableSlot); timeCheater.cheat__jumpToSlot(_jumpToSlot); - vm.expectRevert( - abi.encodeWithSelector(Slasher.Slasher__PayloadVetoed.selector, address(payload)) - ); + vm.expectRevert(abi.encodeWithSelector(Slasher.Slasher__PayloadVetoed.selector, address(payload))); slashingProposer.submitRoundWinner(firstSlashingRound); } diff --git a/l1-contracts/test/harnesses/InboxHarness.sol b/l1-contracts/test/harnesses/InboxHarness.sol index 913e063de981..855e655ceeb2 100644 --- a/l1-contracts/test/harnesses/InboxHarness.sol +++ b/l1-contracts/test/harnesses/InboxHarness.sol @@ -41,8 +41,7 @@ contract InboxHarness is Inbox { function getNextMessageIndex() external view returns (uint256) { FrontierLib.Tree storage currentTree = trees[state.inProgress]; - uint256 index = - (state.inProgress - Constants.INITIAL_L2_BLOCK_NUM) * SIZE + currentTree.nextIndex; + uint256 index = (state.inProgress - Constants.INITIAL_L2_BLOCK_NUM) * SIZE + currentTree.nextIndex; return index; } } diff --git a/l1-contracts/test/harnesses/TestConstants.sol b/l1-contracts/test/harnesses/TestConstants.sol index 8c0085aaef0d..a10f6627112a 100644 --- a/l1-contracts/test/harnesses/TestConstants.sol +++ b/l1-contracts/test/harnesses/TestConstants.sol @@ -3,12 +3,7 @@ pragma solidity >=0.8.27; -import { - RollupConfigInput, - GenesisState, - EthValue, - RewardConfig -} from "@aztec/core/interfaces/IRollup.sol"; +import {RollupConfigInput, GenesisState, EthValue, RewardConfig} from "@aztec/core/interfaces/IRollup.sol"; import {Constants} from "@aztec/core/libraries/ConstantsGen.sol"; import {Bps} from "@aztec/core/libraries/rollup/RewardLib.sol"; import {StakingQueueConfig} from "@aztec/core/libraries/compressed-data/StakingQueueConfig.sol"; @@ -28,7 +23,7 @@ library TestConstants { uint256 internal constant AZTEC_SLASHING_LIFETIME_IN_ROUNDS = 5; uint256 internal constant AZTEC_SLASHING_EXECUTION_DELAY_IN_ROUNDS = 0; address internal constant AZTEC_SLASHING_VETOER = address(0); - uint256 internal constant AZTEC_MANA_TARGET = 100000000; + uint256 internal constant AZTEC_MANA_TARGET = 100_000_000; uint256 internal constant AZTEC_ENTRY_QUEUE_FLUSH_SIZE_MIN = 4; uint256 internal constant AZTEC_ENTRY_QUEUE_FLUSH_SIZE_QUOTIENT = 2; uint256 internal constant AZTEC_ENTRY_QUEUE_BOOTSTRAP_VALIDATOR_SET_SIZE = 0; @@ -46,10 +41,7 @@ library TestConstants { function getGovernanceConfiguration() internal pure returns (Configuration memory) { return Configuration({ - proposeConfig: ProposeConfiguration({ - lockDelay: Timestamp.wrap(60 * 60 * 24 * 30), - lockAmount: 1e24 - }), + proposeConfig: ProposeConfiguration({lockDelay: Timestamp.wrap(60 * 60 * 24 * 30), lockAmount: 1e24}), votingDelay: Timestamp.wrap(60), votingDuration: Timestamp.wrap(60 * 60), executionDelay: Timestamp.wrap(60), @@ -69,13 +61,7 @@ library TestConstants { } function getRewardBoostConfig() internal pure returns (RewardBoostConfig memory) { - return RewardBoostConfig({ - increment: 200000, - maxScore: 5000000, - a: 5000, - k: 1000000, - minimum: 100000 - }); + return RewardBoostConfig({increment: 200_000, maxScore: 5_000_000, a: 5000, k: 1_000_000, minimum: 100_000}); } function getRewardConfig() internal pure returns (RewardConfig memory) { diff --git a/l1-contracts/test/ignition.t.sol b/l1-contracts/test/ignition.t.sol index 628932f2a7c4..3db4e7a6f06e 100644 --- a/l1-contracts/test/ignition.t.sol +++ b/l1-contracts/test/ignition.t.sol @@ -53,9 +53,8 @@ contract IgnitionTest is RollupBase { SLOT_DURATION = TestConstants.AZTEC_SLOT_DURATION; EPOCH_DURATION = TestConstants.AZTEC_EPOCH_DURATION; PROOF_SUBMISSION_EPOCHS = TestConstants.AZTEC_PROOF_SUBMISSION_EPOCHS; - timeCheater = new TimeCheater( - address(this), block.timestamp, SLOT_DURATION, EPOCH_DURATION, PROOF_SUBMISSION_EPOCHS - ); + timeCheater = + new TimeCheater(address(this), block.timestamp, SLOT_DURATION, EPOCH_DURATION, PROOF_SUBMISSION_EPOCHS); } /** @@ -65,13 +64,11 @@ contract IgnitionTest is RollupBase { { DecoderBase.Full memory full = load(_name); Slot slotNumber = full.block.header.slotNumber; - uint256 initialTime = - Timestamp.unwrap(full.block.header.timestamp) - Slot.unwrap(slotNumber) * SLOT_DURATION; + uint256 initialTime = Timestamp.unwrap(full.block.header.timestamp) - Slot.unwrap(slotNumber) * SLOT_DURATION; vm.warp(initialTime); } - RollupBuilder builder = - new RollupBuilder(address(this)).setManaTarget(0).setTargetCommitteeSize(0); + RollupBuilder builder = new RollupBuilder(address(this)).setManaTarget(0).setTargetCommitteeSize(0); builder.deploy(); rollup = IInstance(address(builder.getConfig().rollup)); @@ -92,20 +89,14 @@ contract IgnitionTest is RollupBase { _proveBlocks("empty_block_", 1, 1, address(0xbeef)); // The block rewards should have accumulated - assertEq( - rollup.getFeeAsset().balanceOf(address(rollup)), - rollup.getBlockReward(), - "no block rewards collected" - ); + assertEq(rollup.getFeeAsset().balanceOf(address(rollup)), rollup.getBlockReward(), "no block rewards collected"); uint256 blockReward = rollup.getBlockReward(); Bps bps = rollup.getRewardConfig().sequencerBps; uint256 sequencerReward = BpsLib.mul(blockReward, bps); address coinbase = address(bytes20("sequencer")); - assertEq( - rollup.getSequencerRewards(coinbase), sequencerReward, "sequencer reward not collected" - ); + assertEq(rollup.getSequencerRewards(coinbase), sequencerReward, "sequencer reward not collected"); assertEq( rollup.getCollectiveProverRewardsForEpoch(Epoch.wrap(0)), blockReward - sequencerReward, @@ -114,8 +105,6 @@ contract IgnitionTest is RollupBase { } function test_RevertNonEmptyBlock() public setUpFor("empty_block_1") { - _proposeBlockFail( - "empty_block_1", 1, 1, abi.encodeWithSelector(Errors.Rollup__ManaLimitExceeded.selector) - ); + _proposeBlockFail("empty_block_1", 1, 1, abi.encodeWithSelector(Errors.Rollup__ManaLimitExceeded.selector)); } } diff --git a/l1-contracts/test/merkle/MerkleLib.t.sol b/l1-contracts/test/merkle/MerkleLib.t.sol index 53886f5073c3..3dc9a5d003bf 100644 --- a/l1-contracts/test/merkle/MerkleLib.t.sol +++ b/l1-contracts/test/merkle/MerkleLib.t.sol @@ -61,10 +61,7 @@ contract MerkleLibTest is Test { merkleLibHelper.verifyMembership(emptyPath, leaf, leafIndex, expectedRoot); } - function testVerifyMembershipWithRandomSiblingPaths( - uint256 _idx, - bytes32[DEPTH] memory _siblingPath - ) public { + function testVerifyMembershipWithRandomSiblingPaths(uint256 _idx, bytes32[DEPTH] memory _siblingPath) public { uint256 leafIndex = _idx % (2 ** DEPTH); bytes32 expectedRoot = merkle.computeRoot(); diff --git a/l1-contracts/test/merkle/Naive.t.sol b/l1-contracts/test/merkle/Naive.t.sol index 34269d325641..4c90852b8084 100644 --- a/l1-contracts/test/merkle/Naive.t.sol +++ b/l1-contracts/test/merkle/Naive.t.sol @@ -38,7 +38,8 @@ contract NaiveTest is Test { ) ]; - /// We then compute the sibling path using the tree and expect that our manual calculation should equal the computed one + /// We then compute the sibling path using the tree and expect that our manual calculation should equal the computed + /// one (bytes32[] memory path, bytes32 leaf) = tree.computeSiblingPath(0); assertEq(leaf, bytes32(abi.encode(1))); assertEq(path[0], expectedPath[0]); @@ -56,7 +57,8 @@ contract NaiveTest is Test { /** * We manually make a path; this is the sibling path of the leaf with the value of 8. - * This path, from leaf to root, consists of c a, b, and c; which correspond to the value of 7, then the hash of 5 and 6, + * This path, from leaf to root, consists of c a, b, and c; which correspond to the value of 7, then the hash of 5 + * and 6, * and finally, the hash of 1 and 2 concatenated with the hash of 3 and 4; * d0: [ root ] * d1: [c] [ ] @@ -74,7 +76,8 @@ contract NaiveTest is Test { ) ]; - /// We then compute the sibling path using the tree and expect that our manual calculation should equal the computed one + /// We then compute the sibling path using the tree and expect that our manual calculation should equal the computed + /// one (bytes32[] memory path, bytes32 leaf) = tree.computeSiblingPath(7); assertEq(leaf, bytes32(abi.encode(8))); assertEq(path[0], expectedPath[0]); diff --git a/l1-contracts/test/merkle/TestUtil.sol b/l1-contracts/test/merkle/TestUtil.sol index 397162b03e40..8caf4d59b5c4 100644 --- a/l1-contracts/test/merkle/TestUtil.sol +++ b/l1-contracts/test/merkle/TestUtil.sol @@ -22,15 +22,20 @@ contract MerkleTestUtil is Test { /// hence the next highest power of two from the amount of leaves - Math.ceil(Math.log2(x)) uint256 height = 0; - /// While size > 1, we divide by two, and count how many times we do this; producing a rudimentary way of calculating Math.Floor(Math.log2(x)) + /// While size > 1, we divide by two, and count how many times we do this; producing a rudimentary way of + /// calculating Math.Floor(Math.log2(x)) while (_size > 1) { _size >>= 1; height++; } - /// @notice - We check if 2 ** height does not equal our original number. If so, this means that our size is not a power of two, - /// and hence we've rounded down (Math.floor) and have obtained the next lowest power of two instead of rounding up (Math.ceil) to obtain the next highest power of two and therefore we need to increment height before returning it. - /// If 2 ** height equals our original number, it means that we have a perfect power of two and Math.floor(Math.log2(x)) = Math.ceil(Math.log2(x)) and we can return height as-is + /// @notice - We check if 2 ** height does not equal our original number. If so, this means that our size is not a + /// power of two, + /// and hence we've rounded down (Math.floor) and have obtained the next lowest power of two instead of rounding up + /// (Math.ceil) to obtain the next highest power of two and therefore we need to increment height before returning + /// it. + /// If 2 ** height equals our original number, it means that we have a perfect power of two and + /// Math.floor(Math.log2(x)) = Math.ceil(Math.log2(x)) and we can return height as-is return (2 ** height) != originalNumber ? ++height : height; } diff --git a/l1-contracts/test/merkle/UnbalancedMerkle.t.sol b/l1-contracts/test/merkle/UnbalancedMerkle.t.sol index 88f1e63334a4..f4c791ed5e44 100644 --- a/l1-contracts/test/merkle/UnbalancedMerkle.t.sol +++ b/l1-contracts/test/merkle/UnbalancedMerkle.t.sol @@ -25,12 +25,12 @@ contract UnbalancedMerkleTest is Test { function testDecomp() public view { // Worst case - max num txs - uint32 numTxs = 65535; + uint32 numTxs = 65_535; (uint256 min, uint256 max) = merkleLibHelper.computeMinMaxPathLength(numTxs); assertEq(min, 15); assertEq(max, 16); // Single tree of 2**15 - numTxs = 32768; + numTxs = 32_768; (min, max) = merkleLibHelper.computeMinMaxPathLength(numTxs); assertEq(min, 15); assertEq(max, 15); @@ -101,8 +101,7 @@ contract UnbalancedMerkleTest is Test { assertEq(min, 1); assertEq(max, 2); bytes32 mergeTxsEffectsHash = Hash.sha256ToField(bytes.concat(baseLeaves[0], baseLeaves[1])); - bytes32 rootTxsEffectsHash = - Hash.sha256ToField(bytes.concat(mergeTxsEffectsHash, baseLeaves[2])); + bytes32 rootTxsEffectsHash = Hash.sha256ToField(bytes.concat(mergeTxsEffectsHash, baseLeaves[2])); bytes32 calculatedTxsEffectsHash = merkleLibHelper.computeUnbalancedRoot(baseLeaves); assertEq(calculatedTxsEffectsHash, rootTxsEffectsHash); } @@ -125,14 +124,11 @@ contract UnbalancedMerkleTest is Test { (uint256 min, uint256 max) = merkleLibHelper.computeMinMaxPathLength(5); assertEq(min, 1); assertEq(max, 3); - bytes32 firstMergeTxsEffectsHash = - Hash.sha256ToField(bytes.concat(baseLeaves[0], baseLeaves[1])); - bytes32 secondMergeTxsEffectsHash = - Hash.sha256ToField(bytes.concat(baseLeaves[2], baseLeaves[3])); + bytes32 firstMergeTxsEffectsHash = Hash.sha256ToField(bytes.concat(baseLeaves[0], baseLeaves[1])); + bytes32 secondMergeTxsEffectsHash = Hash.sha256ToField(bytes.concat(baseLeaves[2], baseLeaves[3])); bytes32 thirdMergeTxsEffectsHash = Hash.sha256ToField(bytes.concat(firstMergeTxsEffectsHash, secondMergeTxsEffectsHash)); - bytes32 rootTxsEffectsHash = - Hash.sha256ToField(bytes.concat(thirdMergeTxsEffectsHash, baseLeaves[4])); + bytes32 rootTxsEffectsHash = Hash.sha256ToField(bytes.concat(thirdMergeTxsEffectsHash, baseLeaves[4])); bytes32 calculatedTxsEffectsHash = merkleLibHelper.computeUnbalancedRoot(baseLeaves); assertEq(calculatedTxsEffectsHash, rootTxsEffectsHash); } @@ -155,16 +151,12 @@ contract UnbalancedMerkleTest is Test { (uint256 min, uint256 max) = merkleLibHelper.computeMinMaxPathLength(6); assertEq(min, 2); assertEq(max, 3); - bytes32 firstMergeTxsEffectsHash = - Hash.sha256ToField(bytes.concat(baseLeaves[0], baseLeaves[1])); - bytes32 secondMergeTxsEffectsHash = - Hash.sha256ToField(bytes.concat(baseLeaves[2], baseLeaves[3])); - bytes32 thirdMergeTxsEffectsHash = - Hash.sha256ToField(bytes.concat(baseLeaves[4], baseLeaves[5])); + bytes32 firstMergeTxsEffectsHash = Hash.sha256ToField(bytes.concat(baseLeaves[0], baseLeaves[1])); + bytes32 secondMergeTxsEffectsHash = Hash.sha256ToField(bytes.concat(baseLeaves[2], baseLeaves[3])); + bytes32 thirdMergeTxsEffectsHash = Hash.sha256ToField(bytes.concat(baseLeaves[4], baseLeaves[5])); bytes32 fourthMergeTxsEffectsHash = Hash.sha256ToField(bytes.concat(firstMergeTxsEffectsHash, secondMergeTxsEffectsHash)); - bytes32 rootTxsEffectsHash = - Hash.sha256ToField(bytes.concat(fourthMergeTxsEffectsHash, thirdMergeTxsEffectsHash)); + bytes32 rootTxsEffectsHash = Hash.sha256ToField(bytes.concat(fourthMergeTxsEffectsHash, thirdMergeTxsEffectsHash)); bytes32 calculatedTxsEffectsHash = merkleLibHelper.computeUnbalancedRoot(baseLeaves); assertEq(calculatedTxsEffectsHash, rootTxsEffectsHash); } @@ -187,19 +179,14 @@ contract UnbalancedMerkleTest is Test { (uint256 min, uint256 max) = merkleLibHelper.computeMinMaxPathLength(7); assertEq(min, 2); assertEq(max, 3); - bytes32 firstMergeTxsEffectsHash = - Hash.sha256ToField(bytes.concat(baseLeaves[0], baseLeaves[1])); - bytes32 secondMergeTxsEffectsHash = - Hash.sha256ToField(bytes.concat(baseLeaves[2], baseLeaves[3])); + bytes32 firstMergeTxsEffectsHash = Hash.sha256ToField(bytes.concat(baseLeaves[0], baseLeaves[1])); + bytes32 secondMergeTxsEffectsHash = Hash.sha256ToField(bytes.concat(baseLeaves[2], baseLeaves[3])); bytes32 thirdMergeTxsEffectsHash = Hash.sha256ToField(bytes.concat(firstMergeTxsEffectsHash, secondMergeTxsEffectsHash)); - bytes32 fourthMergeTxsEffectsHash = - Hash.sha256ToField(bytes.concat(baseLeaves[4], baseLeaves[5])); - bytes32 fifthMergeTxsEffectsHash = - Hash.sha256ToField(bytes.concat(fourthMergeTxsEffectsHash, baseLeaves[6])); + bytes32 fourthMergeTxsEffectsHash = Hash.sha256ToField(bytes.concat(baseLeaves[4], baseLeaves[5])); + bytes32 fifthMergeTxsEffectsHash = Hash.sha256ToField(bytes.concat(fourthMergeTxsEffectsHash, baseLeaves[6])); - bytes32 rootTxsEffectsHash = - Hash.sha256ToField(bytes.concat(thirdMergeTxsEffectsHash, fifthMergeTxsEffectsHash)); + bytes32 rootTxsEffectsHash = Hash.sha256ToField(bytes.concat(thirdMergeTxsEffectsHash, fifthMergeTxsEffectsHash)); bytes32 calculatedTxsEffectsHash = merkleLibHelper.computeUnbalancedRoot(baseLeaves); assertEq(calculatedTxsEffectsHash, rootTxsEffectsHash); } diff --git a/l1-contracts/test/merkle/helpers/MerkleLibHelper.sol b/l1-contracts/test/merkle/helpers/MerkleLibHelper.sol index 7f8c15f94ed9..54bcc774557f 100644 --- a/l1-contracts/test/merkle/helpers/MerkleLibHelper.sol +++ b/l1-contracts/test/merkle/helpers/MerkleLibHelper.sol @@ -4,14 +4,13 @@ pragma solidity >=0.8.27; import {MerkleLib} from "@aztec/core/libraries/crypto/MerkleLib.sol"; -// A wrapper used to be able to "call" library functions, instead of "jumping" to them, allowing forge to catch the reverts +// A wrapper used to be able to "call" library functions, instead of "jumping" to them, allowing forge to catch the +// reverts contract MerkleLibHelper { - function verifyMembership( - bytes32[] calldata _path, - bytes32 _leaf, - uint256 _index, - bytes32 _expectedRoot - ) external pure { + function verifyMembership(bytes32[] calldata _path, bytes32 _leaf, uint256 _index, bytes32 _expectedRoot) + external + pure + { MerkleLib.verifyMembership(_path, _leaf, _index, _expectedRoot); } diff --git a/l1-contracts/test/portals/TokenPortal.sol b/l1-contracts/test/portals/TokenPortal.sol index b558e429894c..ff5ab3b16602 100644 --- a/l1-contracts/test/portals/TokenPortal.sol +++ b/l1-contracts/test/portals/TokenPortal.sol @@ -16,13 +16,9 @@ import {Hash} from "@aztec/core/libraries/crypto/Hash.sol"; contract TokenPortal { using SafeERC20 for IERC20; - event DepositToAztecPublic( - bytes32 to, uint256 amount, bytes32 secretHash, bytes32 key, uint256 index - ); + event DepositToAztecPublic(bytes32 to, uint256 amount, bytes32 secretHash, bytes32 key, uint256 index); - event DepositToAztecPrivate( - uint256 amount, bytes32 secretHashForL2MessageConsumption, bytes32 key, uint256 index - ); + event DepositToAztecPrivate(uint256 amount, bytes32 secretHashForL2MessageConsumption, bytes32 key, uint256 index); IRegistry public registry; IERC20 public underlying; @@ -57,12 +53,11 @@ contract TokenPortal { * @notice Deposit funds into the portal and adds an L2 message which can only be consumed publicly on Aztec * @param _to - The aztec address of the recipient * @param _amount - The amount to deposit - * @param _secretHash - The hash of the secret consumable message. The hash should be 254 bits (so it can fit in a Field element) + * @param _secretHash - The hash of the secret consumable message. The hash should be 254 bits (so it can fit in a + * Field element) * @return The key of the entry in the Inbox and its leaf index */ - function depositToAztecPublic(bytes32 _to, uint256 _amount, bytes32 _secretHash) - external - returns (bytes32, uint256) + function depositToAztecPublic(bytes32 _to, uint256 _amount, bytes32 _secretHash) external returns (bytes32, uint256) // docs:end:deposit_public { // Preamble @@ -71,8 +66,7 @@ contract TokenPortal { // Hash the message content to be reconstructed in the receiving contract // The purpose of including the function selector is to make the message unique to that specific call. Note that // it has nothing to do with calling the function. - bytes32 contentHash = - Hash.sha256ToField(abi.encodeWithSignature("mint_to_public(bytes32,uint256)", _to, _amount)); + bytes32 contentHash = Hash.sha256ToField(abi.encodeWithSignature("mint_to_public(bytes32,uint256)", _to, _amount)); // Hold the tokens in the portal underlying.safeTransferFrom(msg.sender, address(this), _amount); @@ -90,7 +84,8 @@ contract TokenPortal { /** * @notice Deposit funds into the portal and adds an L2 message which can only be consumed privately on Aztec * @param _amount - The amount to deposit - * @param _secretHashForL2MessageConsumption - The hash of the secret consumable L1 to L2 message. The hash should be 254 bits (so it can fit in a Field element) + * @param _secretHashForL2MessageConsumption - The hash of the secret consumable L1 to L2 message. The hash should be + * 254 bits (so it can fit in a Field element) * @return The key of the entry in the Inbox and its leaf index */ function depositToAztecPrivate(uint256 _amount, bytes32 _secretHashForL2MessageConsumption) @@ -103,15 +98,13 @@ contract TokenPortal { // Hash the message content to be reconstructed in the receiving contract - the signature below does not correspond // to a real function. It's just an identifier of an action. - bytes32 contentHash = - Hash.sha256ToField(abi.encodeWithSignature("mint_to_private(uint256)", _amount)); + bytes32 contentHash = Hash.sha256ToField(abi.encodeWithSignature("mint_to_private(uint256)", _amount)); // Hold the tokens in the portal underlying.safeTransferFrom(msg.sender, address(this), _amount); // Send message to rollup - (bytes32 key, uint256 index) = - inbox.sendL2Message(actor, contentHash, _secretHashForL2MessageConsumption); + (bytes32 key, uint256 index) = inbox.sendL2Message(actor, contentHash, _secretHashForL2MessageConsumption); // Emit event emit DepositToAztecPrivate(_amount, _secretHashForL2MessageConsumption, key, index); @@ -146,10 +139,7 @@ contract TokenPortal { recipient: DataStructures.L1Actor(address(this), block.chainid), content: Hash.sha256ToField( abi.encodeWithSignature( - "withdraw(address,uint256,address)", - _recipient, - _amount, - _withCaller ? msg.sender : address(0) + "withdraw(address,uint256,address)", _recipient, _amount, _withCaller ? msg.sender : address(0) ) ) }); diff --git a/l1-contracts/test/portals/TokenPortal.t.sol b/l1-contracts/test/portals/TokenPortal.t.sol index f959431cb505..7cfc2442a77d 100644 --- a/l1-contracts/test/portals/TokenPortal.t.sol +++ b/l1-contracts/test/portals/TokenPortal.t.sol @@ -76,8 +76,7 @@ contract TokenPortalTest is Test { tokenPortal.initialize(address(registry), address(testERC20), l2TokenAddress); // Modify the proven block count - stdstore.enable_packed_slots().target(address(rollup)).sig("getProvenBlockNumber()") - .checked_write(l2BlockNumber); + stdstore.enable_packed_slots().target(address(rollup)).sig("getProvenBlockNumber()").checked_write(l2BlockNumber); assertEq(rollup.getProvenBlockNumber(), l2BlockNumber); vm.deal(address(this), 100 ether); @@ -109,9 +108,7 @@ contract TokenPortalTest is Test { return DataStructures.L1ToL2Msg({ sender: DataStructures.L1Actor(address(tokenPortal), block.chainid), recipient: DataStructures.L2Actor(l2TokenAddress, rollup.getVersion()), - content: Hash.sha256ToField( - abi.encodeWithSignature("mint_to_public(bytes32,uint256)", to, amount) - ), + content: Hash.sha256ToField(abi.encodeWithSignature("mint_to_public(bytes32,uint256)", to, amount)), secretHash: secretHashForL2MessageConsumption, index: _index }); @@ -125,12 +122,10 @@ contract TokenPortalTest is Test { // Check for the expected message uint256 expectedIndex = (FIRST_REAL_TREE_NUM - 1) * L1_TO_L2_MSG_SUBTREE_SIZE; - DataStructures.L1ToL2Msg memory expectedMessage = - _createExpectedMintPrivateL1ToL2Message(expectedIndex); + DataStructures.L1ToL2Msg memory expectedMessage = _createExpectedMintPrivateL1ToL2Message(expectedIndex); bytes32 expectedLeaf = expectedMessage.sha256ToField(); - bytes16 expectedHash = - bytes16(keccak256(abi.encodePacked(inbox.getState().rollingHash, expectedLeaf))); + bytes16 expectedHash = bytes16(keccak256(abi.encodePacked(inbox.getState().rollingHash, expectedLeaf))); // Check the event was emitted vm.expectEmit(true, true, true, true); // event we expect @@ -138,8 +133,7 @@ contract TokenPortalTest is Test { // event we will get // Perform op - (bytes32 leaf, uint256 index) = - tokenPortal.depositToAztecPrivate(amount, secretHashForL2MessageConsumption); + (bytes32 leaf, uint256 index) = tokenPortal.depositToAztecPrivate(amount, secretHashForL2MessageConsumption); assertEq(leaf, expectedLeaf, "returned leaf and calculated leaf should match"); assertEq(index, expectedIndex, "returned index and calculated index should match"); @@ -155,11 +149,9 @@ contract TokenPortalTest is Test { // Check for the expected message uint256 expectedIndex = (FIRST_REAL_TREE_NUM - 1) * L1_TO_L2_MSG_SUBTREE_SIZE; - DataStructures.L1ToL2Msg memory expectedMessage = - _createExpectedMintPublicL1ToL2Message(expectedIndex); + DataStructures.L1ToL2Msg memory expectedMessage = _createExpectedMintPublicL1ToL2Message(expectedIndex); bytes32 expectedLeaf = expectedMessage.sha256ToField(); - bytes16 expectedHash = - bytes16(keccak256(abi.encodePacked(inbox.getState().rollingHash, expectedLeaf))); + bytes16 expectedHash = bytes16(keccak256(abi.encodePacked(inbox.getState().rollingHash, expectedLeaf))); // Check the event was emitted vm.expectEmit(true, true, true, true); @@ -167,8 +159,7 @@ contract TokenPortalTest is Test { emit IInbox.MessageSent(FIRST_REAL_TREE_NUM, expectedIndex, expectedLeaf, expectedHash); // Perform op - (bytes32 leaf, uint256 index) = - tokenPortal.depositToAztecPublic(to, amount, secretHashForL2MessageConsumption); + (bytes32 leaf, uint256 index) = tokenPortal.depositToAztecPublic(to, amount, secretHashForL2MessageConsumption); assertEq(leaf, expectedLeaf, "returned leaf and calculated leaf should match"); assertEq(index, expectedIndex, "returned index and calculated index should match"); @@ -176,10 +167,7 @@ contract TokenPortalTest is Test { return leaf; } - function _createWithdrawMessageForOutbox(address _designatedCaller) - internal - returns (bytes32, bytes32) - { + function _createWithdrawMessageForOutbox(address _designatedCaller) internal returns (bytes32, bytes32) { // The purpose of including the function selector is to make the message unique to that specific call. Note that // it has nothing to do with calling the function. bytes32 l2ToL1Message = Hash.sha256ToField( @@ -187,9 +175,7 @@ contract TokenPortalTest is Test { sender: DataStructures.L2Actor({actor: l2TokenAddress, version: rollup.getVersion()}), recipient: DataStructures.L1Actor({actor: address(tokenPortal), chainId: block.chainid}), content: Hash.sha256ToField( - abi.encodeWithSignature( - "withdraw(address,uint256,address)", recipient, withdrawAmount, _designatedCaller - ) + abi.encodeWithSignature("withdraw(address,uint256,address)", recipient, withdrawAmount, _designatedCaller) ) }) ); @@ -247,9 +233,7 @@ contract TokenPortalTest is Test { assertEq(testERC20.balanceOf(recipient), withdrawAmount); // Should not be able to withdraw again - vm.expectRevert( - abi.encodeWithSelector(Errors.Outbox__AlreadyNullified.selector, l2BlockNumber, leafId) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Outbox__AlreadyNullified.selector, l2BlockNumber, leafId)); tokenPortal.withdraw(recipient, withdrawAmount, false, l2BlockNumber, leafIndex, siblingPath); vm.stopPrank(); } @@ -257,23 +241,18 @@ contract TokenPortalTest is Test { function testWithdrawWithDesignatedCallerFailsForOtherCallers(address _caller) public { vm.assume(_caller != address(this)); // add message with caller as this address - (, bytes32[] memory siblingPath, bytes32 treeRoot) = - _addWithdrawMessageInOutbox(address(this), l2BlockNumber); + (, bytes32[] memory siblingPath, bytes32 treeRoot) = _addWithdrawMessageInOutbox(address(this), l2BlockNumber); vm.startPrank(_caller); (bytes32 l2ToL1MessageHash, bytes32 consumedRoot) = _createWithdrawMessageForOutbox(_caller); vm.expectRevert( - abi.encodeWithSelector( - Errors.MerkleLib__InvalidRoot.selector, treeRoot, consumedRoot, l2ToL1MessageHash, 0 - ) + abi.encodeWithSelector(Errors.MerkleLib__InvalidRoot.selector, treeRoot, consumedRoot, l2ToL1MessageHash, 0) ); tokenPortal.withdraw(recipient, withdrawAmount, true, l2BlockNumber, 0, siblingPath); (l2ToL1MessageHash, consumedRoot) = _createWithdrawMessageForOutbox(address(0)); vm.expectRevert( - abi.encodeWithSelector( - Errors.MerkleLib__InvalidRoot.selector, treeRoot, consumedRoot, l2ToL1MessageHash, 0 - ) + abi.encodeWithSelector(Errors.MerkleLib__InvalidRoot.selector, treeRoot, consumedRoot, l2ToL1MessageHash, 0) ); tokenPortal.withdraw(recipient, withdrawAmount, false, l2BlockNumber, 0, siblingPath); vm.stopPrank(); diff --git a/l1-contracts/test/portals/UniswapPortal.sol b/l1-contracts/test/portals/UniswapPortal.sol index 7b7309155349..649930e89ab8 100644 --- a/l1-contracts/test/portals/UniswapPortal.sol +++ b/l1-contracts/test/portals/UniswapPortal.sol @@ -59,7 +59,8 @@ contract UniswapPortal { * @param _outputTokenPortal - The ethereum address of the output token portal * @param _amountOutMinimum - The minimum amount of output assets to receive from the swap (slippage protection) * @param _aztecRecipient - The aztec address to receive the output assets - * @param _secretHashForL1ToL2Message - The hash of the secret consumable message. The hash should be 254 bits (so it can fit in a Field element) + * @param _secretHashForL1ToL2Message - The hash of the secret consumable message. The hash should be 254 bits (so it + * can fit in a Field element) * @param _withCaller - When true, using `msg.sender` as the caller, otherwise address(0) * @return A hash of the L1 to L2 message inserted in the Inbox */ @@ -148,9 +149,7 @@ contract UniswapPortal { vars.outputAsset.approve(address(_outputTokenPortal), amountOut); // Deposit the output asset to the L2 via its portal - return TokenPortal(_outputTokenPortal).depositToAztecPublic( - _aztecRecipient, amountOut, _secretHashForL1ToL2Message - ); + return TokenPortal(_outputTokenPortal).depositToAztecPublic(_aztecRecipient, amountOut, _secretHashForL1ToL2Message); } // docs:end:solidity_uniswap_swap_public @@ -165,7 +164,8 @@ contract UniswapPortal { * @param _uniswapFeeTier - The fee tier for the swap on UniswapV3 * @param _outputTokenPortal - The ethereum address of the output token portal * @param _amountOutMinimum - The minimum amount of output assets to receive from the swap (slippage protection) - * @param _secretHashForL1ToL2Message - The hash of the secret consumable message. The hash should be 254 bits (so it can fit in a Field element) + * @param _secretHashForL1ToL2Message - The hash of the secret consumable message. The hash should be 254 bits (so it + * can fit in a Field element) * @param _withCaller - When true, using `msg.sender` as the caller, otherwise address(0) * @return A hash of the L1 to L2 message inserted in the Inbox */ @@ -251,8 +251,7 @@ contract UniswapPortal { vars.outputAsset.approve(address(_outputTokenPortal), amountOut); // Deposit the output asset to the L2 via its portal - return - TokenPortal(_outputTokenPortal).depositToAztecPrivate(amountOut, _secretHashForL1ToL2Message); + return TokenPortal(_outputTokenPortal).depositToAztecPrivate(amountOut, _secretHashForL1ToL2Message); } } // docs:end:solidity_uniswap_swap_private diff --git a/l1-contracts/test/portals/UniswapPortal.t.sol b/l1-contracts/test/portals/UniswapPortal.t.sol index 6129fdf495e1..a7418d283396 100644 --- a/l1-contracts/test/portals/UniswapPortal.t.sol +++ b/l1-contracts/test/portals/UniswapPortal.t.sol @@ -169,11 +169,10 @@ contract UniswapPortalTest is Test { return message.sha256ToField(); } - function _addMessagesToOutbox( - bytes32 daiWithdrawMessageHash, - bytes32 swapMessageHash, - uint256 _l2BlockNumber - ) internal returns (bytes32, bytes32[] memory, bytes32[] memory) { + function _addMessagesToOutbox(bytes32 daiWithdrawMessageHash, bytes32 swapMessageHash, uint256 _l2BlockNumber) + internal + returns (bytes32, bytes32[] memory, bytes32[] memory) + { uint256 treeHeight = 1; NaiveMerkle tree = new NaiveMerkle(treeHeight); tree.insertLeaf(daiWithdrawMessageHash); @@ -195,8 +194,7 @@ contract UniswapPortalTest is Test { bytes32 l2ToL1MessageToInsert = _createDaiWithdrawMessage(address(uniswapPortal), address(0)); (, bytes32[] memory withdrawSiblingPath, bytes32[] memory swapSiblingPath) = _addMessagesToOutbox(l2ToL1MessageToInsert, bytes32(uint256(0x1)), l2BlockNumber); - bytes32 l2ToL1MessageToConsume = - _createDaiWithdrawMessage(address(uniswapPortal), address(uniswapPortal)); + bytes32 l2ToL1MessageToConsume = _createDaiWithdrawMessage(address(uniswapPortal), address(uniswapPortal)); uint256 treeHeight = 1; NaiveMerkle tree1 = new NaiveMerkle(treeHeight); @@ -221,11 +219,7 @@ contract UniswapPortalTest is Test { _leafIndex: 0, _path: withdrawSiblingPath }), - PortalDataStructures.OutboxMessageMetadata({ - _l2BlockNumber: l2BlockNumber, - _leafIndex: 1, - _path: swapSiblingPath - }) + PortalDataStructures.OutboxMessageMetadata({_l2BlockNumber: l2BlockNumber, _leafIndex: 1, _path: swapSiblingPath}) ]; uniswapPortal.swapPublic( @@ -251,8 +245,7 @@ contract UniswapPortalTest is Test { (, bytes32[] memory withdrawSiblingPath, bytes32[] memory swapSiblingPath) = _addMessagesToOutbox(l2ToL1MessageToInsert, bytes32(uint256(0x1)), l2BlockNumber); - bytes32 l2ToL1MessageToConsume = - _createDaiWithdrawMessage(address(uniswapPortal), address(uniswapPortal)); + bytes32 l2ToL1MessageToConsume = _createDaiWithdrawMessage(address(uniswapPortal), address(uniswapPortal)); uint256 treeHeight = 1; NaiveMerkle tree1 = new NaiveMerkle(treeHeight); @@ -277,11 +270,7 @@ contract UniswapPortalTest is Test { _leafIndex: 0, _path: withdrawSiblingPath }), - PortalDataStructures.OutboxMessageMetadata({ - _l2BlockNumber: l2BlockNumber, - _leafIndex: 1, - _path: swapSiblingPath - }) + PortalDataStructures.OutboxMessageMetadata({_l2BlockNumber: l2BlockNumber, _leafIndex: 1, _path: swapSiblingPath}) ]; uniswapPortal.swapPublic( @@ -298,15 +287,13 @@ contract UniswapPortalTest is Test { } function testRevertIfSwapParamsDifferentToOutboxMessage() public { - bytes32 daiWithdrawMessageHash = - _createDaiWithdrawMessage(address(uniswapPortal), address(uniswapPortal)); + bytes32 daiWithdrawMessageHash = _createDaiWithdrawMessage(address(uniswapPortal), address(uniswapPortal)); bytes32 swapMessageHash = _createUniswapSwapMessagePublic(aztecRecipient, address(this)); (, bytes32[] memory withdrawSiblingPath, bytes32[] memory swapSiblingPath) = _addMessagesToOutbox(daiWithdrawMessageHash, swapMessageHash, l2BlockNumber); bytes32 newAztecRecipient = bytes32(uint256(0x4)); - bytes32 messageHashPortalChecksAgainst = - _createUniswapSwapMessagePublic(newAztecRecipient, address(this)); + bytes32 messageHashPortalChecksAgainst = _createUniswapSwapMessagePublic(newAztecRecipient, address(this)); bytes32 actualRoot; bytes32 consumedRoot; @@ -326,11 +313,7 @@ contract UniswapPortalTest is Test { vm.expectRevert( abi.encodeWithSelector( - Errors.MerkleLib__InvalidRoot.selector, - actualRoot, - consumedRoot, - messageHashPortalChecksAgainst, - 1 + Errors.MerkleLib__InvalidRoot.selector, actualRoot, consumedRoot, messageHashPortalChecksAgainst, 1 ) ); @@ -340,11 +323,7 @@ contract UniswapPortalTest is Test { _leafIndex: 0, _path: withdrawSiblingPath }), - PortalDataStructures.OutboxMessageMetadata({ - _l2BlockNumber: l2BlockNumber, - _leafIndex: 1, - _path: swapSiblingPath - }) + PortalDataStructures.OutboxMessageMetadata({_l2BlockNumber: l2BlockNumber, _leafIndex: 1, _path: swapSiblingPath}) ]; uniswapPortal.swapPublic( @@ -361,8 +340,7 @@ contract UniswapPortalTest is Test { } function testSwapWithDesignatedCaller() public { - bytes32 daiWithdrawMessageHash = - _createDaiWithdrawMessage(address(uniswapPortal), address(uniswapPortal)); + bytes32 daiWithdrawMessageHash = _createDaiWithdrawMessage(address(uniswapPortal), address(uniswapPortal)); bytes32 swapMessageHash = _createUniswapSwapMessagePublic(aztecRecipient, address(this)); (, bytes32[] memory withdrawSiblingPath, bytes32[] memory swapSiblingPath) = @@ -374,11 +352,7 @@ contract UniswapPortalTest is Test { _leafIndex: 0, _path: withdrawSiblingPath }), - PortalDataStructures.OutboxMessageMetadata({ - _l2BlockNumber: l2BlockNumber, - _leafIndex: 1, - _path: swapSiblingPath - }) + PortalDataStructures.OutboxMessageMetadata({_l2BlockNumber: l2BlockNumber, _leafIndex: 1, _path: swapSiblingPath}) ]; uniswapPortal.swapPublic( @@ -405,8 +379,7 @@ contract UniswapPortalTest is Test { function testSwapCalledByAnyoneIfDesignatedCallerNotSet(address _caller) public { vm.assume(_caller != address(uniswapPortal)); - bytes32 daiWithdrawMessageHash = - _createDaiWithdrawMessage(address(uniswapPortal), address(uniswapPortal)); + bytes32 daiWithdrawMessageHash = _createDaiWithdrawMessage(address(uniswapPortal), address(uniswapPortal)); // don't set caller on swapPublic() -> so anyone can call this method. bytes32 swapMessageHash = _createUniswapSwapMessagePublic(aztecRecipient, address(0)); @@ -419,11 +392,7 @@ contract UniswapPortalTest is Test { _leafIndex: 0, _path: withdrawSiblingPath }), - PortalDataStructures.OutboxMessageMetadata({ - _l2BlockNumber: l2BlockNumber, - _leafIndex: 1, - _path: swapSiblingPath - }) + PortalDataStructures.OutboxMessageMetadata({_l2BlockNumber: l2BlockNumber, _leafIndex: 1, _path: swapSiblingPath}) ]; vm.prank(_caller); @@ -451,8 +420,7 @@ contract UniswapPortalTest is Test { function testRevertIfSwapWithDesignatedCallerCalledByWrongCaller(address _caller) public { vm.assume(_caller != address(this)); - bytes32 daiWithdrawMessageHash = - _createDaiWithdrawMessage(address(uniswapPortal), address(uniswapPortal)); + bytes32 daiWithdrawMessageHash = _createDaiWithdrawMessage(address(uniswapPortal), address(uniswapPortal)); bytes32 swapMessageHash = _createUniswapSwapMessagePublic(aztecRecipient, address(this)); (, bytes32[] memory withdrawSiblingPath, bytes32[] memory swapSiblingPath) = @@ -464,16 +432,11 @@ contract UniswapPortalTest is Test { _leafIndex: 0, _path: withdrawSiblingPath }), - PortalDataStructures.OutboxMessageMetadata({ - _l2BlockNumber: l2BlockNumber, - _leafIndex: 1, - _path: swapSiblingPath - }) + PortalDataStructures.OutboxMessageMetadata({_l2BlockNumber: l2BlockNumber, _leafIndex: 1, _path: swapSiblingPath}) ]; vm.startPrank(_caller); - bytes32 messageHashPortalChecksAgainst = - _createUniswapSwapMessagePublic(aztecRecipient, _caller); + bytes32 messageHashPortalChecksAgainst = _createUniswapSwapMessagePublic(aztecRecipient, _caller); bytes32 actualRoot; bytes32 consumedRoot; @@ -493,11 +456,7 @@ contract UniswapPortalTest is Test { vm.expectRevert( abi.encodeWithSelector( - Errors.MerkleLib__InvalidRoot.selector, - actualRoot, - consumedRoot, - messageHashPortalChecksAgainst, - 1 + Errors.MerkleLib__InvalidRoot.selector, actualRoot, consumedRoot, messageHashPortalChecksAgainst, 1 ) ); @@ -529,11 +488,7 @@ contract UniswapPortalTest is Test { } vm.expectRevert( abi.encodeWithSelector( - Errors.MerkleLib__InvalidRoot.selector, - actualRoot, - consumedRoot, - messageHashPortalChecksAgainst, - 1 + Errors.MerkleLib__InvalidRoot.selector, actualRoot, consumedRoot, messageHashPortalChecksAgainst, 1 ) ); uniswapPortal.swapPublic( @@ -551,8 +506,7 @@ contract UniswapPortalTest is Test { } function testRevertIfSwapMessageWasForDifferentPublicOrPrivateFlow() public { - bytes32 daiWithdrawMessageHash = - _createDaiWithdrawMessage(address(uniswapPortal), address(uniswapPortal)); + bytes32 daiWithdrawMessageHash = _createDaiWithdrawMessage(address(uniswapPortal), address(uniswapPortal)); // Create message for `_isPrivateFlow`: bytes32 swapMessageHash = _createUniswapSwapMessagePublic(aztecRecipient, address(this)); @@ -565,11 +519,7 @@ contract UniswapPortalTest is Test { _leafIndex: 0, _path: withdrawSiblingPath }), - PortalDataStructures.OutboxMessageMetadata({ - _l2BlockNumber: l2BlockNumber, - _leafIndex: 1, - _path: swapSiblingPath - }) + PortalDataStructures.OutboxMessageMetadata({_l2BlockNumber: l2BlockNumber, _leafIndex: 1, _path: swapSiblingPath}) ]; bytes32 messageHashPortalChecksAgainst = _createUniswapSwapMessagePrivate(address(this)); @@ -592,11 +542,7 @@ contract UniswapPortalTest is Test { vm.expectRevert( abi.encodeWithSelector( - Errors.MerkleLib__InvalidRoot.selector, - actualRoot, - consumedRoot, - messageHashPortalChecksAgainst, - 1 + Errors.MerkleLib__InvalidRoot.selector, actualRoot, consumedRoot, messageHashPortalChecksAgainst, 1 ) ); diff --git a/l1-contracts/test/shouting.t.sol b/l1-contracts/test/shouting.t.sol index 7999206499e0..fa2ce84be1e0 100644 --- a/l1-contracts/test/shouting.t.sol +++ b/l1-contracts/test/shouting.t.sol @@ -21,35 +21,27 @@ contract ScreamAndShoutTest is Test { bytes memory creationCode = type(Governance).creationCode; bytes32 codeHash = keccak256(creationCode); - assertEq( - codeHash, 0xf302136f8b3a84d3c36be87e283cda0d6ad04392b7e3c5379c55b2d5b2634c1c, ERR_STRING - ); + assertEq(codeHash, 0xf302136f8b3a84d3c36be87e283cda0d6ad04392b7e3c5379c55b2d5b2634c1c, ERR_STRING); } function test_HonkVerifierCreationCode() public pure { bytes memory creationCode = type(HonkVerifier).creationCode; bytes32 codeHash = keccak256(creationCode); - assertEq( - codeHash, 0xe64a1670c48b0e0f03d405cdf00a7bc6823a47f89851e02680f827e055fd3c60, ERR_STRING - ); + assertEq(codeHash, 0xe64a1670c48b0e0f03d405cdf00a7bc6823a47f89851e02680f827e055fd3c60, ERR_STRING); } function test_RegistryCreationCode() public pure { bytes memory creationCode = type(Registry).creationCode; bytes32 codeHash = keccak256(creationCode); - assertEq( - codeHash, 0x2cb444995a1644607bd5bdeb3ce0027a8484849810c28b57e641cdf61d786c4c, ERR_STRING - ); + assertEq(codeHash, 0x2cb444995a1644607bd5bdeb3ce0027a8484849810c28b57e641cdf61d786c4c, ERR_STRING); } function test_RollupCreationCode() public pure { bytes memory creationCode = type(Rollup).creationCode; bytes32 codeHash = keccak256(creationCode); - assertEq( - codeHash, 0xb87a83463eba5f258db1166fb43f2cd6c55169fb5ef39412157d3acea384f7ce, ERR_STRING - ); + assertEq(codeHash, 0xb87a83463eba5f258db1166fb43f2cd6c55169fb5ef39412157d3acea384f7ce, ERR_STRING); } } diff --git a/l1-contracts/test/staking/15050.t.sol b/l1-contracts/test/staking/15050.t.sol index 9d057301dfb3..857e64ca116c 100644 --- a/l1-contracts/test/staking/15050.t.sol +++ b/l1-contracts/test/staking/15050.t.sol @@ -3,9 +3,7 @@ pragma solidity >=0.8.27; import {StakingBase} from "./base.t.sol"; import {Errors} from "@aztec/core/libraries/Errors.sol"; -import { - IStakingCore, Status, AttesterView, Exit, Timestamp -} from "@aztec/core/interfaces/IStaking.sol"; +import {IStakingCore, Status, AttesterView, Exit, Timestamp} from "@aztec/core/interfaces/IStaking.sol"; import {Slasher} from "@aztec/core/slashing/Slasher.sol"; import {SlashPayload, IPayload} from "@aztec/periphery/SlashPayload.sol"; @@ -41,19 +39,19 @@ contract Test15050 is StakingBase { assertEq(attesterView.exit.exitableAt, 0); assertEq(attesterView.exit.isRecipient, false); - SlashPayload payload = - new SlashPayload(validators, amounts, IValidatorSelection(address(staking))); + SlashPayload payload = new SlashPayload(validators, amounts, IValidatorSelection(address(staking))); SlashingProposer caller = Slasher(SLASHER).PROPOSER(); stdstore.clear(); - stdstore.enable_packed_slots().target(address(caller)).sig("getRoundData(address,uint256)") - .with_key(address(staking)).with_key(uint256(0)).depth(1).checked_write(address(payload)); + stdstore.enable_packed_slots().target(address(caller)).sig("getRoundData(address,uint256)").with_key( + address(staking) + ).with_key(uint256(0)).depth(1).checked_write(address(payload)); stdstore.clear(); - stdstore.target(address(caller)).sig("signalCount(address,uint256,address)").with_key( - address(staking) - ).with_key(uint256(0)).with_key(address(payload)).checked_write(caller.ROUND_SIZE()); + stdstore.target(address(caller)).sig("signalCount(address,uint256,address)").with_key(address(staking)).with_key( + uint256(0) + ).with_key(address(payload)).checked_write(caller.ROUND_SIZE()); assertEq(caller.getCurrentRound(), 0); @@ -69,14 +67,12 @@ contract Test15050 is StakingBase { address target = payload.getActions()[0].target; bytes memory data = payload.getActions()[0].data; bytes memory returnData = ""; // empty because oog won't give anything back. - vm.expectRevert( - abi.encodeWithSelector(Slasher.Slasher__SlashFailed.selector, target, data, returnData) - ); + vm.expectRevert(abi.encodeWithSelector(Slasher.Slasher__SlashFailed.selector, target, data, returnData)); // We execute the proposal with some gas amount that is insufficient to execute all // the accounting. And then we see that the proposal is marked as executed, so we cannot // execute it again, but at the same time, the attester was not actually slashes! // It can require a bit of fiddling here to get the correct one going gas-wise. - caller.submitRoundWinner{gas: 200000}(0); + caller.submitRoundWinner{gas: 200_000}(0); r = caller.getRoundData(address(staking), 0); assertFalse(r.executed); diff --git a/l1-contracts/test/staking/base.t.sol b/l1-contracts/test/staking/base.t.sol index c50339be38c9..f100b991700f 100644 --- a/l1-contracts/test/staking/base.t.sol +++ b/l1-contracts/test/staking/base.t.sol @@ -25,8 +25,7 @@ contract StakingBase is TestBase { address internal SLASHER; function setUp() public virtual { - RollupBuilder builder = - new RollupBuilder(address(this)).setSlashingQuorum(1).setSlashingRoundSize(1); + RollupBuilder builder = new RollupBuilder(address(this)).setSlashingQuorum(1).setSlashingRoundSize(1); builder.deploy(); registry = builder.getConfig().registry; diff --git a/l1-contracts/test/staking/deposit.t.sol b/l1-contracts/test/staking/deposit.t.sol index 27c848765aff..ac9ecc05948a 100644 --- a/l1-contracts/test/staking/deposit.t.sol +++ b/l1-contracts/test/staking/deposit.t.sol @@ -40,9 +40,7 @@ contract DepositTest is StakingBase { // it reverts vm.expectRevert( - abi.encodeWithSelector( - IERC20Errors.ERC20InsufficientBalance.selector, address(this), 0, ACTIVATION_THRESHOLD - ) + abi.encodeWithSelector(IERC20Errors.ERC20InsufficientBalance.selector, address(this), 0, ACTIVATION_THRESHOLD) ); staking.deposit({_attester: ATTESTER, _withdrawer: WITHDRAWER, _moveWithLatestRollup: true}); @@ -67,9 +65,8 @@ contract DepositTest is StakingBase { stakingAsset.approve(address(staking), type(uint256).max); // Now reset the next flushable epoch to 0 - stdstore.enable_packed_slots().target(address(staking)).sig( - IStaking.getNextFlushableEpoch.selector - ).depth(0).checked_write(uint256(0)); + stdstore.enable_packed_slots().target(address(staking)).sig(IStaking.getNextFlushableEpoch.selector).depth(0) + .checked_write(uint256(0)); staking.deposit({_attester: ATTESTER, _withdrawer: WITHDRAWER, _moveWithLatestRollup: true}); // The real error gets caught by the flushEntryQueue call diff --git a/l1-contracts/test/staking/flushEntryQueue.t.sol b/l1-contracts/test/staking/flushEntryQueue.t.sol index f8e6da4234a8..585cb66be133 100644 --- a/l1-contracts/test/staking/flushEntryQueue.t.sol +++ b/l1-contracts/test/staking/flushEntryQueue.t.sol @@ -13,10 +13,7 @@ import {Status, AttesterView, IStakingCore} from "@aztec/core/interfaces/IStakin import {Math} from "@oz/utils/math/Math.sol"; import {GSE, IGSECore} from "@aztec/governance/GSE.sol"; import {StakingQueueLib} from "@aztec/core/libraries/StakingQueue.sol"; -import { - StakingQueueConfig, - StakingQueueConfigLib -} from "@aztec/core/libraries/compressed-data/StakingQueueConfig.sol"; +import {StakingQueueConfig, StakingQueueConfigLib} from "@aztec/core/libraries/compressed-data/StakingQueueConfig.sol"; import {Rollup} from "@aztec/core/Rollup.sol"; contract FlushEntryQueueTest is StakingBase { @@ -29,8 +26,7 @@ contract FlushEntryQueueTest is StakingBase { vm.expectRevert( abi.encodeWithSelector( - Errors.Staking__QueueAlreadyFlushed.selector, - Epoch.wrap(block.timestamp / EPOCH_DURATION_SECONDS) + Errors.Staking__QueueAlreadyFlushed.selector, Epoch.wrap(block.timestamp / EPOCH_DURATION_SECONDS) ) ); staking.flushEntryQueue(); @@ -72,9 +68,7 @@ contract FlushEntryQueueTest is StakingBase { _numValidators = bound(_numValidators, 0, _bootstrapValidatorSetSize - 1); _bootstrapFlushSize = bound(_bootstrapFlushSize, 1, StakingQueueLib.MAX_QUEUE_FLUSH_SIZE); - _setupQueueConfig( - _bootstrapValidatorSetSize, _bootstrapFlushSize, _normalFlushSizeMin, _normalFlushSizeQuotient - ); + _setupQueueConfig(_bootstrapValidatorSetSize, _bootstrapFlushSize, _normalFlushSizeMin, _normalFlushSizeQuotient); for (uint256 i = 1; i <= _numValidators; i++) { bool onCanonical = i % 2 == 0; @@ -103,14 +97,11 @@ contract FlushEntryQueueTest is StakingBase { // it refunds the withdrawer if the deposit fails _bootstrapValidatorSetSize = bound(_bootstrapValidatorSetSize, 1, 1000); - _numValidators = - bound(_numValidators, _bootstrapValidatorSetSize, _bootstrapValidatorSetSize * 2); + _numValidators = bound(_numValidators, _bootstrapValidatorSetSize, _bootstrapValidatorSetSize * 2); _bootstrapFlushSize = bound(_bootstrapFlushSize, 1, _bootstrapValidatorSetSize * 2); uint256 effectiveFlushSize = Math.min(_bootstrapFlushSize, StakingQueueLib.MAX_QUEUE_FLUSH_SIZE); - _setupQueueConfig( - _bootstrapValidatorSetSize, _bootstrapFlushSize, _normalFlushSizeMin, _normalFlushSizeQuotient - ); + _setupQueueConfig(_bootstrapValidatorSetSize, _bootstrapFlushSize, _normalFlushSizeMin, _normalFlushSizeQuotient); _help_flushEntryQueue(_numValidators, effectiveFlushSize); } @@ -132,9 +123,7 @@ contract FlushEntryQueueTest is StakingBase { _bootstrapFlushSize = bound(_bootstrapFlushSize, 1, _bootstrapValidatorSetSize / 3); uint256 effectiveFlushSize = Math.min(_bootstrapFlushSize, StakingQueueLib.MAX_QUEUE_FLUSH_SIZE); - _setupQueueConfig( - _bootstrapValidatorSetSize, _bootstrapFlushSize, _normalFlushSizeMin, _normalFlushSizeQuotient - ); + _setupQueueConfig(_bootstrapValidatorSetSize, _bootstrapFlushSize, _normalFlushSizeMin, _normalFlushSizeQuotient); for (uint256 i = 1; i <= _bootstrapValidatorSetSize; i++) { bool onCanonical = i % 2 == 0; @@ -146,9 +135,7 @@ contract FlushEntryQueueTest is StakingBase { vm.warp(block.timestamp + EPOCH_DURATION_SECONDS); staking.flushEntryQueue(); - assertEq( - staking.getActiveAttesterCount(), 2 * effectiveFlushSize, "invalid active attester count" - ); + assertEq(staking.getActiveAttesterCount(), 2 * effectiveFlushSize, "invalid active attester count"); assertEq(staking.getEntryQueueFlushSize(), effectiveFlushSize, "invalid flush size"); } @@ -169,8 +156,7 @@ contract FlushEntryQueueTest is StakingBase { _numNewValidators = bound(_numNewValidators, 0, 5 * _activeAttesterCount); _normalFlushSizeMin = bound(_normalFlushSizeMin, 1, 1000); _normalFlushSizeQuotient = bound(_normalFlushSizeQuotient, 1, 1000); - uint256 effectiveFlushSize = - Math.max(_normalFlushSizeMin, _activeAttesterCount / _normalFlushSizeQuotient); + uint256 effectiveFlushSize = Math.max(_normalFlushSizeMin, _activeAttesterCount / _normalFlushSizeQuotient); effectiveFlushSize = Math.min(effectiveFlushSize, StakingQueueLib.MAX_QUEUE_FLUSH_SIZE); _setupQueueConfig(0, 0, _normalFlushSizeMin, _normalFlushSizeQuotient); @@ -197,48 +183,30 @@ contract FlushEntryQueueTest is StakingBase { _help_flushEntryQueue(_numNewValidators, effectiveFlushSize); } - function _help_deposit(address _attester, address _withdrawer, bool _moveWithLatestRollup) - internal - { + function _help_deposit(address _attester, address _withdrawer, bool _moveWithLatestRollup) internal { mint(address(this), ACTIVATION_THRESHOLD); stakingAsset.approve(address(staking), ACTIVATION_THRESHOLD); uint256 balance = stakingAsset.balanceOf(address(staking)); - staking.deposit({ - _attester: _attester, - _withdrawer: _withdrawer, - _moveWithLatestRollup: _moveWithLatestRollup - }); + staking.deposit({_attester: _attester, _withdrawer: _withdrawer, _moveWithLatestRollup: _moveWithLatestRollup}); - assertEq( - stakingAsset.balanceOf(address(staking)), balance + ACTIVATION_THRESHOLD, "invalid balance" - ); + assertEq(stakingAsset.balanceOf(address(staking)), balance + ACTIVATION_THRESHOLD, "invalid balance"); } function _help_flushEntryQueue(uint256 _numValidators, uint256 _expectedFlushSize) internal { GSE gse = staking.getGSE(); address bonusInstanceAddress = gse.BONUS_INSTANCE_ADDRESS(); uint256 initialActiveAttesterCount = staking.getActiveAttesterCount(); - uint256 initialCanonicalCount = - gse.getAttestersAtTime(bonusInstanceAddress, Timestamp.wrap(block.timestamp)).length; - uint256 initialInstanceCount = - gse.getAttestersAtTime(address(staking), Timestamp.wrap(block.timestamp)).length; + uint256 initialCanonicalCount = gse.getAttestersAtTime(bonusInstanceAddress, Timestamp.wrap(block.timestamp)).length; + uint256 initialInstanceCount = gse.getAttestersAtTime(address(staking), Timestamp.wrap(block.timestamp)).length; for (uint256 i = 1; i <= _numValidators; i++) { bool onCanonical = i % 2 == 0; _help_deposit(address(uint160(i * 2)), address(uint160(i * 2 + 1)), onCanonical); } - assertEq( - staking.getActiveAttesterCount(), - initialActiveAttesterCount, - "depositors should not be active" - ); - assertEq( - stakingAsset.balanceOf(address(staking)), - _numValidators * ACTIVATION_THRESHOLD, - "invalid balance" - ); + assertEq(staking.getActiveAttesterCount(), initialActiveAttesterCount, "depositors should not be active"); + assertEq(stakingAsset.balanceOf(address(staking)), _numValidators * ACTIVATION_THRESHOLD, "invalid balance"); uint256 flushSize = staking.getEntryQueueFlushSize(); assertEq(flushSize, _expectedFlushSize, "invalid flush size"); @@ -275,9 +243,7 @@ contract FlushEntryQueueTest is StakingBase { assertEq(stakingAsset.allowance(address(staking), address(gse)), 0, "invalid allowance"); assertEq( - staking.getActiveAttesterCount(), - initialActiveAttesterCount + depositCount, - "invalid active attester count" + staking.getActiveAttesterCount(), initialActiveAttesterCount + depositCount, "invalid active attester count" ); assertEq( @@ -319,26 +285,17 @@ contract FlushEntryQueueTest is StakingBase { address[] memory attestersOnCanonical = gse.getAttestersAtTime(bonusInstanceAddress, Timestamp.wrap(block.timestamp)); assertEq( - attestersOnCanonical.length, - initialCanonicalCount + onCanonicalCount, - "invalid number of attesters on canonical" + attestersOnCanonical.length, initialCanonicalCount + onCanonicalCount, "invalid number of attesters on canonical" ); for (uint256 i = 0; i < onCanonicalCount; i++) { assertEq( - attestersOnCanonical[i + initialCanonicalCount], - address(uint160((i + 1) * 4)), - "invalid canonical attester" + attestersOnCanonical[i + initialCanonicalCount], address(uint160((i + 1) * 4)), "invalid canonical attester" ); } // Check the instance set has the proper validators - address[] memory attestersOnInstance = - gse.getAttestersAtTime(address(staking), Timestamp.wrap(block.timestamp)); - assertEq( - attestersOnInstance.length, - initialInstanceCount + depositCount, - "invalid number of attesters on instance" - ); + address[] memory attestersOnInstance = gse.getAttestersAtTime(address(staking), Timestamp.wrap(block.timestamp)); + assertEq(attestersOnInstance.length, initialInstanceCount + depositCount, "invalid number of attesters on instance"); emit log_named_uint("depositCount", depositCount); emit log_named_uint("onCanonicalCount", onCanonicalCount); emit log_named_uint("initialInstanceCount", initialInstanceCount); diff --git a/l1-contracts/test/staking/initiateWithdraw.t.sol b/l1-contracts/test/staking/initiateWithdraw.t.sol index 29d5773aa3de..9e210e7941a1 100644 --- a/l1-contracts/test/staking/initiateWithdraw.t.sol +++ b/l1-contracts/test/staking/initiateWithdraw.t.sol @@ -3,9 +3,7 @@ pragma solidity >=0.8.27; import {StakingBase} from "./base.t.sol"; import {Errors} from "@aztec/core/libraries/Errors.sol"; -import { - Timestamp, Status, AttesterView, Exit, IStakingCore -} from "@aztec/core/interfaces/IStaking.sol"; +import {Timestamp, Status, AttesterView, Exit, IStakingCore} from "@aztec/core/interfaces/IStaking.sol"; contract InitiateWithdrawTest is StakingBase { function test_WhenAttesterIsNotRegistered() external { @@ -28,9 +26,7 @@ contract InitiateWithdrawTest is StakingBase { vm.assume(_caller != WITHDRAWER); - vm.expectRevert( - abi.encodeWithSelector(Errors.Staking__NotWithdrawer.selector, WITHDRAWER, _caller) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Staking__NotWithdrawer.selector, WITHDRAWER, _caller)); vm.prank(_caller); staking.initiateWithdraw(ATTESTER, RECIPIENT); } @@ -39,11 +35,7 @@ contract InitiateWithdrawTest is StakingBase { _; } - function test_GivenAttesterIsNotValidatingOrLiving() - external - whenAttesterIsRegistered - whenCallerIsTheWithdrawer - { + function test_GivenAttesterIsNotValidatingOrLiving() external whenAttesterIsRegistered whenCallerIsTheWithdrawer { // it revert assertTrue(staking.getStatus(address(1)) == Status.NONE); diff --git a/l1-contracts/test/staking/move.t.sol b/l1-contracts/test/staking/move.t.sol index 730086efaeb4..0b4ebf8a24ee 100644 --- a/l1-contracts/test/staking/move.t.sol +++ b/l1-contracts/test/staking/move.t.sol @@ -30,8 +30,8 @@ contract MoveTest is StakingBase { StakingQueueConfig memory stakingQueueConfig = TestConstants.getStakingQueueConfig(); stakingQueueConfig.normalFlushSizeMin = n; - RollupBuilder builder = new RollupBuilder(address(this)).setSlashingQuorum(1) - .setSlashingRoundSize(1).setStakingQueueConfig(stakingQueueConfig); + RollupBuilder builder = new RollupBuilder(address(this)).setSlashingQuorum(1).setSlashingRoundSize(1) + .setStakingQueueConfig(stakingQueueConfig); builder.deploy(); registry = builder.getConfig().registry; @@ -55,10 +55,11 @@ contract MoveTest is StakingBase { StakingQueueConfig memory stakingQueueConfig = TestConstants.getStakingQueueConfig(); stakingQueueConfig.normalFlushSizeMin = n; - RollupBuilder builder = new RollupBuilder(address(this)).setGSE(gse).setTestERC20(stakingAsset) - .setRegistry(registry).setMakeCanonical(false).setMakeGovernance(false).setUpdateOwnerships( - false - ).setStakingQueueConfig(stakingQueueConfig).deploy(); + RollupBuilder builder = new RollupBuilder(address(this)).setGSE(gse).setTestERC20(stakingAsset).setRegistry( + registry + ).setMakeCanonical(false).setMakeGovernance(false).setUpdateOwnerships(false).setStakingQueueConfig( + stakingQueueConfig + ).deploy(); IInstance oldRollup = IInstance(address(staking)); IInstance newRollup = IInstance(address(builder.getConfig().rollup)); @@ -78,8 +79,7 @@ contract MoveTest is StakingBase { oldRollup.flushEntryQueue(); Epoch epoch = Epoch.wrap(5); - Timestamp ts = - newRollup.getTimestampForSlot(Slot.wrap(Epoch.unwrap(epoch) * newRollup.getEpochDuration())); + Timestamp ts = newRollup.getTimestampForSlot(Slot.wrap(Epoch.unwrap(epoch) * newRollup.getEpochDuration())); assertEq(gse.getAttesterCountAtTime(address(oldRollup), Timestamp.wrap(block.timestamp)), n); assertEq(gse.getAttesterCountAtTime(address(newRollup), Timestamp.wrap(block.timestamp)), 0); @@ -89,9 +89,7 @@ contract MoveTest is StakingBase { vm.expectRevert( abi.encodeWithSelector( - Errors.ValidatorSelection__InsufficientCommitteeSize.selector, - 0, - newRollup.getTargetCommitteeSize() + Errors.ValidatorSelection__InsufficientCommitteeSize.selector, 0, newRollup.getTargetCommitteeSize() ) ); newRollup.getEpochCommittee(epoch); @@ -103,9 +101,7 @@ contract MoveTest is StakingBase { // Look at the data "right now", see that half have been moved assertEq(gse.getAttesterCountAtTime(address(oldRollup), Timestamp.wrap(block.timestamp)), n / 2); - assertEq( - gse.getAttesterCountAtTime(address(newRollup), Timestamp.wrap(block.timestamp)), n - n / 2 - ); + assertEq(gse.getAttesterCountAtTime(address(newRollup), Timestamp.wrap(block.timestamp)), n - n / 2); // When we look at the committee for that epoch, the setup "depends" on how far in the past we "lock-in" // the committee. So for good measure, we will first check at the epoch and then add another 100. @@ -113,9 +109,7 @@ contract MoveTest is StakingBase { assertEq(oldRollup.getEpochCommittee(epoch).length, oldRollup.getTargetCommitteeSize()); vm.expectRevert( abi.encodeWithSelector( - Errors.ValidatorSelection__InsufficientCommitteeSize.selector, - 0, - newRollup.getTargetCommitteeSize() + Errors.ValidatorSelection__InsufficientCommitteeSize.selector, 0, newRollup.getTargetCommitteeSize() ) ); newRollup.getEpochCommittee(epoch); @@ -159,9 +153,7 @@ contract MoveTest is StakingBase { attesterView = newRollup.getAttesterView(attesterToExit); assertEq(attesterView.exit.exists, true); assertEq(attesterView.exit.isRecipient, true); - assertEq( - attesterView.exit.exitableAt, Timestamp.wrap(block.timestamp) + newRollup.getExitDelay() - ); + assertEq(attesterView.exit.exitableAt, Timestamp.wrap(block.timestamp) + newRollup.getExitDelay()); assertEq(attesterView.exit.recipientOrWithdrawer, RECIPIENT); assertTrue(attesterView.status == Status.EXITING); diff --git a/l1-contracts/test/staking/setSlasher.t.sol b/l1-contracts/test/staking/setSlasher.t.sol index 501312e5bd80..df31cd65768e 100644 --- a/l1-contracts/test/staking/setSlasher.t.sol +++ b/l1-contracts/test/staking/setSlasher.t.sol @@ -3,9 +3,7 @@ pragma solidity >=0.8.27; import {StakingBase} from "./base.t.sol"; import {Errors} from "@aztec/core/libraries/Errors.sol"; -import { - IStakingCore, Status, AttesterView, Exit, Timestamp -} from "@aztec/core/interfaces/IStaking.sol"; +import {IStakingCore, Status, AttesterView, Exit, Timestamp} from "@aztec/core/interfaces/IStaking.sol"; import {Ownable} from "@oz/access/Ownable.sol"; contract SetslasherTest is StakingBase { diff --git a/l1-contracts/test/staking/slash.t.sol b/l1-contracts/test/staking/slash.t.sol index 7250e71e4e05..1c511e50fe8d 100644 --- a/l1-contracts/test/staking/slash.t.sol +++ b/l1-contracts/test/staking/slash.t.sol @@ -3,9 +3,7 @@ pragma solidity >=0.8.27; import {StakingBase} from "./base.t.sol"; import {Errors} from "@aztec/core/libraries/Errors.sol"; -import { - IStakingCore, Status, AttesterView, Exit, Timestamp -} from "@aztec/core/interfaces/IStaking.sol"; +import {IStakingCore, Status, AttesterView, Exit, Timestamp} from "@aztec/core/interfaces/IStaking.sol"; contract SlashTest is StakingBase { uint256 internal slashingAmount = 1; @@ -21,9 +19,7 @@ contract SlashTest is StakingBase { staking.flushEntryQueue(); // it reverts - vm.expectRevert( - abi.encodeWithSelector(Errors.Staking__NotSlasher.selector, SLASHER, address(this)) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.Staking__NotSlasher.selector, SLASHER, address(this))); staking.slash(ATTESTER, 1); } @@ -55,12 +51,7 @@ contract SlashTest is StakingBase { _; } - function test_GivenTimeIsAfterUnlock() - external - whenCallerIsTheSlasher - whenAttesterIsRegistered - whenAttesterIsExiting - { + function test_GivenTimeIsAfterUnlock() external whenCallerIsTheSlasher whenAttesterIsRegistered whenAttesterIsExiting { // it reverts Exit memory exit = staking.getExit(ATTESTER); @@ -106,9 +97,7 @@ contract SlashTest is StakingBase { bool isAlive = i != 2; // Prepare the status and state AttesterView memory attesterView = staking.getAttesterView(ATTESTER); - assertTrue( - attesterView.status == (isAlive ? Status.VALIDATING : Status.ZOMBIE), "Invalid status" - ); + assertTrue(attesterView.status == (isAlive ? Status.VALIDATING : Status.ZOMBIE), "Invalid status"); assertEq(staking.getActiveAttesterCount(), isAlive ? 1 : 0, "Invalid active attester count"); uint256 balance = isAlive ? attesterView.effectiveBalance : attesterView.exit.amount; @@ -123,9 +112,7 @@ contract SlashTest is StakingBase { if (i == 0) { // The first round, we are still active, not slashing enough yet! - assertEq( - attesterView.effectiveBalance, balance - slashingAmount, "Invalid effective balance" - ); + assertEq(attesterView.effectiveBalance, balance - slashingAmount, "Invalid effective balance"); assertEq(attesterView.exit.amount, 0, "Invalid exit amount"); assertTrue(attesterView.status == Status.VALIDATING, "Invalid status after slash"); assertEq(staking.getActiveAttesterCount(), 1, "Invalid active attester count"); diff --git a/l1-contracts/test/staking/updateStakingQueueConfig.t.sol b/l1-contracts/test/staking/updateStakingQueueConfig.t.sol index 8500d055d129..aa1fcc0c1c7e 100644 --- a/l1-contracts/test/staking/updateStakingQueueConfig.t.sol +++ b/l1-contracts/test/staking/updateStakingQueueConfig.t.sol @@ -13,9 +13,7 @@ import {IStakingCore} from "@aztec/core/interfaces/IStaking.sol"; import {Ownable} from "@oz/access/Ownable.sol"; contract UpdateStakingQueueConfigTest is StakingBase { - function test_GivenCallerIsNotTheRollupOwner(address _caller, StakingQueueConfig memory _config) - external - { + function test_GivenCallerIsNotTheRollupOwner(address _caller, StakingQueueConfig memory _config) external { // it reverts Rollup rollup = Rollup(address(registry.getCanonicalRollup())); vm.assume(rollup.owner() != _caller); @@ -29,16 +27,12 @@ contract UpdateStakingQueueConfigTest is StakingBase { _; } - function test_GivenCallerIsRollupOwner(StakingQueueConfig memory _config) - external - givenCallerIsTheRollupOwner - { + function test_GivenCallerIsRollupOwner(StakingQueueConfig memory _config) external givenCallerIsTheRollupOwner { // it updates the staking queue config // it emits a {StakingQueueConfigUpdated} event // Update the config to have sane values that can be compressed - _config.bootstrapValidatorSetSize = - bound(_config.bootstrapValidatorSetSize, 0, type(uint64).max); + _config.bootstrapValidatorSetSize = bound(_config.bootstrapValidatorSetSize, 0, type(uint64).max); _config.bootstrapFlushSize = bound(_config.bootstrapFlushSize, 0, type(uint64).max); _config.normalFlushSizeMin = bound(_config.normalFlushSizeMin, 0, type(uint64).max); _config.normalFlushSizeQuotient = bound(_config.normalFlushSizeQuotient, 0, type(uint64).max); diff --git a/l1-contracts/test/staking_asset_handler/addValidator.t.sol b/l1-contracts/test/staking_asset_handler/addValidator.t.sol index f6b3d12c3753..834c0efeaec3 100644 --- a/l1-contracts/test/staking_asset_handler/addValidator.t.sol +++ b/l1-contracts/test/staking_asset_handler/addValidator.t.sol @@ -71,11 +71,7 @@ contract AddValidatorTest is StakingAssetHandlerBase { uint256 revertTimestamp = stakingAssetHandler.lastMintTimestamp() + mintInterval; - vm.expectRevert( - abi.encodeWithSelector( - IStakingAssetHandler.ValidatorQuotaFilledUntil.selector, revertTimestamp - ) - ); + vm.expectRevert(abi.encodeWithSelector(IStakingAssetHandler.ValidatorQuotaFilledUntil.selector, revertTimestamp)); vm.prank(_caller); stakingAssetHandler.addValidator(_attester, validMerkleProof, realProof); } @@ -118,9 +114,7 @@ contract AddValidatorTest is StakingAssetHandlerBase { // Set the lastMintTimestamp to be the same as the current timestamp such that our proof will be valid // block.timestamp is overriden to be the time of the proof in ZKPassportBase constructor - stdstore.target(address(stakingAssetHandler)).sig("lastMintTimestamp()").checked_write( - block.timestamp - ); + stdstore.target(address(stakingAssetHandler)).sig("lastMintTimestamp()").checked_write(block.timestamp); _; } @@ -138,10 +132,7 @@ contract AddValidatorTest is StakingAssetHandlerBase { // it deposits into the rollup // it emits a {ValidatorAdded} event - vm.assume( - _attester != address(0) && _caller != address(this) && _attester != address(this) - && _caller != unhinged - ); + vm.assume(_attester != address(0) && _caller != address(this) && _attester != address(this) && _caller != unhinged); uint256 revertTimestamp = stakingAssetHandler.lastMintTimestamp() + mintInterval; vm.warp(revertTimestamp); @@ -167,10 +158,7 @@ contract AddValidatorTest is StakingAssetHandlerBase { givenPassportProofIsValid { // it reverts - vm.assume( - _attester != address(0) && _caller != address(this) && _attester != address(this) - && _caller != unhinged - ); + vm.assume(_attester != address(0) && _caller != address(this) && _attester != address(this) && _caller != unhinged); stakingAssetHandler.setDepositsPerMint(10); @@ -184,9 +172,7 @@ contract AddValidatorTest is StakingAssetHandlerBase { uint256 uniqueIdentifierLocation = _proof.publicInputs.length - 1; vm.expectRevert( - abi.encodeWithSelector( - IStakingAssetHandler.SybilDetected.selector, _proof.publicInputs[uniqueIdentifierLocation] - ) + abi.encodeWithSelector(IStakingAssetHandler.SybilDetected.selector, _proof.publicInputs[uniqueIdentifierLocation]) ); // Call from somebody else vm.prank(_caller); @@ -203,8 +189,7 @@ contract AddValidatorTest is StakingAssetHandlerBase { _proof.devMode = true; vm.assume( - _attester != address(0) && _caller != address(this) && _attester != address(this) - && _attester != unhinged + _attester != address(0) && _caller != address(this) && _attester != address(this) && _attester != unhinged ); uint256 revertTimestamp = block.timestamp + mintInterval; vm.warp(revertTimestamp); @@ -246,10 +231,7 @@ contract AddValidatorTest is StakingAssetHandlerBase { // it does not revert even though flushEntryQueue reverts // it shows the validator was added to the queue - vm.assume( - _attester != address(0) && _caller != address(this) && _attester != address(this) - && _caller != unhinged - ); + vm.assume(_attester != address(0) && _caller != address(this) && _attester != address(this) && _caller != unhinged); uint256 revertTimestamp = stakingAssetHandler.lastMintTimestamp() + mintInterval; vm.warp(revertTimestamp); diff --git a/l1-contracts/test/staking_asset_handler/bind.t.sol b/l1-contracts/test/staking_asset_handler/bind.t.sol index 12e5630c3a62..795cd32bddb2 100644 --- a/l1-contracts/test/staking_asset_handler/bind.t.sol +++ b/l1-contracts/test/staking_asset_handler/bind.t.sol @@ -33,9 +33,7 @@ contract BindTest is StakingAssetHandlerBase { vm.assume(_attester != BOUND_ADDRESS && _attester != address(this)); vm.expectRevert( - abi.encodeWithSelector( - IStakingAssetHandler.ProofNotBoundToAddress.selector, BOUND_ADDRESS, _attester - ) + abi.encodeWithSelector(IStakingAssetHandler.ProofNotBoundToAddress.selector, BOUND_ADDRESS, _attester) ); vm.prank(_attester); stakingAssetHandler.addValidator(_attester, validMerkleProof, realProof); diff --git a/l1-contracts/test/staking_asset_handler/merkle/merkle_tree_getters.sol b/l1-contracts/test/staking_asset_handler/merkle/merkle_tree_getters.sol index 9d278a25c593..ec51622b7691 100644 --- a/l1-contracts/test/staking_asset_handler/merkle/merkle_tree_getters.sol +++ b/l1-contracts/test/staking_asset_handler/merkle/merkle_tree_getters.sol @@ -37,10 +37,7 @@ contract MerkleTreeGetters is Test { return proof; } - function getAddressAndProof(uint256 index) - internal - returns (address addr, bytes32[] memory proof) - { + function getAddressAndProof(uint256 index) internal returns (address addr, bytes32[] memory proof) { string[] memory inputs = new string[](3); inputs[0] = "node"; inputs[1] = "test/staking_asset_handler/merkle/get-address-and-proof.js"; diff --git a/l1-contracts/test/staking_asset_handler/merkleCheck.t.sol b/l1-contracts/test/staking_asset_handler/merkleCheck.t.sol index 4302e62389d7..20ccd37ab60d 100644 --- a/l1-contracts/test/staking_asset_handler/merkleCheck.t.sol +++ b/l1-contracts/test/staking_asset_handler/merkleCheck.t.sol @@ -11,8 +11,7 @@ import {MerkleTreeGetters} from "./merkle/merkle_tree_getters.sol"; contract MerkleCheck is StakingAssetHandlerBase, MerkleTreeGetters { // Generate with `node ./test/staking_asset_handler/merkle/get-root.js` - bytes32 internal constant ROOT = - 0x9c6c9656a7180da61f979b48cb6f9f4d8d91d7f602e172bf8555a6a2d7aef935; + bytes32 internal constant ROOT = 0x9c6c9656a7180da61f979b48cb6f9f4d8d91d7f602e172bf8555a6a2d7aef935; function setUp() public override { super.setUp(); diff --git a/l1-contracts/test/staking_asset_handler/reenterExitedValidator.t.sol b/l1-contracts/test/staking_asset_handler/reenterExitedValidator.t.sol index 287f8e69d03c..a9a4d334bbbf 100644 --- a/l1-contracts/test/staking_asset_handler/reenterExitedValidator.t.sol +++ b/l1-contracts/test/staking_asset_handler/reenterExitedValidator.t.sol @@ -10,24 +10,16 @@ import {IStakingCore} from "@aztec/core/interfaces/IStaking.sol"; // solhint-disable ordering contract ReenterExitedValidatorTest is StakingAssetHandlerBase { - function test_WhenAttesterHasNOTProvidedAValidDeposit(address _attester, address _proposer) - external - { + function test_WhenAttesterHasNOTProvidedAValidDeposit(address _attester, address _proposer) external { // it reverts vm.assume(_attester != address(0) && _proposer != address(0)); - vm.expectRevert( - abi.encodeWithSelector(IStakingAssetHandler.AttesterDoesNotExist.selector, _attester) - ); + vm.expectRevert(abi.encodeWithSelector(IStakingAssetHandler.AttesterDoesNotExist.selector, _attester)); stakingAssetHandler.reenterExitedValidator(_attester); } - function test_WhenAttesterHasProvidedAValidDeposit( - address _caller, - address _attester, - address _proposer - ) external { + function test_WhenAttesterHasProvidedAValidDeposit(address _caller, address _attester, address _proposer) external { // it succeeds // it emits a {ValidatorAdded} event diff --git a/l1-contracts/test/staking_asset_handler/setDepositsPerMint.t.sol b/l1-contracts/test/staking_asset_handler/setDepositsPerMint.t.sol index 124407566e10..7bfe39e861a2 100644 --- a/l1-contracts/test/staking_asset_handler/setDepositsPerMint.t.sol +++ b/l1-contracts/test/staking_asset_handler/setDepositsPerMint.t.sol @@ -37,10 +37,7 @@ contract SetDepositsPerMintTest is StakingAssetHandlerBase { stakingAssetHandler.setDepositsPerMint(0); } - function test_WhenDepositsPerMintIsNot0(uint256 _newDepositsPerMint) - external - whenCallerOfSetDepositsPerMintIsOwner - { + function test_WhenDepositsPerMintIsNot0(uint256 _newDepositsPerMint) external whenCallerOfSetDepositsPerMintIsOwner { _newDepositsPerMint = bound(_newDepositsPerMint, 1, 1000); // it sets the deposits per mint // it emits a {DepositsPerMintUpdated} event @@ -80,9 +77,7 @@ contract SetDepositsPerMintTest is StakingAssetHandlerBase { // it reverts when adding one more validator uint256 lastMintTimestamp = stakingAssetHandler.lastMintTimestamp(); vm.expectRevert( - abi.encodeWithSelector( - IStakingAssetHandler.ValidatorQuotaFilledUntil.selector, lastMintTimestamp + mintInterval - ) + abi.encodeWithSelector(IStakingAssetHandler.ValidatorQuotaFilledUntil.selector, lastMintTimestamp + mintInterval) ); vm.prank(caller); stakingAssetHandler.addValidator(address(0xbeefdeef), validMerkleProof, realProof); diff --git a/l1-contracts/test/staking_asset_handler/setMintInterval.t.sol b/l1-contracts/test/staking_asset_handler/setMintInterval.t.sol index 5a05e7299c4f..572e8e1f6850 100644 --- a/l1-contracts/test/staking_asset_handler/setMintInterval.t.sol +++ b/l1-contracts/test/staking_asset_handler/setMintInterval.t.sol @@ -27,10 +27,7 @@ contract SetMintIntervalTest is StakingAssetHandlerBase { assertEq(stakingAssetHandler.mintInterval(), _newMintInterval); } - function test_WhenOwnerTriesToMintBeforeTheNewIntervalHasPassed( - uint256 _newMintInterval, - uint256 _jump - ) external { + function test_WhenOwnerTriesToMintBeforeTheNewIntervalHasPassed(uint256 _newMintInterval, uint256 _jump) external { // the "last mint timestamp" is 0 before the first mint _newMintInterval = bound(_newMintInterval, mintInterval + 1, 1e18); @@ -44,8 +41,7 @@ contract SetMintIntervalTest is StakingAssetHandlerBase { // it reverts vm.expectRevert( abi.encodeWithSelector( - IStakingAssetHandler.ValidatorQuotaFilledUntil.selector, - lastMintTimestamp + _newMintInterval + IStakingAssetHandler.ValidatorQuotaFilledUntil.selector, lastMintTimestamp + _newMintInterval ) ); vm.prank(address(0xbeefdeef)); diff --git a/l1-contracts/test/staking_asset_handler/setWithdrawer.t.sol b/l1-contracts/test/staking_asset_handler/setWithdrawer.t.sol index 0acde6afc783..bba3eb3c40e9 100644 --- a/l1-contracts/test/staking_asset_handler/setWithdrawer.t.sol +++ b/l1-contracts/test/staking_asset_handler/setWithdrawer.t.sol @@ -33,9 +33,7 @@ contract SetWithdrawerTest is StakingAssetHandlerBase { assertEq(stakingAssetHandler.withdrawer(), _newWithdrawer); } - function test_WhenOwnerCallsAddValidatorAfterSettingTheWithdrawer(address _newWithdrawer) - external - { + function test_WhenOwnerCallsAddValidatorAfterSettingTheWithdrawer(address _newWithdrawer) external { // it uses the new withdrawer vm.assume(_newWithdrawer != address(0)); diff --git a/l1-contracts/test/staking_asset_handler/zkpassport/ZKPassportBase.sol b/l1-contracts/test/staking_asset_handler/zkpassport/ZKPassportBase.sol index e8a51086428f..083a7d79d1c9 100644 --- a/l1-contracts/test/staking_asset_handler/zkpassport/ZKPassportBase.sol +++ b/l1-contracts/test/staking_asset_handler/zkpassport/ZKPassportBase.sol @@ -22,8 +22,7 @@ contract ZKPassportBase is Test { // Path to the proof file - using files directly in project root // Fixtures copied from within the zk passport subrepo - bytes32 constant VKEY_HASH = - bytes32(uint256(0x2ab349ef31f5d516da820a3f55f93c53f9c899b0b991c93fc341199cc1e3b36c)); + bytes32 constant VKEY_HASH = bytes32(uint256(0x2ab349ef31f5d516da820a3f55f93c53f9c899b0b991c93fc341199cc1e3b36c)); bytes32 constant CERTIFICATE_REGISTRY_ROOT = bytes32(uint256(0x130b5775fe59204b0490bdfcdd02bd7cc2bbf5fe3f3fee34cee13c3a3f9b7bbb)); @@ -53,7 +52,7 @@ contract ZKPassportBase is Test { // ( When the proof was made ) // Set the timestamp to 2025-07-16 20:26:48 UTC - vm.warp(1752697608); + vm.warp(1_752_697_608); realProof = makeValidProof(); fakeProof = makeFakeProof(); @@ -156,11 +155,7 @@ contract ZKPassportBase is Test { /** * @dev Helper function to slice a string */ - function slice(string memory s, uint256 start, uint256 length) - internal - pure - returns (string memory) - { + function slice(string memory s, uint256 start, uint256 length) internal pure returns (string memory) { bytes memory b = bytes(s); require(start + length <= b.length, "String slice out of bounds"); diff --git a/l1-contracts/test/validator-selection/Sampling.t.sol b/l1-contracts/test/validator-selection/Sampling.t.sol index fa322ceda8b2..e159f084b996 100644 --- a/l1-contracts/test/validator-selection/Sampling.t.sol +++ b/l1-contracts/test/validator-selection/Sampling.t.sol @@ -18,11 +18,7 @@ contract Sampler { return SampleLib.computeCommittee(_committeeSize, _indexCount, _seed); } - function computeSampleIndex(uint256 _index, uint256 _indexCount, uint256 _seed) - public - pure - returns (uint256) - { + function computeSampleIndex(uint256 _index, uint256 _indexCount, uint256 _seed) public pure returns (uint256) { return SampleLib.computeSampleIndex(_index, _indexCount, _seed); } } @@ -82,11 +78,7 @@ contract SamplingTest is Test { uint256 totalSize = bound(_indexCount, 1, type(uint256).max - 1); uint256 committeeSize = bound(_committeeSize, totalSize + 1, type(uint256).max); - vm.expectRevert( - abi.encodeWithSelector( - Errors.SampleLib__SampleLargerThanIndex.selector, committeeSize, totalSize - ) - ); + vm.expectRevert(abi.encodeWithSelector(Errors.SampleLib__SampleLargerThanIndex.selector, committeeSize, totalSize)); sampler.computeCommittee(committeeSize, totalSize, 0); } diff --git a/l1-contracts/test/validator-selection/ValidatorSelection.t.sol b/l1-contracts/test/validator-selection/ValidatorSelection.t.sol index 6aaa32be45c7..449f4fc714d1 100644 --- a/l1-contracts/test/validator-selection/ValidatorSelection.t.sol +++ b/l1-contracts/test/validator-selection/ValidatorSelection.t.sol @@ -20,12 +20,7 @@ import {MessageHashUtils} from "@oz/utils/cryptography/MessageHashUtils.sol"; import {SafeCast} from "@oz/utils/math/SafeCast.sol"; import {ProposedHeaderLib} from "@aztec/core/libraries/rollup/ProposedHeaderLib.sol"; -import { - ProposeArgs, - OracleInput, - ProposeLib, - ProposePayload -} from "@aztec/core/libraries/rollup/ProposeLib.sol"; +import {ProposeArgs, OracleInput, ProposeLib, ProposePayload} from "@aztec/core/libraries/rollup/ProposeLib.sol"; import {DecoderBase} from "../base/DecoderBase.sol"; @@ -38,9 +33,7 @@ import {ValidatorSelectionTestBase} from "./ValidatorSelectionBase.sol"; import {NaiveMerkle} from "../merkle/Naive.sol"; -import { - BlockLog, PublicInputArgs, SubmitEpochRootProofArgs -} from "@aztec/core/interfaces/IRollup.sol"; +import {BlockLog, PublicInputArgs, SubmitEpochRootProofArgs} from "@aztec/core/interfaces/IRollup.sol"; // solhint-disable comprehensive-interface @@ -108,10 +101,7 @@ contract ValidatorSelectionTest is ValidatorSelectionTestBase { function testProposerForNonSetupEpoch(uint8 _epochsToJump) public setup(4, 4) progressEpochs(2) { Epoch pre = rollup.getCurrentEpoch(); - vm.warp( - block.timestamp - + uint256(_epochsToJump) * rollup.getEpochDuration() * rollup.getSlotDuration() - ); + vm.warp(block.timestamp + uint256(_epochsToJump) * rollup.getEpochDuration() * rollup.getSlotDuration()); Epoch post = rollup.getCurrentEpoch(); assertEq(pre + Epoch.wrap(_epochsToJump), post, "Invalid epoch"); @@ -130,17 +120,13 @@ contract ValidatorSelectionTest is ValidatorSelectionTestBase { function testCommitteeForNonSetupEpoch(uint8 _epochsToJump) public setup(4, 4) progressEpochs(2) { Epoch pre = rollup.getCurrentEpoch(); - vm.warp( - block.timestamp - + uint256(_epochsToJump) * rollup.getEpochDuration() * rollup.getSlotDuration() - ); + vm.warp(block.timestamp + uint256(_epochsToJump) * rollup.getEpochDuration() * rollup.getSlotDuration()); Epoch post = rollup.getCurrentEpoch(); uint256 validatorSetSize = rollup.getAttesters().length; uint256 targetCommitteeSize = rollup.getTargetCommitteeSize(); - uint256 expectedSize = - validatorSetSize > targetCommitteeSize ? targetCommitteeSize : validatorSetSize; + uint256 expectedSize = validatorSetSize > targetCommitteeSize ? targetCommitteeSize : validatorSetSize; address[] memory preCommittee = rollup.getEpochCommittee(pre); address[] memory postCommittee = rollup.getEpochCommittee(post); @@ -185,28 +171,23 @@ contract ValidatorSelectionTest is ValidatorSelectionTestBase { // NOTE: this must be run with --isolate as transient storage gets thrashed when working out the proposer. // This also changes the committee which is calculated within each call. - // TODO(https://github.com/AztecProtocol/aztec-packages/issues/14275): clear out transient storage used by the sample lib - we cannot afford to have a malicious proposer + // TODO(https://github.com/AztecProtocol/aztec-packages/issues/14275): clear out transient storage used by the sample + // lib - we cannot afford to have a malicious proposer // change the committee committment to something unpredictable. /// forge-config: default.isolate = true - function testValidatorSetLargerThanCommittee(bool _insufficientSigs) - public - setup(100, 48) - progressEpochs(2) - { + function testValidatorSetLargerThanCommittee(bool _insufficientSigs) public setup(100, 48) progressEpochs(2) { uint256 committeeSize = rollup.getTargetCommitteeSize(); uint256 signatureCount = committeeSize * 2 / 3 + (_insufficientSigs ? 0 : 1); assertGt(rollup.getAttesters().length, committeeSize, "Not enough validators"); - ProposeTestData memory ree = - _testBlock("mixed_block_1", NO_REVERT, signatureCount, committeeSize, NO_FLAGS); + ProposeTestData memory ree = _testBlock("mixed_block_1", NO_REVERT, signatureCount, committeeSize, NO_FLAGS); assertEq(ree.committee.length, rollup.getTargetCommitteeSize(), "Invalid committee size"); // Test we can invalidate the block by insufficient attestations if sigs were insufficient _invalidateByAttestationCount( - ree, - _insufficientSigs ? NO_REVERT : Errors.ValidatorSelection__InsufficientAttestations.selector + ree, _insufficientSigs ? NO_REVERT : Errors.ValidatorSelection__InsufficientAttestations.selector ); } @@ -221,11 +202,7 @@ contract ValidatorSelectionTest is ValidatorSelectionTestBase { uint256 blockNumber = rollup.getPendingBlockNumber(); _proveBlocks( - "mixed_block_", - blockNumber - 1, - blockNumber, - SignatureLib.packAttestations(ree2.attestations), - NO_REVERT + "mixed_block_", blockNumber - 1, blockNumber, SignatureLib.packAttestations(ree2.attestations), NO_REVERT ); } @@ -363,11 +340,7 @@ contract ValidatorSelectionTest is ValidatorSelectionTestBase { _invalidateByAttestationSig(ree, 0, NO_REVERT); _testBlock("mixed_block_1", NO_REVERT, 3, 4, NO_FLAGS); - assertEq( - rollup.getPendingBlockNumber(), - initialBlockNumber + 1, - "Failed to propose block after invalidate" - ); + assertEq(rollup.getPendingBlockNumber(), initialBlockNumber + 1, "Failed to propose block after invalidate"); } function testCannotProposeIfAllValidatorsHaveMoved() public setup(4, 4) progressEpochs(2) { @@ -415,11 +388,7 @@ contract ValidatorSelectionTest is ValidatorSelectionTestBase { ); } - function _invalidateByAttestationSig( - ProposeTestData memory ree, - uint256 _index, - bytes4 _revertData - ) internal { + function _invalidateByAttestationSig(ProposeTestData memory ree, uint256 _index, bytes4 _revertData) internal { _invalidateByAttestationSig(ree, _index, _revertData, rollup.getPendingBlockNumber()); } @@ -464,8 +433,7 @@ contract ValidatorSelectionTest is ValidatorSelectionTestBase { ree.sender = ree.proposer; { - uint128 manaBaseFee = - SafeCast.toUint128(rollup.getManaBaseFeeAt(Timestamp.wrap(block.timestamp), true)); + uint128 manaBaseFee = SafeCast.toUint128(rollup.getManaBaseFeeAt(Timestamp.wrap(block.timestamp), true)); bytes32 inHash = inbox.getRoot(full.block.blockNumber); header.contentCommitment.inHash = inHash; header.gasFees.feePerL2Gas = manaBaseFee; @@ -550,10 +518,7 @@ contract ValidatorSelectionTest is ValidatorSelectionTestBase { vm.prank(ree.sender); rollup.propose( - ree.proposeArgs, - SignatureLib.packAttestations(ree.attestations), - ree.signers, - full.block.blobCommitments + ree.proposeArgs, SignatureLib.packAttestations(ree.attestations), ree.signers, full.block.blobCommitments ); if (_revertData != NO_REVERT) { @@ -605,9 +570,7 @@ contract ValidatorSelectionTest is ValidatorSelectionTestBase { uint256 version = rollup.getVersion(); for (uint256 i = 0; i < _contents.length; i++) { vm.prank(_sender); - inbox.sendL2Message( - DataStructures.L2Actor({actor: _recipient, version: version}), _contents[i], bytes32(0) - ); + inbox.sendL2Message(DataStructures.L2Actor({actor: _recipient, version: version}), _contents[i], bytes32(0)); } } @@ -631,11 +594,8 @@ contract ValidatorSelectionTest is ValidatorSelectionTestBase { BlockLog memory parentBlockLog = rollup.getBlock(startBlockNumber - 1); address prover = address(0xcafe); - PublicInputArgs memory args = PublicInputArgs({ - previousArchive: parentBlockLog.archive, - endArchive: endFull.block.archive, - proverId: prover - }); + PublicInputArgs memory args = + PublicInputArgs({previousArchive: parentBlockLog.archive, endArchive: endFull.block.archive, proverId: prover}); bytes32[] memory fees = new bytes32[](Constants.AZTEC_MAX_EPOCH_DURATION * 2); @@ -656,11 +616,7 @@ contract ValidatorSelectionTest is ValidatorSelectionTestBase { ); } - function _createAttestation(address _signer, bytes32 _digest) - internal - view - returns (CommitteeAttestation memory) - { + function _createAttestation(address _signer, bytes32 _digest) internal view returns (CommitteeAttestation memory) { uint256 privateKey = attesterPrivateKeys[_signer]; bytes32 digest = _digest.toEthSignedMessageHash(); @@ -670,11 +626,7 @@ contract ValidatorSelectionTest is ValidatorSelectionTestBase { return CommitteeAttestation({addr: _signer, signature: signature}); } - function _createEmptyAttestation(address _signer) - internal - pure - returns (CommitteeAttestation memory) - { + function _createEmptyAttestation(address _signer) internal pure returns (CommitteeAttestation memory) { Signature memory emptySignature = Signature({v: 0, r: 0, s: 0}); return CommitteeAttestation({addr: _signer, signature: emptySignature}); } diff --git a/l1-contracts/test/validator-selection/ValidatorSelectionBase.sol b/l1-contracts/test/validator-selection/ValidatorSelectionBase.sol index 76c02d757bce..b11904d78cb8 100644 --- a/l1-contracts/test/validator-selection/ValidatorSelectionBase.sol +++ b/l1-contracts/test/validator-selection/ValidatorSelectionBase.sol @@ -73,8 +73,8 @@ contract ValidatorSelectionTestBase is DecoderBase { { DecoderBase.Full memory full = load(_name); Slot slotNumber = full.block.header.slotNumber; - uint256 initialTime = Timestamp.unwrap(full.block.header.timestamp) - - Slot.unwrap(slotNumber) * TestConstants.AZTEC_SLOT_DURATION; + uint256 initialTime = + Timestamp.unwrap(full.block.header.timestamp) - Slot.unwrap(slotNumber) * TestConstants.AZTEC_SLOT_DURATION; timeCheater = new TimeCheater( address(rollup), @@ -95,9 +95,9 @@ contract ValidatorSelectionTestBase is DecoderBase { StakingQueueConfig memory stakingQueueConfig = TestConstants.getStakingQueueConfig(); stakingQueueConfig.normalFlushSizeMin = Math.max(_validatorCount, 1); - RollupBuilder builder = new RollupBuilder(address(this)).setStakingQueueConfig( - stakingQueueConfig - ).setValidators(initialValidators).setTargetCommitteeSize(_targetCommitteeSize); + RollupBuilder builder = new RollupBuilder(address(this)).setStakingQueueConfig(stakingQueueConfig).setValidators( + initialValidators + ).setTargetCommitteeSize(_targetCommitteeSize); builder.deploy(); rollup = builder.getConfig().rollup; diff --git a/l1-contracts/test/validator-selection/setupEpoch.t.sol b/l1-contracts/test/validator-selection/setupEpoch.t.sol index 71b39a27ecd4..4c513016afaa 100644 --- a/l1-contracts/test/validator-selection/setupEpoch.t.sol +++ b/l1-contracts/test/validator-selection/setupEpoch.t.sol @@ -22,9 +22,7 @@ contract SetupEpochTest is ValidatorSelectionTestBase { vm.expectRevert( abi.encodeWithSelector( - Errors.ValidatorSelection__InsufficientCommitteeSize.selector, - 0, - rollup.getTargetCommitteeSize() + Errors.ValidatorSelection__InsufficientCommitteeSize.selector, 0, rollup.getTargetCommitteeSize() ) ); rollup.setupEpoch(); @@ -34,16 +32,14 @@ contract SetupEpochTest is ValidatorSelectionTestBase { assertEq(sampleSeed, type(uint224).max, "Sample seed for epoch0 should be max in genesis state"); // Read the sample seed for epoch 1 through the rollup contract - Timestamp epoch1Timestamp = Timestamp.wrap( - block.timestamp + TestConstants.AZTEC_EPOCH_DURATION * TestConstants.AZTEC_SLOT_DURATION - ); + Timestamp epoch1Timestamp = + Timestamp.wrap(block.timestamp + TestConstants.AZTEC_EPOCH_DURATION * TestConstants.AZTEC_SLOT_DURATION); uint256 epoch1Seed = IValidatorSelection(address(rollup)).getSampleSeedAt(epoch1Timestamp); assertEq(epoch1Seed, type(uint224).max, "Sample seed for epoch1 should be max in genesis state"); // Read the sample seed for epoch 2 through the rollup contract - Timestamp epoch2Timestamp = Timestamp.wrap( - block.timestamp + 2 * TestConstants.AZTEC_EPOCH_DURATION * TestConstants.AZTEC_SLOT_DURATION - ); + Timestamp epoch2Timestamp = + Timestamp.wrap(block.timestamp + 2 * TestConstants.AZTEC_EPOCH_DURATION * TestConstants.AZTEC_SLOT_DURATION); assertTrue( IValidatorSelection(address(rollup)).getSampleSeedAt(epoch2Timestamp) == type(uint224).max, "Epoch 2 seed should be max" @@ -62,9 +58,7 @@ contract SetupEpochTest is ValidatorSelectionTestBase { // Call setupEpoch again, from the current epoch it should not change the sample seed vm.expectRevert( abi.encodeWithSelector( - Errors.ValidatorSelection__InsufficientCommitteeSize.selector, - 0, - rollup.getTargetCommitteeSize() + Errors.ValidatorSelection__InsufficientCommitteeSize.selector, 0, rollup.getTargetCommitteeSize() ) ); rollup.setupEpoch(); @@ -76,9 +70,8 @@ contract SetupEpochTest is ValidatorSelectionTestBase { ); // Seed for the epoch 4 should be set - Timestamp epoch4Timestamp = Timestamp.wrap( - block.timestamp + 2 * TestConstants.AZTEC_EPOCH_DURATION * TestConstants.AZTEC_SLOT_DURATION - ); + Timestamp epoch4Timestamp = + Timestamp.wrap(block.timestamp + 2 * TestConstants.AZTEC_EPOCH_DURATION * TestConstants.AZTEC_SLOT_DURATION); assertTrue( IValidatorSelection(address(rollup)).getSampleSeedAt(epoch4Timestamp) == type(uint224).max, "Epoch 4 seed should be max" @@ -89,32 +82,25 @@ contract SetupEpochTest is ValidatorSelectionTestBase { _; } - function test_WhenTheSampleSeedHasBeenSet() - external - setup(4, 4) - whenTheRollupHasTheTargetCommitteeSize - { + function test_WhenTheSampleSeedHasBeenSet() external setup(4, 4) whenTheRollupHasTheTargetCommitteeSize { // it should not change the sample seed // it should be calculate the same committee when looking into the past // it should not change the commitee even when validators are added or removed // it should not change the next seed - Timestamp epoch2Timestamp = Timestamp.wrap( - block.timestamp + 2 * TestConstants.AZTEC_EPOCH_DURATION * TestConstants.AZTEC_SLOT_DURATION - ); + Timestamp epoch2Timestamp = + Timestamp.wrap(block.timestamp + 2 * TestConstants.AZTEC_EPOCH_DURATION * TestConstants.AZTEC_SLOT_DURATION); vm.warp(Timestamp.unwrap(epoch2Timestamp)); rollup.setupEpoch(); // Check that the initial epoch seed is set - uint256 initialEpochSeed = - IValidatorSelection(address(rollup)).getSampleSeedAt(Timestamp.wrap(block.timestamp)); + uint256 initialEpochSeed = IValidatorSelection(address(rollup)).getSampleSeedAt(Timestamp.wrap(block.timestamp)); assertEq(initialEpochSeed, type(uint224).max, "Sample seed for initial epoch should be max"); // Get the initial committee - address[] memory initialCommittee = - IValidatorSelection(address(rollup)).getCurrentEpochCommittee(); + address[] memory initialCommittee = IValidatorSelection(address(rollup)).getCurrentEpochCommittee(); // When setup epoch is called, nothing should change rollup.setupEpoch(); @@ -123,23 +109,17 @@ contract SetupEpochTest is ValidatorSelectionTestBase { assertEq(initialEpochSeedAfterSetup, initialEpochSeed, "Sample seed should not change"); // Check that the committee is the same - address[] memory committeeAfterRepeatedSetup = - IValidatorSelection(address(rollup)).getCurrentEpochCommittee(); - assertEq( - committeeAfterRepeatedSetup.length, - initialCommittee.length, - "Committee should have the same length" - ); + address[] memory committeeAfterRepeatedSetup = IValidatorSelection(address(rollup)).getCurrentEpochCommittee(); + assertEq(committeeAfterRepeatedSetup.length, initialCommittee.length, "Committee should have the same length"); assertEq(committeeAfterRepeatedSetup, initialCommittee, "Committee should be the same"); // Overwrite the flushable epoch to 0 to force our ability to add more validators this epoch // Now reset the next flushable epoch to 0 - stdstore.enable_packed_slots().target(address(rollup)).sig( - IStaking.getNextFlushableEpoch.selector - ).depth(0).checked_write(uint256(0)); + stdstore.enable_packed_slots().target(address(rollup)).sig(IStaking.getNextFlushableEpoch.selector).depth(0) + .checked_write(uint256(0)); // Add a couple of extra validators during this epoch, the sampled validator set should not change - addNumberOfValidators(420420, 2); + addNumberOfValidators(420_420, 2); // Sample the validator set for the current epoch address[] memory committeeAfterAddingExtraValidators = @@ -165,9 +145,8 @@ contract SetupEpochTest is ValidatorSelectionTestBase { setup(50, 48) whenTheRollupHasTheTargetCommitteeSize { - Timestamp epoch2Timestamp = Timestamp.wrap( - block.timestamp + 2 * TestConstants.AZTEC_EPOCH_DURATION * TestConstants.AZTEC_SLOT_DURATION - ); + Timestamp epoch2Timestamp = + Timestamp.wrap(block.timestamp + 2 * TestConstants.AZTEC_EPOCH_DURATION * TestConstants.AZTEC_SLOT_DURATION); vm.warp(Timestamp.unwrap(epoch2Timestamp)); @@ -177,54 +156,41 @@ contract SetupEpochTest is ValidatorSelectionTestBase { // Check that the sample seed has been set for two epochs next uint256 nextEpochTimestamp = block.timestamp + 2 * TestConstants.AZTEC_EPOCH_DURATION * TestConstants.AZTEC_SLOT_DURATION; - uint256 nextEpochSeed = - IValidatorSelection(address(rollup)).getSampleSeedAt(Timestamp.wrap(nextEpochTimestamp)); + uint256 nextEpochSeed = IValidatorSelection(address(rollup)).getSampleSeedAt(Timestamp.wrap(nextEpochTimestamp)); assertGt(nextEpochSeed, 0, "Sample seed should be set for the next epoch"); // Jump into the future, looking back, the returned sample seed should be the same for the next range of epochs uint256 savedTimestamp = block.timestamp; - vm.warp( - savedTimestamp + 2 * (TestConstants.AZTEC_EPOCH_DURATION * TestConstants.AZTEC_SLOT_DURATION) - ); + vm.warp(savedTimestamp + 2 * (TestConstants.AZTEC_EPOCH_DURATION * TestConstants.AZTEC_SLOT_DURATION)); uint256 sampleSeedAfterJump = IValidatorSelection(address(rollup)).getCurrentSampleSeed(); assertEq(sampleSeedAfterJump, nextEpochSeed, "Sample seed should be the same"); // Add some validators - addNumberOfValidators(420422, 2); + addNumberOfValidators(420_422, 2); // Jump further into the future - vm.warp( - savedTimestamp + 4 * (TestConstants.AZTEC_EPOCH_DURATION * TestConstants.AZTEC_SLOT_DURATION) - ); + vm.warp(savedTimestamp + 4 * (TestConstants.AZTEC_EPOCH_DURATION * TestConstants.AZTEC_SLOT_DURATION)); // Check that the sample seed has not changed assertEq( - IValidatorSelection(address(rollup)).getCurrentSampleSeed(), - nextEpochSeed, - "Sample seed should not change" + IValidatorSelection(address(rollup)).getCurrentSampleSeed(), nextEpochSeed, "Sample seed should not change" ); // Call setupEpoch, the sample seed should not change rollup.setupEpoch(); assertEq( - IValidatorSelection(address(rollup)).getCurrentSampleSeed(), - nextEpochSeed, - "Sample seed should not change" + IValidatorSelection(address(rollup)).getCurrentSampleSeed(), nextEpochSeed, "Sample seed should not change" ); // The sample seed for the next epoch should have changed uint256 nextEpochTimestamp2 = block.timestamp + 2 * TestConstants.AZTEC_EPOCH_DURATION * TestConstants.AZTEC_SLOT_DURATION; - uint256 nextEpochSeed2 = - IValidatorSelection(address(rollup)).getSampleSeedAt(Timestamp.wrap(nextEpochTimestamp2)); + uint256 nextEpochSeed2 = IValidatorSelection(address(rollup)).getSampleSeedAt(Timestamp.wrap(nextEpochTimestamp2)); assertNotEq(nextEpochSeed2, nextEpochSeed, "Sample seed for the next epoch should have changed"); } - function test_WhenNewSampleSeedsAreAdded() - external - whenItHasBeenALongTimeSinceTheLastSampleSeedWasSet - { + function test_WhenNewSampleSeedsAreAdded() external whenItHasBeenALongTimeSinceTheLastSampleSeedWasSet { // it should continue to use the snapshotted sample seed // it should calculate the same committee } diff --git a/l1-contracts/test/validator-selection/setupSampleSeed.t.sol b/l1-contracts/test/validator-selection/setupSampleSeed.t.sol index e4fb91e599cb..9c5dbb9d410c 100644 --- a/l1-contracts/test/validator-selection/setupSampleSeed.t.sol +++ b/l1-contracts/test/validator-selection/setupSampleSeed.t.sol @@ -13,15 +13,12 @@ contract SetupSampleSeedTest is ValidatorSelectionTestBase { // Check that the epoch is not set _epochToTest = uint16(bound(_epochToTest, 2, type(uint16).max)); - uint256 timejump = - _epochToTest * TestConstants.AZTEC_EPOCH_DURATION * TestConstants.AZTEC_SLOT_DURATION; - uint256 originalSampleSeed = - rollup.getSampleSeedAt(Timestamp.wrap(block.timestamp + timejump + 1)); + uint256 timejump = _epochToTest * TestConstants.AZTEC_EPOCH_DURATION * TestConstants.AZTEC_SLOT_DURATION; + uint256 originalSampleSeed = rollup.getSampleSeedAt(Timestamp.wrap(block.timestamp + timejump + 1)); // Jump to just before the epoch we are testing vm.warp( - block.timestamp - + (_epochToTest - 1) * TestConstants.AZTEC_EPOCH_DURATION * TestConstants.AZTEC_SLOT_DURATION + block.timestamp + (_epochToTest - 1) * TestConstants.AZTEC_EPOCH_DURATION * TestConstants.AZTEC_SLOT_DURATION ); rollup.setupSeedSnapshotForNextEpoch();