diff --git a/docs/docs/the_aztec_network/guides/run_nodes/cli_reference.md b/docs/docs/the_aztec_network/guides/run_nodes/cli_reference.md index 7bb8b6776961..3a8188c37824 100644 --- a/docs/docs/the_aztec_network/guides/run_nodes/cli_reference.md +++ b/docs/docs/the_aztec_network/guides/run_nodes/cli_reference.md @@ -381,10 +381,10 @@ If two subsystems can contain the same configuration option, only one needs to b --archiver.aztecProofSubmissionEpochs (default: 1) ($AZTEC_PROOF_SUBMISSION_EPOCHS) The number of epochs after an epoch ends that proofs are still accepted. - --archiver.depositAmount (default: 100000000000000000000) ($AZTEC_DEPOSIT_AMOUNT) + --archiver.activationThreshold (default: 100000000000000000000) ($AZTEC_ACTIVATION_THRESHOLD) The deposit amount for a validator - --archiver.minimumStake (default: 50000000000000000000) ($AZTEC_MINIMUM_STAKE) + --archiver.ejectionThreshold (default: 50000000000000000000) ($AZTEC_EJECTION_THRESHOLD) The minimum stake for a validator. --archiver.slashingQuorum (default: 101) ($AZTEC_SLASHING_QUORUM) diff --git a/l1-contracts/script/InternalGov.s.sol b/l1-contracts/script/InternalGov.s.sol index 2dc192faa2e2..c3ba84241fd4 100644 --- a/l1-contracts/script/InternalGov.s.sol +++ b/l1-contracts/script/InternalGov.s.sol @@ -84,7 +84,9 @@ contract GovScript is Test { emit log_named_uint( "\tNumber of attestors ", IStaking(address(rollup)).getActiveAttesterCount() ); - emit log_named_decimal_uint("\tMinimum stake", IStaking(address(rollup)).getDepositAmount(), 18); + emit log_named_decimal_uint( + "\tMinimum stake", IStaking(address(rollup)).getActivationThreshold(), 18 + ); emit log_named_address("# Governance", address(governance)); Configuration memory config = governance.getConfiguration(); diff --git a/l1-contracts/src/core/Rollup.sol b/l1-contracts/src/core/Rollup.sol index 4675969dbd9d..96a87d150685 100644 --- a/l1-contracts/src/core/Rollup.sol +++ b/l1-contracts/src/core/Rollup.sol @@ -224,12 +224,12 @@ contract Rollup is IStaking, IValidatorSelection, IRollup, RollupCore { return StakingLib.getStorage().stakingAsset; } - function getMinimumStake() external view override(IStaking) returns (uint256) { - return StakingLib.getStorage().gse.MINIMUM_STAKE(); + function getEjectionThreshold() external view override(IStaking) returns (uint256) { + return StakingLib.getStorage().gse.EJECTION_THRESHOLD(); } - function getDepositAmount() external view override(IStaking) returns (uint256) { - return StakingLib.getStorage().gse.DEPOSIT_AMOUNT(); + function getActivationThreshold() external view override(IStaking) returns (uint256) { + return StakingLib.getStorage().gse.ACTIVATION_THRESHOLD(); } function getExitDelay() external view override(IStaking) returns (Timestamp) { diff --git a/l1-contracts/src/core/interfaces/IStaking.sol b/l1-contracts/src/core/interfaces/IStaking.sol index e9d27eb48049..2cedfadd8582 100644 --- a/l1-contracts/src/core/interfaces/IStaking.sol +++ b/l1-contracts/src/core/interfaces/IStaking.sol @@ -37,8 +37,8 @@ interface IStaking is IStakingCore { function getAttesterAtIndex(uint256 _index) external view returns (address); function getSlasher() external view returns (address); function getStakingAsset() external view returns (IERC20); - function getDepositAmount() external view returns (uint256); - function getMinimumStake() external view returns (uint256); + function getActivationThreshold() external view returns (uint256); + function getEjectionThreshold() external view returns (uint256); function getExitDelay() external view returns (Timestamp); function getGSE() external view returns (GSE); function getAttesterView(address _attester) external view returns (AttesterView memory); diff --git a/l1-contracts/src/core/libraries/rollup/StakingLib.sol b/l1-contracts/src/core/libraries/rollup/StakingLib.sol index b612f572da84..a2c3f9da9f6a 100644 --- a/l1-contracts/src/core/libraries/rollup/StakingLib.sol +++ b/l1-contracts/src/core/libraries/rollup/StakingLib.sol @@ -150,7 +150,7 @@ library StakingLib { delete store.exits[_attester]; - store.gse.finaliseHelper(exit.withdrawalId); + store.gse.finaliseWithdraw(exit.withdrawalId); store.stakingAsset.transfer(exit.recipientOrWithdrawer, exit.amount); emit IStakingCore.WithdrawFinalised(_attester, exit.recipientOrWithdrawer, exit.amount); @@ -225,7 +225,7 @@ library StakingLib { StakingStorage storage store = getStorage(); // We don't allow deposits, if we are currently exiting. require(!store.exits[_attester].exists, Errors.Staking__AlreadyExiting(_attester)); - uint256 amount = store.gse.DEPOSIT_AMOUNT(); + uint256 amount = store.gse.ACTIVATION_THRESHOLD(); store.stakingAsset.transferFrom(msg.sender, address(this), amount); store.entryQueue.enqueue(_attester, _withdrawer, _moveWithLatestRollup); @@ -243,7 +243,7 @@ library StakingLib { store.nextFlushableEpoch <= currentEpoch, Errors.Staking__QueueAlreadyFlushed(currentEpoch) ); store.nextFlushableEpoch = currentEpoch + Epoch.wrap(1); - uint256 amount = store.gse.DEPOSIT_AMOUNT(); + uint256 amount = store.gse.ACTIVATION_THRESHOLD(); uint256 queueLength = store.entryQueue.length(); uint256 numToDequeue = Math.min(_maxAddableValidators, queueLength); diff --git a/l1-contracts/src/governance/GSE.sol b/l1-contracts/src/governance/GSE.sol index e495929bebeb..f4badd4c3635 100644 --- a/l1-contracts/src/governance/GSE.sol +++ b/l1-contracts/src/governance/GSE.sol @@ -9,7 +9,10 @@ import { AddressSnapshotLib, SnapshottedAddressSet } from "@aztec/governance/libraries/AddressSnapshotLib.sol"; -import {DelegationLib, DelegationData} from "@aztec/governance/libraries/DelegationLib.sol"; +import { + DepositDelegationLib, + DepositAndDelegationAccounting +} from "@aztec/governance/libraries/DepositDelegationLib.sol"; import {Errors} from "@aztec/governance/libraries/Errors.sol"; import {ProposalLib} from "@aztec/governance/libraries/ProposalLib.sol"; import {Timestamp} from "@aztec/shared/libraries/TimeMath.sol"; @@ -18,14 +21,16 @@ import {IERC20} from "@oz/token/ERC20/IERC20.sol"; import {SafeCast} from "@oz/utils/math/SafeCast.sol"; import {Checkpoints} from "@oz/utils/structs/Checkpoints.sol"; +// Struct to store configuration of an attester (block producer) +// Keep track of the actor who can initiate and control withdraws for the attester. struct AttesterConfig { address withdrawer; } -// Struct to track the attesters on a particular rollup instance throughout time, -// along with each attester's current config. +// Struct to track the attesters (block producers) on a particular rollup instance +// throughout time, along with each attester's current config. // Finally a flag to track if the instance exists. -struct InstanceStaking { +struct InstanceAttesterRegistry { SnapshottedAddressSet attesters; mapping(address attester => AttesterConfig config) configOf; bool exists; @@ -41,7 +46,7 @@ interface IGSECore { function delegate(address _instance, address _attester, address _delegatee) external; function vote(uint256 _proposalId, uint256 _amount, bool _support) external; function voteWithBonus(uint256 _proposalId, uint256 _amount, bool _support) external; - function finaliseHelper(uint256 _withdrawalId) external; + function finaliseWithdraw(uint256 _withdrawalId) external; function proposeWithLock(IPayload _proposal, address _to) external returns (uint256); function isRegistered(address _instance, address _attester) external view returns (bool); @@ -96,16 +101,16 @@ interface IGSE is IGSECore { /** * @title GSECore * @author Aztec Labs - * @notice The core Governance Staking Escrow contract that handles the staking of attesters on rollup instances. + * @notice The core Governance Staking Escrow contract that handles the deposits of attesters on rollup instances. * It is responsible for: * - depositing/withdrawing attesters on rollup instances * - providing rollup instances with historical views of their attesters * - allowing depositors to delegate their voting power * - allowing delegatees to vote at governance - * - maintaining a set of "bonus" attesters which are always staked on the latest rollup + * - maintaining a set of "bonus" attesters which are always deposited on behalf of the latest rollup * * NB: The "bonus" attesters are thus automatically "moved along" whenever the latest rollup changes. - * That is, at the point of the rollup getting added, the bonus stake is immediately available. + * That is, at the point of the rollup getting added, the bonus is immediately available. * This allows the latest rollup to start with a set of attesters, rather than requiring them to exit * the old rollup and deposit in the new one. * @@ -126,13 +131,13 @@ contract GSECore is IGSECore, Ownable { using SafeCast for uint256; using SafeCast for uint224; using Checkpoints for Checkpoints.Trace224; - using DelegationLib for DelegationData; + using DepositDelegationLib for DepositAndDelegationAccounting; using ProposalLib for Proposal; /** * Create a special "bonus" address for use by the latest rollup. * - * As far as terminology, the GSE tracks staking and voting/delegation data for "instances", + * As far as terminology, the GSE tracks deposits and voting/delegation data for "instances", * and an "instance" is either the address of a "true" rollup contract which was added via `addRollup`, * or (ONLY IN THIS CONTRACT) this special "bonus" address, which has its own accounting. * @@ -177,14 +182,20 @@ contract GSECore is IGSECore, Ownable { address public constant BONUS_INSTANCE_ADDRESS = address(uint160(uint256(keccak256("bonus-instance")))); - uint256 public immutable DEPOSIT_AMOUNT; - uint256 public immutable MINIMUM_STAKE; - IERC20 public immutable STAKING_ASSET; + // The amount of ASSET needed to add an attester to the set + uint256 public immutable ACTIVATION_THRESHOLD; + + // The amount of ASSET needed to keep an attester in the set, if the attester balance fall below this threshold + // 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. + IERC20 public immutable ASSET; // The GSE's history of rollups. Checkpoints.Trace224 internal rollups; - // Mapping from instance address to its historical staking information. - mapping(address instanceAddress => InstanceStaking instance) internal instances; + // Mapping from instance address to its historical attester information. + mapping(address instanceAddress => InstanceAttesterRegistry instance) internal instances; /** * Contains state for: @@ -198,7 +209,7 @@ contract GSECore is IGSECore, Ownable { * proposal ID => { power used } * } */ - DelegationData internal delegation; + DepositAndDelegationAccounting internal delegation; Governance internal governance; /** @@ -211,24 +222,26 @@ contract GSECore is IGSECore, Ownable { /** * @param __owner - The owner of the GSE. - * @param _stakingAsset - The asset that is used for staking. - * @param _depositAmount - The amount of staking asset required to deposit an attester on the rollup. - * @param _minimumStake - The minimum amount of staking asset required to be in the set to be considered an attester. - * Presently, as the rollup instance does not allow for partial withdrawals, the only way for - * a staked amount to reduce is to either withdraw the entire amount or be slashed. - * If the balance falls below the minimum stake, the attester is removed from the set. + * Initially a deployer to allow adding an initial rollup, then handed over to governance. + * @param _asset - The asset used in governance and for sybil resistance + * @param _activationThreshold - The amount of asset required to deposit an attester on the rollup. + * @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 _stakingAsset, uint256 _depositAmount, uint256 _minimumStake) - Ownable(__owner) - { - STAKING_ASSET = _stakingAsset; - DEPOSIT_AMOUNT = _depositAmount; - MINIMUM_STAKE = _minimumStake; + constructor( + address __owner, + IERC20 _asset, + uint256 _activationThreshold, + uint256 _ejectionThreshold + ) Ownable(__owner) { + ASSET = _asset; + ACTIVATION_THRESHOLD = _activationThreshold; + EJECTION_THRESHOLD = _ejectionThreshold; instances[BONUS_INSTANCE_ADDRESS].exists = true; } function setGovernance(Governance _governance) external override(IGSECore) onlyOwner { - // Once again desparate times calls for desparate measures. + // Once again desperate times calls for desperate measures. require(address(governance) == address(0), Errors.GSE__GovernanceAlreadySet()); governance = _governance; } @@ -253,7 +266,7 @@ contract GSECore is IGSECore, Ownable { * * @dev msg.sender must be a registered rollup. * - * @dev Transfers STAKING_ASSET from msg.sender to the GSE, and then into Governance. + * @dev Transfers ASSET from msg.sender to the GSE, and then into Governance. * * @dev if _moveWithLatestRollup is true, then msg.sender must be the latest rollup. * @@ -318,13 +331,13 @@ contract GSECore is IGSECore, Ownable { instances[recipientInstance].configOf[_attester] = AttesterConfig({withdrawer: _withdrawer}); delegation.delegate(recipientInstance, _attester, recipientInstance); - delegation.increaseBalance(recipientInstance, _attester, DEPOSIT_AMOUNT); + delegation.increaseBalance(recipientInstance, _attester, ACTIVATION_THRESHOLD); - STAKING_ASSET.transferFrom(msg.sender, address(this), DEPOSIT_AMOUNT); + ASSET.transferFrom(msg.sender, address(this), ACTIVATION_THRESHOLD); Governance gov = getGovernance(); - STAKING_ASSET.approve(address(gov), DEPOSIT_AMOUNT); - gov.deposit(address(this), DEPOSIT_AMOUNT); + ASSET.approve(address(gov), ACTIVATION_THRESHOLD); + gov.deposit(address(this), ACTIVATION_THRESHOLD); emit Deposit(recipientInstance, _attester, _withdrawer); } @@ -357,43 +370,40 @@ contract GSECore is IGSECore, Ownable { // We need to figure out where the attester is effectively located // we start by looking at the instance that is withdrawing the attester address withdrawingInstance = msg.sender; - InstanceStaking storage instanceStaking = instances[msg.sender]; - bool foundAttester = instanceStaking.attesters.contains(_attester); + InstanceAttesterRegistry storage attesterRegistry = instances[msg.sender]; + bool foundAttester = attesterRegistry.attesters.contains(_attester); - // If we haven't found the attester in the rollup instance staking, - // 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) ) { withdrawingInstance = BONUS_INSTANCE_ADDRESS; - instanceStaking = instances[BONUS_INSTANCE_ADDRESS]; + attesterRegistry = instances[BONUS_INSTANCE_ADDRESS]; foundAttester = true; } require(foundAttester, Errors.GSE__NothingToExit(_attester)); uint256 balance = delegation.getBalanceOf(withdrawingInstance, _attester); - require(balance >= _amount, Errors.GSE__InsufficientStake(balance, _amount)); + require(balance >= _amount, Errors.GSE__InsufficientBalance(balance, _amount)); // First assume we are only withdrawing the amount specified. uint256 amountWithdrawn = _amount; - // If the balance after withdrawal is less than the minimum stake, + // If the balance after withdrawal is less than the ejection threshold, // we will remove the attester from the instance. - bool isRemoved = balance - _amount < MINIMUM_STAKE; + bool isRemoved = balance - _amount < EJECTION_THRESHOLD; // Note that the current implementation of the rollup does not allow for partial withdrawals, // via `initiateWithdraw`, so a "normal" withdrawal will always remove the attester from the instance. // However, if the attester is slashed, we might just reduce the balance. if (isRemoved) { - require(instanceStaking.attesters.remove(_attester), Errors.GSE__FailedToRemove(_attester)); - delete instanceStaking.configOf[_attester]; + require(attesterRegistry.attesters.remove(_attester), Errors.GSE__FailedToRemove(_attester)); + delete attesterRegistry.configOf[_attester]; amountWithdrawn = balance; - // Update the delegatee to address(0) when removing - // This reduces the voting power of the attester's delegatee by the amount withdrawn - // by moving it to address(0). - delegation.delegate(withdrawingInstance, _attester, address(0)); + // When removing the user, remove the delegating as well. + delegation.undelegate(withdrawingInstance, _attester); } // Decrease the balance of the attester in the instance. @@ -419,7 +429,7 @@ contract GSECore is IGSECore, Ownable { * * @param _withdrawalId - The id of the withdrawal */ - function finaliseHelper(uint256 _withdrawalId) external override(IGSECore) { + function finaliseWithdraw(uint256 _withdrawalId) external override(IGSECore) { Governance gov = getGovernance(); if (!gov.getWithdrawal(_withdrawalId).claimed) { gov.finaliseWithdraw(_withdrawalId); @@ -432,7 +442,7 @@ contract GSECore is IGSECore, Ownable { * @dev It is required to expose this on the GSE, since it is assumed that only the GSE can hold * power in Governance (see the comment at the top of Governance.sol). * - * @dev Transfers governance's configured `lockAmount` of STAKING_ASSET from msg.sender to the GSE, + * @dev Transfers governance's configured `lockAmount` of ASSET from msg.sender to the GSE, * and then into Governance. * * @dev Immediately creates a withdrawal from Governance for the `lockAmount`. @@ -452,8 +462,8 @@ contract GSECore is IGSECore, Ownable { Governance gov = getGovernance(); uint256 amount = gov.getConfiguration().proposeConfig.lockAmount; - STAKING_ASSET.transferFrom(msg.sender, address(this), amount); - STAKING_ASSET.approve(address(gov), amount); + ASSET.transferFrom(msg.sender, address(this), amount); + ASSET.approve(address(gov), amount); gov.deposit(address(this), amount); @@ -464,7 +474,10 @@ contract GSECore is IGSECore, Ownable { * @notice Delegates the voting power of `_attester` at `_instance` to `_delegatee` * * Only callable by the `withdrawer` for the given `_attester` at the given - * `_instance`. + * `_instance`. This is to ensure that the depositor in poor mans delegation; + * listing another entity as the `attester`, still controls his voting power, + * even if someone else is running the node. Separately, it makes it simpler + * to use cold-storage for more impactful actions. * * @dev The delegatee may use this voting power to vote on proposals in Governance. * @@ -473,9 +486,9 @@ contract GSECore is IGSECore, Ownable { * See `Governance.getProposalState` for more details. * * @param _instance - The address of the rollup instance (or bonus instance address) - * - to which the `_attester` stake is pledged. + * to which the `_attester` deposit is pledged. * @param _attester - The address of the attester to delegate on behalf of - * @param _delegatee - The degelegatee that should receive the power + * @param _delegatee - The delegatee that should receive the power */ function delegate(address _instance, address _attester, address _delegatee) external @@ -590,11 +603,14 @@ contract GSE is IGSE, GSECore { using SafeCast for uint256; using SafeCast for uint224; using Checkpoints for Checkpoints.Trace224; - using DelegationLib for DelegationData; + using DepositDelegationLib for DepositAndDelegationAccounting; - constructor(address __owner, IERC20 _stakingAsset, uint256 _depositAmount, uint256 _minimumStake) - GSECore(__owner, _stakingAsset, _depositAmount, _minimumStake) - {} + constructor( + address __owner, + IERC20 _asset, + uint256 _activationThreshold, + uint256 _ejectionThreshold + ) GSECore(__owner, _asset, _activationThreshold, _ejectionThreshold) {} function getConfig(address _instance, address _attester) external @@ -602,14 +618,14 @@ contract GSE is IGSE, GSECore { override(IGSE) returns (AttesterConfig memory) { - (InstanceStaking storage instanceStaking, bool attesterExists,) = + (InstanceAttesterRegistry storage attesterRegistry, bool attesterExists,) = _getInstanceStoreWithAttester(_instance, _attester); if (!attesterExists) { return AttesterConfig({withdrawer: address(0)}); } - return instanceStaking.configOf[_attester]; + return attesterRegistry.configOf[_attester]; } function getWithdrawer(address _instance, address _attester) @@ -618,15 +634,15 @@ contract GSE is IGSE, GSECore { override(IGSE) returns (address withdrawer, bool attesterExists, address instanceAddress) { - InstanceStaking storage instanceStaking; - (instanceStaking, attesterExists, instanceAddress) = + InstanceAttesterRegistry storage attesterRegistry; + (attesterRegistry, attesterExists, instanceAddress) = _getInstanceStoreWithAttester(_instance, _attester); if (!attesterExists) { return (address(0), false, address(0)); } - return (instanceStaking.configOf[_attester].withdrawer, true, instanceAddress); + return (attesterRegistry.configOf[_attester].withdrawer, true, instanceAddress); } function balanceOf(address _instance, address _attester) @@ -697,7 +713,6 @@ contract GSE is IGSE, GSECore { override(IGSE) returns (address[] memory) { - // @todo Throw me in jail for this crime against humanity uint256 count = getAttesterCountAtTime(_instance, _timestamp); uint256[] memory indices = new uint256[](count); for (uint256 i = 0; i < count; i++) { @@ -763,7 +778,7 @@ contract GSE is IGSE, GSECore { override(IGSE) returns (uint256) { - InstanceStaking storage store = instances[_instance]; + InstanceAttesterRegistry storage store = instances[_instance]; uint32 timestamp = Timestamp.unwrap(_timestamp).toUint32(); uint256 count = store.attesters.lengthAtTimestamp(timestamp); @@ -795,8 +810,8 @@ contract GSE is IGSE, GSECore { // Note: This function could get called where _instance is the bonus instance. // This is okay, because we know that in this case, `isLatestRollup` will be false. // So we won't double count. - InstanceStaking storage instanceStore = instances[_instance]; - InstanceStaking storage bonusStore = instances[BONUS_INSTANCE_ADDRESS]; + InstanceAttesterRegistry storage instanceStore = instances[_instance]; + InstanceAttesterRegistry storage bonusStore = instances[BONUS_INSTANCE_ADDRESS]; bool isLatestRollup = getLatestRollupAt(_timestamp) == _instance; uint32 ts = Timestamp.unwrap(_timestamp).toUint32(); @@ -825,13 +840,12 @@ contract GSE is IGSE, GSECore { return attesters; } - // @todo I think we can clean this up more, don't think we need the instances being passed around nearly as much now. function _getInstanceStoreWithAttester(address _instance, address _attester) internal view - returns (InstanceStaking storage, bool, address) + returns (InstanceAttesterRegistry storage, bool, address) { - InstanceStaking storage store = instances[_instance]; + InstanceAttesterRegistry storage store = instances[_instance]; bool attesterExists = store.attesters.contains(_attester); address instanceAddress = _instance; diff --git a/l1-contracts/src/governance/Governance.sol b/l1-contracts/src/governance/Governance.sol index 10010e18c457..e704e070fdd0 100644 --- a/l1-contracts/src/governance/Governance.sol +++ b/l1-contracts/src/governance/Governance.sol @@ -11,10 +11,12 @@ 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 {ConfigurationLib} from "@aztec/governance/libraries/ConfigurationLib.sol"; import {Errors} from "@aztec/governance/libraries/Errors.sol"; import {ProposalLib, VoteTabulationReturn} from "@aztec/governance/libraries/ProposalLib.sol"; -import {User, UserLib} from "@aztec/governance/libraries/UserLib.sol"; import {Timestamp} from "@aztec/shared/libraries/TimeMath.sol"; import {IERC20} from "@oz/token/ERC20/IERC20.sol"; import {SafeERC20} from "@oz/token/ERC20/utils/SafeERC20.sol"; @@ -124,7 +126,7 @@ struct DepositControl { contract Governance is IGovernance { using SafeERC20 for IERC20; using ProposalLib for Proposal; - using UserLib for User; + using CheckpointedUintLib for Checkpoints.Trace224; using ConfigurationLib for Configuration; IERC20 public immutable ASSET; @@ -164,7 +166,7 @@ contract Governance is IGovernance { * * `users` is only updated during `deposit`, `initiateWithdraw`, and `proposeWithLock`. */ - mapping(address userAddress => User user) internal users; + mapping(address userAddress => Checkpoints.Trace224 user) internal users; /** * @dev Withdrawals that have been initiated. @@ -186,7 +188,7 @@ contract Governance is IGovernance { * * `total` is only updated during `deposit`, `initiateWithdraw`, and `proposeWithLock`. */ - User internal total; + Checkpoints.Trace224 internal total; /** * @dev The count of proposals that have been made. @@ -456,7 +458,7 @@ contract Governance is IGovernance { require(state == ProposalState.Active, Errors.Governance__ProposalNotActive()); // Compute the power at the time where we became active - uint256 userPower = users[msg.sender].powerAt(proposals[_proposalId].pendingThrough()); + uint256 userPower = users[msg.sender].valueAt(proposals[_proposalId].pendingThrough()); Ballot storage userBallot = ballots[_proposalId][msg.sender]; @@ -559,9 +561,9 @@ contract Governance is IGovernance { returns (uint256) { if (_ts == Timestamp.wrap(block.timestamp)) { - return users[_owner].powerNow(); + return users[_owner].valueNow(); } - return users[_owner].powerAt(_ts); + return users[_owner].valueAt(_ts); } /** @@ -578,9 +580,9 @@ contract Governance is IGovernance { */ function totalPowerAt(Timestamp _ts) external view override(IGovernance) returns (uint256) { if (_ts == Timestamp.wrap(block.timestamp)) { - return total.powerNow(); + return total.valueNow(); } - return total.powerAt(_ts); + return total.valueAt(_ts); } /** @@ -703,7 +705,7 @@ contract Governance is IGovernance { return ProposalState.Active; } - uint256 totalPower = total.powerAt(self.pendingThrough()); + uint256 totalPower = total.valueAt(self.pendingThrough()); (VoteTabulationReturn vtr,) = self.voteTabulation(totalPower); if (vtr != VoteTabulationReturn.Accepted) { return ProposalState.Rejected; diff --git a/l1-contracts/src/governance/libraries/CheckpointedUintLib.sol b/l1-contracts/src/governance/libraries/CheckpointedUintLib.sol new file mode 100644 index 000000000000..1ca160b4340e --- /dev/null +++ b/l1-contracts/src/governance/libraries/CheckpointedUintLib.sol @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2024 Aztec Labs. +pragma solidity >=0.8.27; + +import {Errors} from "@aztec/governance/libraries/Errors.sol"; +import {Timestamp} from "@aztec/shared/libraries/TimeMath.sol"; +import {SafeCast} from "@oz/utils/math/SafeCast.sol"; +import {Checkpoints} from "@oz/utils/structs/Checkpoints.sol"; + +/** + * @title CheckpointedUintLib + * @notice Library for managing Trace224 using a timestamp as key, + * Provides helper functions to `add` to or `sub` from the current value. + */ +library CheckpointedUintLib { + using Checkpoints for Checkpoints.Trace224; + using SafeCast for uint256; + + /** + * @notice Add `_amount` to the current value + * + * @dev The amounts are cast to uint224 before storing such that the (key: value) fits in a single slot + * + * @param _self - The Trace224 to add to + * @param _amount - The amount to add + * + * @return - The current value and the new value + */ + function add(Checkpoints.Trace224 storage _self, uint256 _amount) + internal + returns (uint256, uint256) + { + uint224 current = _self.latest(); + if (_amount == 0) { + return (current, current); + } + uint224 amount = _amount.toUint224(); + _self.push(block.timestamp.toUint32(), current + amount); + return (current, current + amount); + } + + /** + * @notice Subtract `_amount` from the current value + * + * @param _self - The Trace224 to subtract from + * @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) + { + 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) + ); + _self.push(block.timestamp.toUint32(), current - amount); + return (current, current - amount); + } + + /** + * @notice Get the current value + * + * @param _self - The Trace224 to get the value of + * @return - The current value + */ + function valueNow(Checkpoints.Trace224 storage _self) internal view returns (uint256) { + return _self.latest(); + } + + /** + * @notice Get the value at a given timestamp + * The timestamp MUST be in the past to guarantee it is stable + * + * @dev Uses `upperLookupRecent` instead of just `upperLookup` as it will most + * likely be a recent value when looked up as part of governance. + * + * @param _self - The Trace224 to get the value of + * @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() + ); + return _self.upperLookupRecent(Timestamp.unwrap(_time).toUint32()); + } +} diff --git a/l1-contracts/src/governance/libraries/DelegationLib.sol b/l1-contracts/src/governance/libraries/DelegationLib.sol deleted file mode 100644 index 1bb16ec37658..000000000000 --- a/l1-contracts/src/governance/libraries/DelegationLib.sol +++ /dev/null @@ -1,199 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// Copyright 2024 Aztec Labs. -pragma solidity >=0.8.27; - -import {Errors} from "@aztec/governance/libraries/Errors.sol"; -import {User, UserLib} from "@aztec/governance/libraries/UserLib.sol"; -import {Timestamp} from "@aztec/shared/libraries/TimeMath.sol"; - -struct AttesterDelegationData { - uint256 balance; - address delegatee; -} - -struct InstanceDelegationData { - mapping(address attester => AttesterDelegationData attesterData) attesterData; - User supply; -} - -struct DelegateeData { - mapping(uint256 proposalId => uint256 powerUsed) powerUsed; - User votingPower; -} - -struct DelegationData { - mapping(address instance => InstanceDelegationData instanceData) instanceData; - mapping(address delegatee => DelegateeData delegateeData) delegateeData; - User supply; -} - -// @todo Need to figure out a better naming here. It is not just delegation, it is a lib to deal with -// all of the token value stuff really. - -// This library have a lot of overlap with `Votes.sol` from Openzeppelin, -// It mainly differs as it is a library to allow us having many accountings in the same contract -// and the unit of time -library DelegationLib { - using UserLib for User; - - event DelegateChanged(address indexed attester, address oldDelegatee, address newDelegatee); - event DelegateVotesChanged(address indexed delegatee, uint256 oldValue, uint256 newValue); - - function increaseBalance( - DelegationData storage _self, - address _instance, - address _attester, - uint256 _amount - ) internal { - if (_amount == 0) { - return; - } - - InstanceDelegationData storage instance = _self.instanceData[_instance]; - - instance.attesterData[_attester].balance += _amount; - moveVotingPower(_self, address(0), instance.attesterData[_attester].delegatee, _amount); - - instance.supply.add(_amount); - _self.supply.add(_amount); - } - - function decreaseBalance( - DelegationData storage _self, - address _instance, - address _attester, - uint256 _amount - ) internal { - if (_amount == 0) { - return; - } - - InstanceDelegationData storage instance = _self.instanceData[_instance]; - - instance.attesterData[_attester].balance -= _amount; - moveVotingPower(_self, instance.attesterData[_attester].delegatee, address(0), _amount); - - instance.supply.sub(_amount); - _self.supply.sub(_amount); - } - - /** - * @notice Use power on a specific proposal and use its time as balance - * - * @dev If different timestamps are passed, it can cause mismatch in the amount of - * power that can be voted with, so it is very important that it is stable for - * a given `_proposalId` - * - * @param _self - The DelegationDate struct to modify in storage - * @param _delegatee - The delegatee using their power - * @param _proposalId - The id to use for accounting - * @param _timestamp - The timestamp for voting power of the specific `_proposalId` - * @param _amount - The amount of power to use - */ - function usePower( - DelegationData storage _self, - address _delegatee, - uint256 _proposalId, - Timestamp _timestamp, - uint256 _amount - ) internal { - uint256 powerAt = getVotingPowerAt(_self, _delegatee, _timestamp); - uint256 powerUsed = getPowerUsed(_self, _delegatee, _proposalId); - - require( - powerAt >= powerUsed + _amount, - Errors.Delegation__InsufficientPower(_delegatee, powerAt, powerUsed + _amount) - ); - - _self.delegateeData[_delegatee].powerUsed[_proposalId] += _amount; - } - - function delegate( - DelegationData storage _self, - address _instance, - address _attester, - address _delegatee - ) internal { - address oldDelegate = getDelegatee(_self, _instance, _attester); - if (oldDelegate == _delegatee) { - return; - } - _self.instanceData[_instance].attesterData[_attester].delegatee = _delegatee; - emit DelegateChanged(_attester, oldDelegate, _delegatee); - - moveVotingPower(_self, oldDelegate, _delegatee, getBalanceOf(_self, _instance, _attester)); - } - - function getBalanceOf(DelegationData storage _self, address _instance, address _attester) - internal - view - returns (uint256) - { - return _self.instanceData[_instance].attesterData[_attester].balance; - } - - function getSupplyOf(DelegationData storage _self, address _instance) - internal - view - returns (uint256) - { - return _self.instanceData[_instance].supply.powerNow(); - } - - function getSupply(DelegationData storage _self) internal view returns (uint256) { - return _self.supply.powerNow(); - } - - function getDelegatee(DelegationData storage _self, address _instance, address _attester) - internal - view - returns (address) - { - return _self.instanceData[_instance].attesterData[_attester].delegatee; - } - - function getVotingPower(DelegationData storage _self, address _delegatee) - internal - view - returns (uint256) - { - return _self.delegateeData[_delegatee].votingPower.powerNow(); - } - - function getVotingPowerAt(DelegationData storage _self, address _delegatee, Timestamp _timestamp) - internal - view - returns (uint256) - { - return _self.delegateeData[_delegatee].votingPower.powerAt(_timestamp); - } - - function getPowerUsed(DelegationData storage _self, address _delegatee, uint256 _proposalId) - internal - view - returns (uint256) - { - return _self.delegateeData[_delegatee].powerUsed[_proposalId]; - } - - function moveVotingPower( - DelegationData storage _self, - address _from, - address _to, - uint256 _amount - ) private { - if (_from == _to || _amount == 0) { - return; - } - - if (_from != address(0)) { - (uint256 oldValue, uint256 newValue) = _self.delegateeData[_from].votingPower.sub(_amount); - emit DelegateVotesChanged(_from, oldValue, newValue); - } - - if (_to != address(0)) { - (uint256 oldValue, uint256 newValue) = _self.delegateeData[_to].votingPower.add(_amount); - emit DelegateVotesChanged(_to, oldValue, newValue); - } - } -} diff --git a/l1-contracts/src/governance/libraries/DepositDelegationLib.sol b/l1-contracts/src/governance/libraries/DepositDelegationLib.sol new file mode 100644 index 000000000000..9c220c0aaf51 --- /dev/null +++ b/l1-contracts/src/governance/libraries/DepositDelegationLib.sol @@ -0,0 +1,213 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2024 Aztec Labs. +pragma solidity >=0.8.27; + +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"; + +// A struct storing balance and delegatee for an attester +struct DepositPosition { + uint256 balance; + address delegatee; +} + +// A struct storing all the positions for an instance along with a supply +struct DepositLedger { + mapping(address attester => DepositPosition position) positions; + Checkpoints.Trace224 supply; +} + +// A struct storing the voting power used for each proposal for a delegatee +// as well as their checkpointed voting power +struct VotingAccount { + mapping(uint256 proposalId => uint256 powerUsed) powerUsed; + Checkpoints.Trace224 votingPower; +} + +// A struct storing the ledgers for the individual rollup instances, the voting +// account for delegatees and the total supply. +struct DepositAndDelegationAccounting { + mapping(address instance => DepositLedger ledger) ledgers; + mapping(address delegatee => VotingAccount votingAccount) votingAccounts; + Checkpoints.Trace224 supply; +} + +// This library have a lot of overlap with `Votes.sol` from Openzeppelin, +// It mainly differs as it is a library to allow us having many accountings in the same contract +// the unit of time and allowing multiple uses of power. +library DepositDelegationLib { + using CheckpointedUintLib for Checkpoints.Trace224; + + event DelegateChanged(address indexed attester, address oldDelegatee, address newDelegatee); + event DelegateVotesChanged(address indexed delegatee, uint256 oldValue, uint256 newValue); + + function increaseBalance( + DepositAndDelegationAccounting storage _self, + address _instance, + address _attester, + uint256 _amount + ) internal { + if (_amount == 0) { + return; + } + + DepositLedger storage instance = _self.ledgers[_instance]; + + instance.positions[_attester].balance += _amount; + moveVotingPower(_self, address(0), instance.positions[_attester].delegatee, _amount); + + instance.supply.add(_amount); + _self.supply.add(_amount); + } + + function decreaseBalance( + DepositAndDelegationAccounting storage _self, + address _instance, + address _attester, + uint256 _amount + ) internal { + if (_amount == 0) { + return; + } + + DepositLedger storage instance = _self.ledgers[_instance]; + + instance.positions[_attester].balance -= _amount; + moveVotingPower(_self, instance.positions[_attester].delegatee, address(0), _amount); + + instance.supply.sub(_amount); + _self.supply.sub(_amount); + } + + /** + * @notice Use `_amount` of `_delegatee`'s voting power on `_proposalId` + * The `_delegatee`'s voting power based on the snapshot at `_timestamp` + * + * @dev If different timestamps are passed, it can cause mismatch in the amount of + * power that can be voted with, so it is very important that it is stable for + * a given `_proposalId` + * + * @param _self - The DelegationDate struct to modify in storage + * @param _delegatee - The delegatee using their power + * @param _proposalId - The id to use for accounting + * @param _timestamp - The timestamp for voting power of the specific `_proposalId` + * @param _amount - The amount of power to use + */ + function usePower( + DepositAndDelegationAccounting storage _self, + address _delegatee, + uint256 _proposalId, + Timestamp _timestamp, + uint256 _amount + ) internal { + uint256 powerAt = getVotingPowerAt(_self, _delegatee, _timestamp); + uint256 powerUsed = getPowerUsed(_self, _delegatee, _proposalId); + + require( + powerAt >= powerUsed + _amount, + Errors.Delegation__InsufficientPower(_delegatee, powerAt, powerUsed + _amount) + ); + + _self.votingAccounts[_delegatee].powerUsed[_proposalId] += _amount; + } + + function delegate( + DepositAndDelegationAccounting storage _self, + address _instance, + address _attester, + address _delegatee + ) internal { + address oldDelegate = getDelegatee(_self, _instance, _attester); + if (oldDelegate == _delegatee) { + return; + } + _self.ledgers[_instance].positions[_attester].delegatee = _delegatee; + emit DelegateChanged(_attester, oldDelegate, _delegatee); + + moveVotingPower(_self, oldDelegate, _delegatee, getBalanceOf(_self, _instance, _attester)); + } + + 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) + internal + view + returns (uint256) + { + return _self.ledgers[_instance].supply.valueNow(); + } + + function getSupply(DepositAndDelegationAccounting storage _self) internal view returns (uint256) { + return _self.supply.valueNow(); + } + + function getDelegatee( + DepositAndDelegationAccounting storage _self, + address _instance, + address _attester + ) internal view returns (address) { + return _self.ledgers[_instance].positions[_attester].delegatee; + } + + function getVotingPower(DepositAndDelegationAccounting storage _self, address _delegatee) + internal + view + returns (uint256) + { + return _self.votingAccounts[_delegatee].votingPower.valueNow(); + } + + 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) { + return _self.votingAccounts[_delegatee].powerUsed[_proposalId]; + } + + function moveVotingPower( + DepositAndDelegationAccounting storage _self, + address _from, + address _to, + uint256 _amount + ) private { + if (_from == _to || _amount == 0) { + return; + } + + if (_from != address(0)) { + (uint256 oldValue, uint256 newValue) = _self.votingAccounts[_from].votingPower.sub(_amount); + emit DelegateVotesChanged(_from, oldValue, newValue); + } + + if (_to != address(0)) { + (uint256 oldValue, uint256 newValue) = _self.votingAccounts[_to].votingPower.add(_amount); + emit DelegateVotesChanged(_to, oldValue, newValue); + } + } +} diff --git a/l1-contracts/src/governance/libraries/Errors.sol b/l1-contracts/src/governance/libraries/Errors.sol index 786ec06e0c4a..17b10b432fd5 100644 --- a/l1-contracts/src/governance/libraries/Errors.sol +++ b/l1-contracts/src/governance/libraries/Errors.sol @@ -30,7 +30,10 @@ library Errors { error Governance__ProposalCannotBeDropped(); error Governance__DepositNotAllowed(); - error Governance__UserLib__NotInPast(); + error Governance__CheckpointedUintLib__InsufficientValue( + address owner, uint256 have, uint256 required + ); + error Governance__CheckpointedUintLib__NotInPast(); error Governance__ConfigurationLib__InvalidMinimumVotes(); error Governance__ConfigurationLib__LockAmountTooSmall(); @@ -78,7 +81,7 @@ library Errors { error GSE__NotLatestRollup(address); error GSE__AlreadyRegistered(address, address); error GSE__NothingToExit(address); - error GSE__InsufficientStake(uint256, uint256); + error GSE__InsufficientBalance(uint256, uint256); error GSE__FailedToRemove(address); error GSE__InstanceDoesNotExist(address); error GSE__NotWithdrawer(address, address); diff --git a/l1-contracts/src/governance/libraries/UserLib.sol b/l1-contracts/src/governance/libraries/UserLib.sol deleted file mode 100644 index ea5c517ca5c8..000000000000 --- a/l1-contracts/src/governance/libraries/UserLib.sol +++ /dev/null @@ -1,55 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// Copyright 2024 Aztec Labs. -pragma solidity >=0.8.27; - -import {Errors} from "@aztec/governance/libraries/Errors.sol"; -import {Timestamp} from "@aztec/shared/libraries/TimeMath.sol"; -import {SafeCast} from "@oz/utils/math/SafeCast.sol"; -import {Checkpoints} from "@oz/utils/structs/Checkpoints.sol"; - -struct User { - Checkpoints.Trace224 checkpoints; -} - -/** - * @title UserLib - * @notice Library for managing user power - * Using timestamp to uint32 to fit neatly with the Trace224 struct. We see this as sane - * because the governance can upgrade itself and will hopefully have figured out something better - * by then. - */ -library UserLib { - using Checkpoints for Checkpoints.Trace224; - using SafeCast for uint256; - - function add(User storage _self, uint256 _amount) internal returns (uint256, uint256) { - uint224 current = _self.checkpoints.latest(); - if (_amount == 0) { - return (current, current); - } - uint224 amount = _amount.toUint224(); - _self.checkpoints.push(block.timestamp.toUint32(), current + amount); - return (current, current + amount); - } - - function sub(User storage _self, uint256 _amount) internal returns (uint256, uint256) { - uint224 current = _self.checkpoints.latest(); - if (_amount == 0) { - return (current, current); - } - uint224 amount = _amount.toUint224(); - require(current >= amount, Errors.Governance__InsufficientPower(msg.sender, current, amount)); - _self.checkpoints.push(block.timestamp.toUint32(), current - amount); - return (current, current - amount); - } - - function powerNow(User storage _self) internal view returns (uint256) { - return _self.checkpoints.latest(); - } - - function powerAt(User storage _self, Timestamp _time) internal view returns (uint256) { - // If not in the past, the values are not stable. We disallow using it to avoid potential misuse. - require(_time < Timestamp.wrap(block.timestamp), Errors.Governance__UserLib__NotInPast()); - return _self.checkpoints.upperLookup(Timestamp.unwrap(_time).toUint32()); - } -} diff --git a/l1-contracts/src/mock/StakingAssetHandler.sol b/l1-contracts/src/mock/StakingAssetHandler.sol index 4ee23cc53851..181c86431726 100644 --- a/l1-contracts/src/mock/StakingAssetHandler.sol +++ b/l1-contracts/src/mock/StakingAssetHandler.sol @@ -166,23 +166,23 @@ contract StakingAssetHandler is IStakingAssetHandler, Ownable { ProofVerificationParams calldata _params ) external override(IStakingAssetHandler) { IStaking rollup = IStaking(address(REGISTRY.getCanonicalRollup())); - uint256 depositAmount = rollup.getDepositAmount(); + uint256 activationThreshold = rollup.getActivationThreshold(); // If the sender is unhinged, will mint the required amount (to not impact other users). // Otherwise we add them to the deposit queue. if (isUnhinged[msg.sender]) { - STAKING_ASSET.mint(address(this), depositAmount); + STAKING_ASSET.mint(address(this), activationThreshold); - _triggerDeposit(rollup, depositAmount, _attester); + _triggerDeposit(rollup, activationThreshold, _attester); } else { - _topUpIfRequired(depositAmount); + _topUpIfRequired(activationThreshold); // Check attester has the guardian role (included in merkle tree) _validateMerkleProof(_attester, _merkleProof); _validatePassportProof(_attester, _params); // If the attester is currently exiting, we finalize the exit for him. - _triggerDeposit(rollup, depositAmount, _attester); + _triggerDeposit(rollup, activationThreshold, _attester); } } @@ -199,10 +199,10 @@ contract StakingAssetHandler is IStakingAssetHandler, Ownable { require(nullifiers[nullifier] != false, NoNullifier()); IStaking rollup = IStaking(address(REGISTRY.getCanonicalRollup())); - uint256 depositAmount = rollup.getDepositAmount(); + uint256 activationThreshold = rollup.getActivationThreshold(); - _topUpIfRequired(depositAmount); - _triggerDeposit(rollup, depositAmount, _attester); + _topUpIfRequired(activationThreshold); + _triggerDeposit(rollup, activationThreshold, _attester); } function setMintInterval(uint256 _interval) external override(IStakingAssetHandler) onlyOwner { @@ -315,15 +315,15 @@ contract StakingAssetHandler is IStakingAssetHandler, Ownable { attesterToNullifier[_attester] = nullifier; } - function _topUpIfRequired(uint256 _depositAmount) internal { - if (STAKING_ASSET.balanceOf(address(this)) < _depositAmount) { + function _topUpIfRequired(uint256 _activationThreshold) internal { + if (STAKING_ASSET.balanceOf(address(this)) < _activationThreshold) { require( block.timestamp - lastMintTimestamp >= mintInterval, ValidatorQuotaFilledUntil(lastMintTimestamp + mintInterval) ); - STAKING_ASSET.mint(address(this), _depositAmount * depositsPerMint); + STAKING_ASSET.mint(address(this), _activationThreshold * depositsPerMint); lastMintTimestamp = block.timestamp; - emit ToppedUp(_depositAmount * depositsPerMint); + emit ToppedUp(_activationThreshold * depositsPerMint); } } @@ -333,16 +333,18 @@ contract StakingAssetHandler is IStakingAssetHandler, Ownable { * complete the exit for them first. * * @param _rollup - the rollup address - * @param _depositAmount - the deposit amount + * @param _activationThreshold - the deposit amount * @param _attester - the validator's attester address */ - function _triggerDeposit(IStaking _rollup, uint256 _depositAmount, 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); } - STAKING_ASSET.approve(address(_rollup), _depositAmount); + STAKING_ASSET.approve(address(_rollup), _activationThreshold); _rollup.deposit(_attester, withdrawer, true); emit ValidatorAdded(address(_rollup), _attester, withdrawer); diff --git a/l1-contracts/test/RollupGetters.t.sol b/l1-contracts/test/RollupGetters.t.sol index d90220fa872c..a5b051ac4f83 100644 --- a/l1-contracts/test/RollupGetters.t.sol +++ b/l1-contracts/test/RollupGetters.t.sol @@ -89,10 +89,10 @@ contract RollupShouldBeGetters is ValidatorSelectionTestBase { timeCheater.cheat__jumpForwardEpochs(2); - uint256 depositAmount = rollup.getGSE().DEPOSIT_AMOUNT(); + uint256 activationThreshold = rollup.getGSE().ACTIVATION_THRESHOLD(); vm.prank(testERC20.owner()); - testERC20.mint(address(this), 10e3 * depositAmount); + testERC20.mint(address(this), 10e3 * activationThreshold); testERC20.approve(address(rollup), type(uint256).max); uint256 offset = 0; @@ -149,10 +149,10 @@ contract RollupShouldBeGetters is ValidatorSelectionTestBase { // altering the size checkpoints do not heavily impact the gas costs. timeCheater.cheat__jumpForwardEpochs(2); - uint256 depositAmount = rollup.getGSE().DEPOSIT_AMOUNT(); + uint256 activationThreshold = rollup.getGSE().ACTIVATION_THRESHOLD(); vm.prank(testERC20.owner()); - testERC20.mint(address(this), 10e3 * depositAmount); + testERC20.mint(address(this), 10e3 * activationThreshold); testERC20.approve(address(rollup), type(uint256).max); // Add a bunch of attesters to diff --git a/l1-contracts/test/builder/GseBuilder.sol b/l1-contracts/test/builder/GseBuilder.sol index 74ad456d9b77..9b8207e3a302 100644 --- a/l1-contracts/test/builder/GseBuilder.sol +++ b/l1-contracts/test/builder/GseBuilder.sol @@ -66,7 +66,10 @@ contract GSEBuilder is TestBase { if (address(config.gse) == address(0)) { config.gse = new GSE( - address(this), config.testERC20, TestConstants.DEPOSIT_AMOUNT, TestConstants.MINIMUM_STAKE + address(this), + config.testERC20, + TestConstants.ACTIVATION_THRESHOLD, + TestConstants.EJECTION_THRESHOLD ); vm.label(address(config.gse), "GSE"); } diff --git a/l1-contracts/test/builder/RollupBuilder.sol b/l1-contracts/test/builder/RollupBuilder.sol index 9cfeac005784..4a2625df143c 100644 --- a/l1-contracts/test/builder/RollupBuilder.sol +++ b/l1-contracts/test/builder/RollupBuilder.sol @@ -233,7 +233,10 @@ contract RollupBuilder is Test { if (address(config.gse) == address(0)) { config.gse = new GSE( - address(this), config.testERC20, TestConstants.DEPOSIT_AMOUNT, TestConstants.MINIMUM_STAKE + address(this), + config.testERC20, + TestConstants.ACTIVATION_THRESHOLD, + TestConstants.EJECTION_THRESHOLD ); } @@ -300,7 +303,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.DEPOSIT_AMOUNT() * config.validators.length + address(multiAdder), config.gse.ACTIVATION_THRESHOLD() * config.validators.length ); multiAdder.addValidators(config.validators); } diff --git a/l1-contracts/test/delegation/base.t.sol b/l1-contracts/test/delegation/base.t.sol index 7d6d462ae04c..0a767037a61f 100644 --- a/l1-contracts/test/delegation/base.t.sol +++ b/l1-contracts/test/delegation/base.t.sol @@ -46,10 +46,10 @@ contract GSEBase is TestBase { function help__deposit(address _attester, address _withdrawer, bool _moveWithLatestRollup) internal { - uint256 depositAmount = ROLLUP.getDepositAmount(); + uint256 activationThreshold = ROLLUP.getActivationThreshold(); vm.prank(stakingAsset.owner()); - stakingAsset.mint(address(this), depositAmount); - stakingAsset.approve(address(ROLLUP), depositAmount); + stakingAsset.mint(address(this), activationThreshold); + stakingAsset.approve(address(ROLLUP), activationThreshold); uint256 balance = stakingAsset.balanceOf(address(governance)); @@ -61,7 +61,9 @@ contract GSEBase is TestBase { ROLLUP.flushEntryQueue(); assertEq( - stakingAsset.balanceOf(address(governance)), balance + depositAmount, "invalid gov balance" + 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 9e4af3831e6b..ee77ba0f4567 100644 --- a/l1-contracts/test/delegation/minimal.t.sol +++ b/l1-contracts/test/delegation/minimal.t.sol @@ -32,12 +32,12 @@ contract MinimalDelegationTest is GSEBase { using stdStorage for StdStorage; address bonus; - uint256 depositAmount; + uint256 activationThreshold; function setUp() public override { super.setUp(); bonus = gse.getBonusInstanceAddress(); - depositAmount = ROLLUP.getDepositAmount(); + activationThreshold = ROLLUP.getActivationThreshold(); vm.label(bonus, "bonus"); } @@ -85,10 +85,12 @@ contract MinimalDelegationTest is GSEBase { vm.warp(ts.ts4); - _checkInstanceCanonical(address(ROLLUP), 0, depositAmount, Timestamp.wrap(ts.ts1)); - _checkInstanceCanonical(address(ROLLUP), depositAmount, depositAmount, Timestamp.wrap(ts.ts2)); + _checkInstanceCanonical(address(ROLLUP), 0, activationThreshold, Timestamp.wrap(ts.ts1)); _checkInstanceCanonical( - address(ROLLUP), depositAmount, depositAmount * 2, Timestamp.wrap(ts.ts3) + 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"); @@ -119,7 +121,7 @@ contract MinimalDelegationTest is GSEBase { vm.warp(ts.ts6); - assertEq(governance.totalPowerAt(Timestamp.wrap(ts.ts6)), depositAmount * 3); + assertEq(governance.totalPowerAt(Timestamp.wrap(ts.ts6)), activationThreshold * 3); if (_overwriteDelay) { stdstore.enable_packed_slots().target(address(ROLLUP)).sig("getExitDelay()").checked_write(5); @@ -128,41 +130,45 @@ contract MinimalDelegationTest is GSEBase { vm.prank(WITHDRAWER); ROLLUP.initiateWithdraw(ATTESTER2, WITHDRAWER); - assertEq(governance.totalPowerAt(Timestamp.wrap(ts.ts6)), depositAmount * 2); + assertEq(governance.totalPowerAt(Timestamp.wrap(ts.ts6)), activationThreshold * 2); vm.warp(ts.ts7); // Check power at different points in time. - _checkInstanceCanonical(address(ROLLUP), 0, depositAmount, Timestamp.wrap(ts.ts1)); + _checkInstanceCanonical(address(ROLLUP), 0, activationThreshold, Timestamp.wrap(ts.ts1)); _checkInstanceNonCanonical(address(dead), 0, Timestamp.wrap(ts.ts1)); - _checkInstanceCanonical(address(ROLLUP), depositAmount, depositAmount, Timestamp.wrap(ts.ts2)); + _checkInstanceCanonical( + address(ROLLUP), activationThreshold, activationThreshold, Timestamp.wrap(ts.ts2) + ); _checkInstanceNonCanonical(address(dead), 0, Timestamp.wrap(ts.ts2)); _checkInstanceCanonical( - address(ROLLUP), depositAmount, depositAmount * 2, Timestamp.wrap(ts.ts3) + address(ROLLUP), activationThreshold, activationThreshold * 2, Timestamp.wrap(ts.ts3) ); _checkInstanceNonCanonical(address(dead), 0, Timestamp.wrap(ts.ts3)); - _checkInstanceCanonical(address(ROLLUP), depositAmount, depositAmount, Timestamp.wrap(ts.ts4)); + _checkInstanceCanonical( + address(ROLLUP), activationThreshold, activationThreshold, Timestamp.wrap(ts.ts4) + ); _checkInstanceNonCanonical(address(dead), 0, Timestamp.wrap(ts.ts4)); - _checkInstanceNonCanonical(address(ROLLUP), depositAmount, Timestamp.wrap(ts.ts5)); - _checkInstanceCanonical(address(dead), 0, depositAmount, Timestamp.wrap(ts.ts5)); + _checkInstanceNonCanonical(address(ROLLUP), activationThreshold, Timestamp.wrap(ts.ts5)); + _checkInstanceCanonical(address(dead), 0, activationThreshold, Timestamp.wrap(ts.ts5)); _checkInstanceNonCanonical(address(ROLLUP), 0, Timestamp.wrap(ts.ts6)); - _checkInstanceCanonical(address(dead), 0, depositAmount, Timestamp.wrap(ts.ts6)); + _checkInstanceCanonical(address(dead), 0, activationThreshold, Timestamp.wrap(ts.ts6)); - assertEq(gse.getVotingPower(WITHDRAWER), depositAmount, "voting power user"); + assertEq(gse.getVotingPower(WITHDRAWER), activationThreshold, "voting power user"); // Voting _checkPowerUsed(WITHDRAWER, 0, 0, votingTime); - _checkPowerUsed(address(ROLLUP), 0, depositAmount, votingTime); - _checkPowerUsed(bonus, 0, depositAmount * 2, votingTime); + _checkPowerUsed(address(ROLLUP), 0, activationThreshold, votingTime); + _checkPowerUsed(bonus, 0, activationThreshold * 2, votingTime); // Checking extra here just for sanity uint256 powerToVoteSelf = gse.getVotingPowerAt(address(ROLLUP), Timestamp.wrap(votingTime)); - assertEq(powerToVoteSelf, depositAmount, "powerToVoteSelf"); + assertEq(powerToVoteSelf, activationThreshold, "powerToVoteSelf"); // We go to the rollup and have it vote. // If we did not update the registry, it and the governanceProposer still belive that the rollup is canonical @@ -175,9 +181,9 @@ contract MinimalDelegationTest is GSEBase { ); } else { vm.expectEmit(true, true, true, true, address(governance)); - emit IGovernance.VoteCast(proposalId, address(gse), true, depositAmount); + emit IGovernance.VoteCast(proposalId, address(gse), true, activationThreshold); vm.expectEmit(true, true, true, true, address(governance)); - emit IGovernance.VoteCast(proposalId, address(gse), true, depositAmount * 2); + emit IGovernance.VoteCast(proposalId, address(gse), true, activationThreshold * 2); } ROLLUP.vote(proposalId); @@ -187,8 +193,8 @@ contract MinimalDelegationTest is GSEBase { } assertEq(gse.getPowerUsed(WITHDRAWER, 0), 0, "power used"); - assertEq(gse.getPowerUsed(address(ROLLUP), 0), depositAmount, "power used"); - assertEq(gse.getPowerUsed(bonus, 0), depositAmount * 2, "power used"); + assertEq(gse.getPowerUsed(address(ROLLUP), 0), activationThreshold, "power used"); + assertEq(gse.getPowerUsed(bonus, 0), activationThreshold * 2, "power used"); // Make sure we cannot double vote. Here we just bypass and try to make the rollup do it directly. vm.prank(address(ROLLUP)); @@ -196,22 +202,22 @@ contract MinimalDelegationTest is GSEBase { abi.encodeWithSelector( GovErrors.Delegation__InsufficientPower.selector, address(ROLLUP), - depositAmount, - depositAmount * 2 + activationThreshold, + activationThreshold * 2 ) ); gse.vote(proposalId, powerToVoteSelf, true); // Now make the same checks but with the bonus instance powerToVoteSelf = gse.getVotingPowerAt(bonus, Timestamp.wrap(votingTime)); - assertEq(powerToVoteSelf, depositAmount * 2, "powerToVoteSelf"); + assertEq(powerToVoteSelf, activationThreshold * 2, "powerToVoteSelf"); vm.prank(address(ROLLUP)); vm.expectRevert( abi.encodeWithSelector( GovErrors.Delegation__InsufficientPower.selector, address(bonus), - depositAmount * 2, - depositAmount * 4 + activationThreshold * 2, + activationThreshold * 4 ) ); gse.voteWithBonus(proposalId, powerToVoteSelf, true); @@ -235,10 +241,10 @@ contract MinimalDelegationTest is GSEBase { } ROLLUP.finaliseWithdraw(ATTESTER2); - assertEq(governance.totalPowerAt(Timestamp.wrap(block.timestamp)), depositAmount * 2); - assertEq(stakingAsset.balanceOf(WITHDRAWER), depositAmount); + assertEq(governance.totalPowerAt(Timestamp.wrap(block.timestamp)), activationThreshold * 2); + assertEq(stakingAsset.balanceOf(WITHDRAWER), activationThreshold); - assertEq(governance.getProposal(proposalId).summedBallot.yea, depositAmount * 3, "yeas"); + assertEq(governance.getProposal(proposalId).summedBallot.yea, activationThreshold * 3, "yeas"); assertEq(governance.getProposal(proposalId).summedBallot.nay, 0, "nays"); } diff --git a/l1-contracts/test/governance/governance/userlib/add.t.sol b/l1-contracts/test/governance/governance/checkpointedUintLib/add.t.sol similarity index 67% rename from l1-contracts/test/governance/governance/userlib/add.t.sol rename to l1-contracts/test/governance/governance/checkpointedUintLib/add.t.sol index 086ea12eedb2..5aa4f7e7d61a 100644 --- a/l1-contracts/test/governance/governance/userlib/add.t.sol +++ b/l1-contracts/test/governance/governance/checkpointedUintLib/add.t.sol @@ -1,14 +1,16 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.27; -import {UserLibBase} from "./base.t.sol"; -import {User, UserLib} from "@aztec/governance/libraries/UserLib.sol"; +import {CheckpointedUintLibBase} from "./base.t.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"; -contract AddTest is UserLibBase { - using UserLib for User; +contract AddTest is CheckpointedUintLibBase { + using CheckpointedUintLib for Checkpoints.Trace224; using Checkpoints for Checkpoints.Trace224; using TimeLib for Timestamp; using SafeCast for uint256; @@ -16,13 +18,13 @@ contract AddTest is UserLibBase { function test_WhenAmountEq0() external { // it return instantly with no changes - assertEq(user.checkpoints.length(), 0); + assertEq(user.length(), 0); vm.record(); user.add(0); (bytes32[] memory reads, bytes32[] memory writes) = vm.accesses(address(this)); - assertEq(user.checkpoints.length(), 0); + assertEq(user.length(), 0); assertEq(reads.length, 1); assertEq(writes.length, 0); } @@ -34,13 +36,13 @@ contract AddTest is UserLibBase { // it adds checkpoint with amount // it increases num checkpoints - assertEq(user.checkpoints.length(), 0); + assertEq(user.length(), 0); vm.warp(_time); user.add(amount); - assertEq(user.checkpoints.length(), 1); - Checkpoints.Checkpoint224 memory last = user.checkpoints.at(0); + assertEq(user.length(), 1); + Checkpoints.Checkpoint224 memory last = user.at(0); assertEq(last._key, _time); assertEq(last._value, amount.toUint224()); } @@ -53,14 +55,14 @@ contract AddTest is UserLibBase { ) external whenAmountGt0(_amount) givenUserHaveCheckpoints(_insert, _timeBetween, _amounts) { // it increases power by amount - assertEq(user.checkpoints.length(), insertions, "num checkpoints"); + assertEq(user.length(), insertions, "num checkpoints"); // Cache in memory - Checkpoints.Checkpoint224 memory last = user.checkpoints.at(uint32(insertions - 1)); + Checkpoints.Checkpoint224 memory last = user.at(uint32(insertions - 1)); user.add(amount); - assertEq(user.checkpoints.length(), insertions, "num checkpoints"); - Checkpoints.Checkpoint224 memory last2 = user.checkpoints.at(uint32(insertions - 1)); + assertEq(user.length(), insertions, "num checkpoints"); + Checkpoints.Checkpoint224 memory last2 = user.at(uint32(insertions - 1)); assertEq(last2._key, last._key, "key"); assertEq(last2._value, last._value + amount.toUint224(), "power"); @@ -78,15 +80,15 @@ contract AddTest is UserLibBase { uint256 time = bound(_time, 1, type(uint16).max); - assertEq(user.checkpoints.length(), insertions); + assertEq(user.length(), insertions); // Cache in memory - Checkpoints.Checkpoint224 memory last = user.checkpoints.at(uint32(insertions - 1)); + Checkpoints.Checkpoint224 memory last = user.at(uint32(insertions - 1)); vm.warp(block.timestamp + time); user.add(amount); - assertEq(user.checkpoints.length(), insertions + 1); - Checkpoints.Checkpoint224 memory last2 = user.checkpoints.at(uint32(insertions)); + assertEq(user.length(), insertions + 1); + Checkpoints.Checkpoint224 memory last2 = user.at(uint32(insertions)); assertEq(last2._key, last._key + time.toUint32()); assertEq(last2._value, last._value + amount); diff --git a/l1-contracts/test/governance/governance/userlib/add.tree b/l1-contracts/test/governance/governance/checkpointedUintLib/add.tree similarity index 100% rename from l1-contracts/test/governance/governance/userlib/add.tree rename to l1-contracts/test/governance/governance/checkpointedUintLib/add.tree diff --git a/l1-contracts/test/governance/governance/userlib/base.t.sol b/l1-contracts/test/governance/governance/checkpointedUintLib/base.t.sol similarity index 78% rename from l1-contracts/test/governance/governance/userlib/base.t.sol rename to l1-contracts/test/governance/governance/checkpointedUintLib/base.t.sol index 0cf04d29119c..ae154ccf99ce 100644 --- a/l1-contracts/test/governance/governance/userlib/base.t.sol +++ b/l1-contracts/test/governance/governance/checkpointedUintLib/base.t.sol @@ -2,14 +2,16 @@ pragma solidity >=0.8.27; import {TestBase} from "@test/base/Base.sol"; -import {User, UserLib} from "@aztec/governance/libraries/UserLib.sol"; +import { + Checkpoints, CheckpointedUintLib +} from "@aztec/governance/libraries/CheckpointedUintLib.sol"; -contract UserLibBase is TestBase { - using UserLib for User; +contract CheckpointedUintLibBase is TestBase { + using CheckpointedUintLib for Checkpoints.Trace224; uint256 internal constant CHECKPOINT_COUNT = 8; - User internal user; + Checkpoints.Trace224 internal user; uint256 internal amount; uint256 internal sumBefore; diff --git a/l1-contracts/test/governance/governance/userlib/powerAt.t.sol b/l1-contracts/test/governance/governance/checkpointedUintLib/powerAt.t.sol similarity index 68% rename from l1-contracts/test/governance/governance/userlib/powerAt.t.sol rename to l1-contracts/test/governance/governance/checkpointedUintLib/powerAt.t.sol index 6003d9cb5c20..db2510697b78 100644 --- a/l1-contracts/test/governance/governance/userlib/powerAt.t.sol +++ b/l1-contracts/test/governance/governance/checkpointedUintLib/powerAt.t.sol @@ -1,15 +1,17 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.27; -import {UserLibBase} from "./base.t.sol"; -import {User, UserLib} from "@aztec/governance/libraries/UserLib.sol"; +import {CheckpointedUintLibBase} from "./base.t.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"; import {SafeCast} from "@oz/utils/math/SafeCast.sol"; -contract PowerAtTest is UserLibBase { - using UserLib for User; +contract PowerAtTest is CheckpointedUintLibBase { + using CheckpointedUintLib for Checkpoints.Trace224; using Checkpoints for Checkpoints.Trace224; using SafeCast for uint256; @@ -17,14 +19,16 @@ contract PowerAtTest is UserLibBase { function test_WhenTimeNotInPast() external { // it revert - vm.expectRevert(abi.encodeWithSelector(Errors.Governance__UserLib__NotInPast.selector)); + vm.expectRevert( + abi.encodeWithSelector(Errors.Governance__CheckpointedUintLib__NotInPast.selector) + ); this.callPowerAt(); } // @dev helper for testing, to avoid: // "call didn't revert at a lower depth than cheatcode call depth" function callPowerAt() external view { - user.powerAt(Timestamp.wrap(block.timestamp)); + user.valueAt(Timestamp.wrap(block.timestamp)); } modifier whenTimeInPast() { @@ -36,7 +40,7 @@ contract PowerAtTest is UserLibBase { function test_GivenNoCheckpoints() external whenTimeInPast { // it return 0 - assertEq(user.powerAt(time), 0); + assertEq(user.valueAt(time), 0); } function test_WhenTimeLtFirstCheckpoint( @@ -46,8 +50,8 @@ contract PowerAtTest is UserLibBase { ) external whenTimeInPast givenUserHaveCheckpoints(_insert, _timeBetween, _amounts) { // it return 0 - assertEq(user.powerAt(time), 0, "non-zero power"); - assertGt(user.powerNow(), 0, "insufficient power"); + assertEq(user.valueAt(time), 0, "non-zero power"); + assertGt(user.valueNow(), 0, "insufficient power"); } function test_WhenTimeGeFirstCheckpoint( @@ -66,22 +70,22 @@ contract PowerAtTest is UserLibBase { vm.warp(block.timestamp + 12); - uint32 index = bound(_index, 0, user.checkpoints.length() - (_between ? 2 : 1)).toUint32(); + uint32 index = bound(_index, 0, user.length() - (_between ? 2 : 1)).toUint32(); - Checkpoints.Checkpoint224 memory first = user.checkpoints.at(index); + Checkpoints.Checkpoint224 memory first = user.at(index); if (_between) { - Checkpoints.Checkpoint224 memory second = user.checkpoints.at(index + 1); + Checkpoints.Checkpoint224 memory second = user.at(index + 1); time = Timestamp.wrap(first._key) + Timestamp.wrap((second._key - first._key) / 2); } else { - if (index == user.checkpoints.length() && _index % 2 == 0) { + if (index == user.length() && _index % 2 == 0) { time = Timestamp.wrap(block.timestamp - 12); } else { time = Timestamp.wrap(first._key); } } - assertEq(user.powerAt(time), first._value); + assertEq(user.valueAt(time), first._value); assertGt(first._value, 0); } } diff --git a/l1-contracts/test/governance/governance/userlib/powerAt.tree b/l1-contracts/test/governance/governance/checkpointedUintLib/powerAt.tree similarity index 100% rename from l1-contracts/test/governance/governance/userlib/powerAt.tree rename to l1-contracts/test/governance/governance/checkpointedUintLib/powerAt.tree diff --git a/l1-contracts/test/governance/governance/userlib/powerNow.t.sol b/l1-contracts/test/governance/governance/checkpointedUintLib/powerNow.t.sol similarity index 69% rename from l1-contracts/test/governance/governance/userlib/powerNow.t.sol rename to l1-contracts/test/governance/governance/checkpointedUintLib/powerNow.t.sol index 4f412ab54b92..a6f8e94c6027 100644 --- a/l1-contracts/test/governance/governance/userlib/powerNow.t.sol +++ b/l1-contracts/test/governance/governance/checkpointedUintLib/powerNow.t.sol @@ -1,14 +1,16 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.27; -import {UserLibBase} from "./base.t.sol"; -import {User, UserLib} from "@aztec/governance/libraries/UserLib.sol"; +import {CheckpointedUintLibBase} from "./base.t.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"; -contract PowerNowTest is UserLibBase { - using UserLib for User; +contract PowerNowTest is CheckpointedUintLibBase { + using CheckpointedUintLib for Checkpoints.Trace224; using Checkpoints for Checkpoints.Trace224; Timestamp internal time; @@ -16,7 +18,7 @@ contract PowerNowTest is UserLibBase { function test_GivenNoCheckpoints(uint64 _time) external { // it return 0 vm.warp(_time); - assertEq(user.powerNow(), 0); + assertEq(user.valueNow(), 0); } function test_GivenCheckpoints( @@ -29,6 +31,6 @@ contract PowerNowTest is UserLibBase { vm.warp(block.timestamp + _timeJump); - assertEq(user.powerNow(), user.checkpoints.latest()); + assertEq(user.valueNow(), user.latest()); } } diff --git a/l1-contracts/test/governance/governance/userlib/powerNow.tree b/l1-contracts/test/governance/governance/checkpointedUintLib/powerNow.tree similarity index 100% rename from l1-contracts/test/governance/governance/userlib/powerNow.tree rename to l1-contracts/test/governance/governance/checkpointedUintLib/powerNow.tree diff --git a/l1-contracts/test/governance/governance/userlib/sub.t.sol b/l1-contracts/test/governance/governance/checkpointedUintLib/sub.t.sol similarity index 73% rename from l1-contracts/test/governance/governance/userlib/sub.t.sol rename to l1-contracts/test/governance/governance/checkpointedUintLib/sub.t.sol index 2708f368c2c0..aee327834d96 100644 --- a/l1-contracts/test/governance/governance/userlib/sub.t.sol +++ b/l1-contracts/test/governance/governance/checkpointedUintLib/sub.t.sol @@ -1,28 +1,30 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.27; -import {UserLibBase} from "./base.t.sol"; -import {User, UserLib} from "@aztec/governance/libraries/UserLib.sol"; +import {CheckpointedUintLibBase} from "./base.t.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"; import {SafeCast} from "@oz/utils/math/SafeCast.sol"; -contract SubTest is UserLibBase { - using UserLib for User; +contract SubTest is CheckpointedUintLibBase { + using CheckpointedUintLib for Checkpoints.Trace224; using Checkpoints for Checkpoints.Trace224; using SafeCast for uint256; function test_WhenAmountEq0() external { // it return instantly with no changes - assertEq(user.checkpoints.length(), 0); + assertEq(user.length(), 0); vm.record(); user.sub(0); (bytes32[] memory reads, bytes32[] memory writes) = vm.accesses(address(this)); - assertEq(user.checkpoints.length(), 0); + assertEq(user.length(), 0); assertEq(reads.length, 1); assertEq(writes.length, 0); } @@ -30,7 +32,9 @@ contract SubTest is UserLibBase { function test_GivenUserHaveNoCheckpoints(uint256 _amount) external whenAmountGt0(_amount) { // it revert vm.expectRevert( - abi.encodeWithSelector(Errors.Governance__InsufficientPower.selector, msg.sender, 0, amount) + abi.encodeWithSelector( + Errors.Governance__CheckpointedUintLib__InsufficientValue.selector, msg.sender, 0, amount + ) ); vm.prank(msg.sender); this.callSub(amount); @@ -48,7 +52,10 @@ contract SubTest is UserLibBase { vm.expectRevert( abi.encodeWithSelector( - Errors.Governance__InsufficientPower.selector, msg.sender, sumBefore, amount + Errors.Governance__CheckpointedUintLib__InsufficientValue.selector, + msg.sender, + sumBefore, + amount ) ); vm.prank(msg.sender); @@ -74,14 +81,14 @@ contract SubTest is UserLibBase { { // it decreases power by amount - assertEq(user.checkpoints.length(), insertions, "num checkpoints"); + assertEq(user.length(), insertions, "num checkpoints"); // Cache in memory - Checkpoints.Checkpoint224 memory last = user.checkpoints.at(uint32(insertions - 1)); + Checkpoints.Checkpoint224 memory last = user.at(uint32(insertions - 1)); user.sub(amount); - assertEq(user.checkpoints.length(), insertions, "num checkpoints"); - Checkpoints.Checkpoint224 memory last2 = user.checkpoints.at(uint32(insertions - 1)); + assertEq(user.length(), insertions, "num checkpoints"); + Checkpoints.Checkpoint224 memory last2 = user.at(uint32(insertions - 1)); assertEq(last2._key, last._key, "time"); assertEq(last2._value, last._value - amount.toUint224(), "power"); @@ -104,15 +111,15 @@ contract SubTest is UserLibBase { uint256 time = bound(_time, 1, type(uint16).max); - assertEq(user.checkpoints.length(), insertions); + assertEq(user.length(), insertions); // Cache in memory - Checkpoints.Checkpoint224 memory last = user.checkpoints.at(uint32(insertions - 1)); + Checkpoints.Checkpoint224 memory last = user.at(uint32(insertions - 1)); vm.warp(block.timestamp + time); user.sub(amount); - assertEq(user.checkpoints.length(), insertions + 1); - Checkpoints.Checkpoint224 memory last2 = user.checkpoints.at(uint32(insertions)); + assertEq(user.length(), insertions + 1); + Checkpoints.Checkpoint224 memory last2 = user.at(uint32(insertions)); assertEq(last2._key, last._key + time.toUint32()); assertEq(last2._value, last._value - amount.toUint224()); diff --git a/l1-contracts/test/governance/governance/userlib/sub.tree b/l1-contracts/test/governance/governance/checkpointedUintLib/sub.tree similarity index 100% rename from l1-contracts/test/governance/governance/userlib/sub.tree rename to l1-contracts/test/governance/governance/checkpointedUintLib/sub.tree diff --git a/l1-contracts/test/governance/governance/finaliseWithdraw.t.sol b/l1-contracts/test/governance/governance/finaliseWithdraw.t.sol index e19b9a5a025c..11257076f11f 100644 --- a/l1-contracts/test/governance/governance/finaliseWithdraw.t.sol +++ b/l1-contracts/test/governance/governance/finaliseWithdraw.t.sol @@ -26,12 +26,12 @@ contract FinaliseWithdrawTest is GovernanceBase { // Lot of this is similar to initiateWithdraw.t.sol::test_WhenCallerHaveSufficientDeposits modifier whenItMatchPendingWithdrawal( - uint256 _depositAmount, + uint256 _activationThreshold, address[WITHDRAWAL_COUNT] memory _recipient, uint256[WITHDRAWAL_COUNT] memory _withdrawals, uint256[WITHDRAWAL_COUNT] memory _timejumps ) { - deposit = bound(_depositAmount, 1, type(uint224).max); + deposit = bound(_activationThreshold, 1, type(uint224).max); uint256 sum = deposit; token.mint(address(this), deposit); @@ -59,11 +59,14 @@ contract FinaliseWithdrawTest is GovernanceBase { } function test_GivenWithdrawanAlreadyClaimed( - uint256 _depositAmount, + uint256 _activationThreshold, address[WITHDRAWAL_COUNT] memory _recipient, uint256[WITHDRAWAL_COUNT] memory _withdrawals, uint256[WITHDRAWAL_COUNT] memory _timejumps - ) external whenItMatchPendingWithdrawal(_depositAmount, _recipient, _withdrawals, _timejumps) { + ) + external + whenItMatchPendingWithdrawal(_activationThreshold, _recipient, _withdrawals, _timejumps) + { // it revert uint256 withdrawalCount = governance.withdrawalCount(); @@ -84,14 +87,14 @@ contract FinaliseWithdrawTest is GovernanceBase { } function test_WhenTimeIsBeforeUnlock( - uint256 _depositAmount, + uint256 _activationThreshold, address[WITHDRAWAL_COUNT] memory _recipient, uint256[WITHDRAWAL_COUNT] memory _withdrawals, uint256[WITHDRAWAL_COUNT] memory _timejumps, uint256[WITHDRAWAL_COUNT] memory _timejumps2 ) external - whenItMatchPendingWithdrawal(_depositAmount, _recipient, _withdrawals, _timejumps) + whenItMatchPendingWithdrawal(_activationThreshold, _recipient, _withdrawals, _timejumps) givenWithdrawanNotClaimed { // it revert @@ -121,14 +124,14 @@ contract FinaliseWithdrawTest is GovernanceBase { } function test_WhenTimeIsAfterOrAtUnlock( - uint256 _depositAmount, + uint256 _activationThreshold, address[WITHDRAWAL_COUNT] memory _recipient, uint256[WITHDRAWAL_COUNT] memory _withdrawals, uint256[WITHDRAWAL_COUNT] memory _timejumps, uint256[WITHDRAWAL_COUNT] memory _timejumps2 ) external - whenItMatchPendingWithdrawal(_depositAmount, _recipient, _withdrawals, _timejumps) + whenItMatchPendingWithdrawal(_activationThreshold, _recipient, _withdrawals, _timejumps) givenWithdrawanNotClaimed { // it mark withdrawal as claimed diff --git a/l1-contracts/test/governance/governance/initiateWithdraw.t.sol b/l1-contracts/test/governance/governance/initiateWithdraw.t.sol index ae3bcc4f4e1d..fd0f39c71296 100644 --- a/l1-contracts/test/governance/governance/initiateWithdraw.t.sol +++ b/l1-contracts/test/governance/governance/initiateWithdraw.t.sol @@ -24,29 +24,29 @@ contract InitiateWithdrawTest is GovernanceBase { uint256 amount = bound(_amount, 1, type(uint224).max); vm.expectRevert( abi.encodeWithSelector( - Errors.Governance__InsufficientPower.selector, address(this), 0, amount + Errors.Governance__CheckpointedUintLib__InsufficientValue.selector, address(this), 0, amount ) ); governance.initiateWithdraw(address(this), amount); } - function test_GivenCheckpoints(uint256 _depositAmount, uint256 _withdrawalAmount) + function test_GivenCheckpoints(uint256 _activationThreshold, uint256 _withdrawalAmount) external whenCallerHaveInsufficientDeposits { // it revert - uint256 depositAmount = bound(_depositAmount, 1, type(uint128).max); - uint256 withdrawalAmount = bound(_withdrawalAmount, depositAmount + 1, type(uint224).max); + uint256 activationThreshold = bound(_activationThreshold, 1, type(uint128).max); + uint256 withdrawalAmount = bound(_withdrawalAmount, activationThreshold + 1, type(uint224).max); - token.mint(address(this), depositAmount); - token.approve(address(governance), depositAmount); - governance.deposit(address(this), depositAmount); + token.mint(address(this), activationThreshold); + token.approve(address(governance), activationThreshold); + governance.deposit(address(this), activationThreshold); vm.expectRevert( abi.encodeWithSelector( - Errors.Governance__InsufficientPower.selector, + Errors.Governance__CheckpointedUintLib__InsufficientValue.selector, address(this), - depositAmount, + activationThreshold, withdrawalAmount ) ); @@ -54,7 +54,7 @@ contract InitiateWithdrawTest is GovernanceBase { } function test_WhenCallerHaveSufficientDeposits( - uint256 _depositAmount, + uint256 _activationThreshold, address[WITHDRAWAL_COUNT] memory _recipient, uint256[WITHDRAWAL_COUNT] memory _withdrawals, uint256[WITHDRAWAL_COUNT] memory _timejumps @@ -64,7 +64,7 @@ contract InitiateWithdrawTest is GovernanceBase { // it creates a pending withdrawal with time of unlock // it emits {WithdrawalInitiated} event - uint256 deposit = bound(_depositAmount, 1, type(uint224).max); + uint256 deposit = bound(_activationThreshold, 1, type(uint224).max); uint256 sum = deposit; uint256 withdrawalId = 0; diff --git a/l1-contracts/test/governance/governance/proposeWithLock.t.sol b/l1-contracts/test/governance/governance/proposeWithLock.t.sol index 132ec91c7f62..56490a357714 100644 --- a/l1-contracts/test/governance/governance/proposeWithLock.t.sol +++ b/l1-contracts/test/governance/governance/proposeWithLock.t.sol @@ -18,7 +18,7 @@ contract ProposeWithLockTest is GovernanceBase { Configuration memory config = governance.getConfiguration(); vm.expectRevert( abi.encodeWithSelector( - Errors.Governance__InsufficientPower.selector, + Errors.Governance__CheckpointedUintLib__InsufficientValue.selector, address(this), 0, config.proposeConfig.lockAmount diff --git a/l1-contracts/test/governance/gse/gse/base.sol b/l1-contracts/test/governance/gse/gse/base.sol index fd43c9c473fc..05dd1277e181 100644 --- a/l1-contracts/test/governance/gse/gse/base.sol +++ b/l1-contracts/test/governance/gse/gse/base.sol @@ -17,20 +17,20 @@ contract WithGSE is TestBase { GSEBuilder builder = new GSEBuilder().deploy(); gse = builder.getConfig().gse; vm.label(address(gse), "GSE"); - stakingAsset = TestERC20(address(gse.STAKING_ASSET())); + stakingAsset = TestERC20(address(gse.ASSET())); governance = Governance(address(gse.getGovernance())); } function cheat_deposit(address _instance, address _attester, address _withdrawer, bool _onBonus) public { - uint256 depositAmount = gse.DEPOSIT_AMOUNT(); + uint256 activationThreshold = gse.ACTIVATION_THRESHOLD(); vm.prank(stakingAsset.owner()); - stakingAsset.mint(address(_instance), depositAmount); + stakingAsset.mint(address(_instance), activationThreshold); vm.startPrank(_instance); - stakingAsset.approve(address(gse), depositAmount); + stakingAsset.approve(address(gse), activationThreshold); gse.deposit(_attester, _withdrawer, _onBonus); vm.stopPrank(); } diff --git a/l1-contracts/test/governance/gse/gse/delegate.t.sol b/l1-contracts/test/governance/gse/gse/delegate.t.sol index 90d88ba74870..11aab18af900 100644 --- a/l1-contracts/test/governance/gse/gse/delegate.t.sol +++ b/l1-contracts/test/governance/gse/gse/delegate.t.sol @@ -104,6 +104,6 @@ contract DelegateTest is WithGSE { // Lookup the delegatee assertEq(gse.getDelegatee(addr, _attester), _delegatee); - assertEq(gse.getVotingPower(_delegatee), gse.DEPOSIT_AMOUNT()); + assertEq(gse.getVotingPower(_delegatee), gse.ACTIVATION_THRESHOLD()); } } diff --git a/l1-contracts/test/governance/gse/gse/deposit.t.sol b/l1-contracts/test/governance/gse/gse/deposit.t.sol index f846a2946b94..259c30284ac0 100644 --- a/l1-contracts/test/governance/gse/gse/deposit.t.sol +++ b/l1-contracts/test/governance/gse/gse/deposit.t.sol @@ -58,13 +58,13 @@ contract DepositTest is WithGSE { ) external whenCallerIsRegisteredRollup(_instance) givenOnBonusEqTrue givenCallerIsLatest { // it reverts - uint256 depositAmount = gse.DEPOSIT_AMOUNT(); + uint256 activationThreshold = gse.ACTIVATION_THRESHOLD(); vm.prank(stakingAsset.owner()); - stakingAsset.mint(address(_instance), depositAmount); + stakingAsset.mint(address(_instance), activationThreshold); vm.startPrank(_instance); - stakingAsset.approve(address(gse), depositAmount); + stakingAsset.approve(address(gse), activationThreshold); gse.deposit(_attester, _withdrawer, false); vm.stopPrank(); @@ -82,13 +82,13 @@ contract DepositTest is WithGSE { ) external whenCallerIsRegisteredRollup(_instance) givenOnBonusEqTrue givenCallerIsLatest { // it reverts - uint256 depositAmount = gse.DEPOSIT_AMOUNT(); + uint256 activationThreshold = gse.ACTIVATION_THRESHOLD(); vm.prank(stakingAsset.owner()); - stakingAsset.mint(address(_instance), depositAmount); + stakingAsset.mint(address(_instance), activationThreshold); vm.startPrank(_instance); - stakingAsset.approve(address(gse), depositAmount); + stakingAsset.approve(address(gse), activationThreshold); gse.deposit(_attester, _withdrawer, true); vm.stopPrank(); @@ -115,13 +115,13 @@ contract DepositTest is WithGSE { // it deposits staking asset to governance // it emits Deposit event - uint256 depositAmount = gse.DEPOSIT_AMOUNT(); + uint256 activationThreshold = gse.ACTIVATION_THRESHOLD(); vm.prank(stakingAsset.owner()); - stakingAsset.mint(address(_instance), depositAmount); + stakingAsset.mint(address(_instance), activationThreshold); vm.prank(_instance); - stakingAsset.approve(address(gse), depositAmount); + stakingAsset.approve(address(gse), activationThreshold); assertEq(gse.isRegistered(_instance, _attester), false); assertEq(gse.isRegistered(gse.BONUS_INSTANCE_ADDRESS(), _attester), false); @@ -133,7 +133,7 @@ contract DepositTest is WithGSE { vm.prank(_instance); gse.deposit(_attester, _withdrawer, onBonus); - assertEq(stakingAsset.balanceOf(address(gse.getGovernance())), depositAmount); + assertEq(stakingAsset.balanceOf(address(gse.getGovernance())), activationThreshold); assertEq(stakingAsset.balanceOf(address(gse)), 0); assertEq(gse.isRegistered(instance, _attester), true); @@ -141,13 +141,13 @@ contract DepositTest is WithGSE { assertEq(gse.getDelegatee(instance, _attester), gse.BONUS_INSTANCE_ADDRESS()); assertEq(gse.getDelegatee(_instance, _attester), address(0)); assertEq(gse.getConfig(instance, _attester).withdrawer, _withdrawer); - assertEq(gse.balanceOf(instance, _attester), depositAmount); + assertEq(gse.balanceOf(instance, _attester), activationThreshold); assertEq(gse.balanceOf(_instance, _attester), 0); - assertEq(gse.effectiveBalanceOf(instance, _attester), depositAmount); - assertEq(gse.effectiveBalanceOf(_instance, _attester), depositAmount); - assertEq(gse.supplyOf(instance), depositAmount); + assertEq(gse.effectiveBalanceOf(instance, _attester), activationThreshold); + assertEq(gse.effectiveBalanceOf(_instance, _attester), activationThreshold); + assertEq(gse.supplyOf(instance), activationThreshold); assertEq(gse.supplyOf(_instance), 0); - assertEq(gse.totalSupply(), depositAmount); + assertEq(gse.totalSupply(), activationThreshold); } modifier givenOnBonusEqFalse() { @@ -166,13 +166,13 @@ contract DepositTest is WithGSE { // the only diff is `onBonus = false` here. We could consider slamming them together, but to be // explicit we are not doing that. - uint256 depositAmount = gse.DEPOSIT_AMOUNT(); + uint256 activationThreshold = gse.ACTIVATION_THRESHOLD(); vm.prank(stakingAsset.owner()); - stakingAsset.mint(address(_instance), depositAmount); + stakingAsset.mint(address(_instance), activationThreshold); vm.startPrank(_instance); - stakingAsset.approve(address(gse), depositAmount); + stakingAsset.approve(address(gse), activationThreshold); gse.deposit(_attester, _withdrawer, false); vm.stopPrank(); @@ -192,13 +192,13 @@ contract DepositTest is WithGSE { // Again, this one is essentially same as test_GivenAttesterAlreadyRegisteredOnBonus but with false. - uint256 depositAmount = gse.DEPOSIT_AMOUNT(); + uint256 activationThreshold = gse.ACTIVATION_THRESHOLD(); vm.prank(stakingAsset.owner()); - stakingAsset.mint(address(_instance), depositAmount); + stakingAsset.mint(address(_instance), activationThreshold); vm.startPrank(_instance); - stakingAsset.approve(address(gse), depositAmount); + stakingAsset.approve(address(gse), activationThreshold); gse.deposit(_attester, _withdrawer, true); vm.stopPrank(); @@ -234,13 +234,13 @@ contract DepositTest is WithGSE { // it deposits staking asset to governance // it emits Deposit event - uint256 depositAmount = gse.DEPOSIT_AMOUNT(); + uint256 activationThreshold = gse.ACTIVATION_THRESHOLD(); vm.prank(stakingAsset.owner()); - stakingAsset.mint(address(_instance), depositAmount); + stakingAsset.mint(address(_instance), activationThreshold); vm.prank(_instance); - stakingAsset.approve(address(gse), depositAmount); + stakingAsset.approve(address(gse), activationThreshold); address bonus = gse.BONUS_INSTANCE_ADDRESS(); @@ -252,7 +252,7 @@ contract DepositTest is WithGSE { vm.prank(_instance); gse.deposit(_attester, _withdrawer, onBonus); - assertEq(stakingAsset.balanceOf(address(gse.getGovernance())), depositAmount); + assertEq(stakingAsset.balanceOf(address(gse.getGovernance())), activationThreshold); assertEq(stakingAsset.balanceOf(address(gse)), 0); assertEq(gse.isRegistered(_instance, _attester), true); @@ -260,13 +260,13 @@ contract DepositTest is WithGSE { assertEq(gse.getDelegatee(_instance, _attester), _instance); assertEq(gse.getDelegatee(bonus, _attester), address(0)); assertEq(gse.getConfig(_instance, _attester).withdrawer, _withdrawer); - assertEq(gse.balanceOf(_instance, _attester), depositAmount); + assertEq(gse.balanceOf(_instance, _attester), activationThreshold); assertEq(gse.balanceOf(bonus, _attester), 0); - assertEq(gse.effectiveBalanceOf(_instance, _attester), depositAmount); + assertEq(gse.effectiveBalanceOf(_instance, _attester), activationThreshold); assertEq(gse.effectiveBalanceOf(bonus, _attester), 0); // special case - assertEq(gse.supplyOf(_instance), depositAmount); + assertEq(gse.supplyOf(_instance), activationThreshold); assertEq(gse.supplyOf(bonus), 0); - assertEq(gse.totalSupply(), depositAmount); + assertEq(gse.totalSupply(), activationThreshold); } function test_GivenCallerIsNotLatest2( @@ -292,13 +292,13 @@ contract DepositTest is WithGSE { // @todo exactly the same as above, with only diff being not latest - uint256 depositAmount = gse.DEPOSIT_AMOUNT(); + uint256 activationThreshold = gse.ACTIVATION_THRESHOLD(); vm.prank(stakingAsset.owner()); - stakingAsset.mint(address(_instance), depositAmount); + stakingAsset.mint(address(_instance), activationThreshold); vm.prank(_instance); - stakingAsset.approve(address(gse), depositAmount); + stakingAsset.approve(address(gse), activationThreshold); address bonus = gse.BONUS_INSTANCE_ADDRESS(); @@ -310,7 +310,7 @@ contract DepositTest is WithGSE { vm.prank(_instance); gse.deposit(_attester, _withdrawer, onBonus); - assertEq(stakingAsset.balanceOf(address(gse.getGovernance())), depositAmount); + assertEq(stakingAsset.balanceOf(address(gse.getGovernance())), activationThreshold); assertEq(stakingAsset.balanceOf(address(gse)), 0); assertEq(gse.isRegistered(_instance, _attester), true); @@ -318,12 +318,12 @@ contract DepositTest is WithGSE { assertEq(gse.getDelegatee(_instance, _attester), _instance); assertEq(gse.getDelegatee(bonus, _attester), address(0)); assertEq(gse.getConfig(_instance, _attester).withdrawer, _withdrawer); - assertEq(gse.balanceOf(_instance, _attester), depositAmount); + assertEq(gse.balanceOf(_instance, _attester), activationThreshold); assertEq(gse.balanceOf(bonus, _attester), 0); - assertEq(gse.effectiveBalanceOf(_instance, _attester), depositAmount); + assertEq(gse.effectiveBalanceOf(_instance, _attester), activationThreshold); assertEq(gse.effectiveBalanceOf(bonus, _attester), 0); // special case - assertEq(gse.supplyOf(_instance), depositAmount); + assertEq(gse.supplyOf(_instance), activationThreshold); assertEq(gse.supplyOf(bonus), 0); - assertEq(gse.totalSupply(), depositAmount); + assertEq(gse.totalSupply(), activationThreshold); } } diff --git a/l1-contracts/test/governance/gse/gse/finaliseHelper.t.sol b/l1-contracts/test/governance/gse/gse/finaliseWithdraw.t.sol similarity index 90% rename from l1-contracts/test/governance/gse/gse/finaliseHelper.t.sol rename to l1-contracts/test/governance/gse/gse/finaliseWithdraw.t.sol index 6b0767b8f8f3..25dfa5747238 100644 --- a/l1-contracts/test/governance/gse/gse/finaliseHelper.t.sol +++ b/l1-contracts/test/governance/gse/gse/finaliseWithdraw.t.sol @@ -5,7 +5,7 @@ import {WithGSE} from "./base.sol"; import {Withdrawal} from "@aztec/governance/interfaces/IGovernance.sol"; import {Timestamp} from "@aztec/shared/libraries/TimeMath.sol"; -contract FinaliseHelperTest is WithGSE { +contract FinaliseWithdrawTest is WithGSE { uint256 internal withdrawalId; address internal ATTESTER = address(0xcafe); @@ -33,7 +33,7 @@ contract FinaliseHelperTest is WithGSE { assertEq(stakingAsset.balanceOf(INSTANCE), 0); - gse.finaliseHelper(withdrawalId); + gse.finaliseWithdraw(withdrawalId); assertEq(stakingAsset.balanceOf(INSTANCE), 100); withdrawal = governance.getWithdrawal(withdrawalId); @@ -47,14 +47,14 @@ contract FinaliseHelperTest is WithGSE { vm.warp(Timestamp.unwrap(withdrawal.unlocksAt)); assertEq(stakingAsset.balanceOf(INSTANCE), 0); - gse.finaliseHelper(withdrawalId); + gse.finaliseWithdraw(withdrawalId); assertEq(stakingAsset.balanceOf(INSTANCE), 100); withdrawal = governance.getWithdrawal(withdrawalId); assertEq(withdrawal.claimed, true); vm.record(); - gse.finaliseHelper(withdrawalId); + gse.finaliseWithdraw(withdrawalId); (, bytes32[] memory writes) = vm.accesses(address(gse)); assertEq(writes.length, 0); } diff --git a/l1-contracts/test/governance/gse/gse/finaliseHelper.tree b/l1-contracts/test/governance/gse/gse/finaliseWithdraw.tree similarity index 88% rename from l1-contracts/test/governance/gse/gse/finaliseHelper.tree rename to l1-contracts/test/governance/gse/gse/finaliseWithdraw.tree index 032fb1018a07..5df41848f900 100644 --- a/l1-contracts/test/governance/gse/gse/finaliseHelper.tree +++ b/l1-contracts/test/governance/gse/gse/finaliseWithdraw.tree @@ -1,4 +1,4 @@ -FinaliseHelperTest +FinaliseWithdrawTest ├── given withdrawal not claimed │ └── it finalises withdrawal in governance └── given withdrawal already claimed diff --git a/l1-contracts/test/governance/gse/gse/setGovernance.t.sol b/l1-contracts/test/governance/gse/gse/setGovernance.t.sol index 3c766695b631..c9fc01699e11 100644 --- a/l1-contracts/test/governance/gse/gse/setGovernance.t.sol +++ b/l1-contracts/test/governance/gse/gse/setGovernance.t.sol @@ -14,7 +14,10 @@ contract SetGovernanceTest is WithGSE { function setUp() public override(WithGSE) { gse = new GSE( - address(this), IERC20(address(0)), TestConstants.DEPOSIT_AMOUNT, TestConstants.MINIMUM_STAKE + address(this), + IERC20(address(0)), + TestConstants.ACTIVATION_THRESHOLD, + TestConstants.EJECTION_THRESHOLD ); } diff --git a/l1-contracts/test/governance/gse/gse/static.t.sol b/l1-contracts/test/governance/gse/gse/static.t.sol index 7079ac23a3b0..6dd6722fd5fa 100644 --- a/l1-contracts/test/governance/gse/gse/static.t.sol +++ b/l1-contracts/test/governance/gse/gse/static.t.sol @@ -66,7 +66,7 @@ contract StaticTest is WithGSE { cheat_deposit(_instance, _attester, _attester, false); assertEq(gse.getVotingPower(_attester), 0, "invalid voting power"); - assertEq(gse.getVotingPower(_instance), gse.DEPOSIT_AMOUNT(), "invalid voting power"); + assertEq(gse.getVotingPower(_instance), gse.ACTIVATION_THRESHOLD(), "invalid voting power"); } function test_getAttesterFromIndexAtTime(address _instance, address[4] memory _attesters) diff --git a/l1-contracts/test/governance/gse/gse/withdraw.t.sol b/l1-contracts/test/governance/gse/gse/withdraw.t.sol index ee76fd5e917d..fd60c55501d3 100644 --- a/l1-contracts/test/governance/gse/gse/withdraw.t.sol +++ b/l1-contracts/test/governance/gse/gse/withdraw.t.sol @@ -111,7 +111,9 @@ contract WithdrawTest is WithGSE { amount = bound(_amount, balance + 1, type(uint256).max); vm.prank(_instance); - vm.expectRevert(abi.encodeWithSelector(Errors.GSE__InsufficientStake.selector, balance, amount)); + vm.expectRevert( + abi.encodeWithSelector(Errors.GSE__InsufficientBalance.selector, balance, amount) + ); gse.withdraw(_attester, amount); } @@ -121,7 +123,7 @@ contract WithdrawTest is WithGSE { _; } - function test_GivenBalanceMinusAmountLessThanMinimumStake( + function test_GivenBalanceMinusAmountLessThanejectionThreshold( address _instance, address _attester, uint256 _amount @@ -146,7 +148,7 @@ contract WithdrawTest is WithGSE { assertEq(gse.getDelegatee(BONUS_ADDRESS, _attester), BONUS_ADDRESS); assertEq(gse.getConfig(BONUS_ADDRESS, _attester).withdrawer, WITHDRAWER); - amount = bound(_amount, balance - gse.MINIMUM_STAKE() + 1, balance); + amount = bound(_amount, balance - gse.EJECTION_THRESHOLD() + 1, balance); } // He will be removed entirely @@ -172,7 +174,7 @@ contract WithdrawTest is WithGSE { } } - function test_GivenBalanceMinusAmountGreaterOrEqualToMinimumStake( + function test_GivenBalanceMinusAmountGreaterOrEqualToejectionThreshold( address _instance, address _attester, uint256 _amount @@ -195,7 +197,7 @@ contract WithdrawTest is WithGSE { assertEq(gse.getDelegatee(BONUS_ADDRESS, _attester), BONUS_ADDRESS); assertEq(gse.getConfig(BONUS_ADDRESS, _attester).withdrawer, WITHDRAWER); - amount = bound(_amount, 0, balance - gse.MINIMUM_STAKE()); + amount = bound(_amount, 0, balance - gse.EJECTION_THRESHOLD()); } // He will not be removed @@ -242,7 +244,9 @@ contract WithdrawTest is WithGSE { amount = bound(_amount, balance + 1, type(uint256).max); vm.prank(_instance); - vm.expectRevert(abi.encodeWithSelector(Errors.GSE__InsufficientStake.selector, balance, amount)); + vm.expectRevert( + abi.encodeWithSelector(Errors.GSE__InsufficientBalance.selector, balance, amount) + ); gse.withdraw(_attester, amount); } @@ -257,7 +261,7 @@ contract WithdrawTest is WithGSE { _; } - function test_GivenBalanceMinusAmountLessThanMinimumStake2( + function test_GivenBalanceMinusAmountLessThanejectionThreshold2( address _instance, address _attester, uint256 _amount @@ -281,7 +285,7 @@ contract WithdrawTest is WithGSE { assertEq(gse.getDelegatee(_instance, _attester), _instance); assertEq(gse.getConfig(_instance, _attester).withdrawer, WITHDRAWER); - amount = bound(_amount, balance - gse.MINIMUM_STAKE() + 1, balance); + amount = bound(_amount, balance - gse.EJECTION_THRESHOLD() + 1, balance); } // He will be removed entirely @@ -307,7 +311,7 @@ contract WithdrawTest is WithGSE { } } - function test_GivenBalanceMinusAmountGreaterOrEqualToMinimumStake2( + function test_GivenBalanceMinusAmountGreaterOrEqualToejectionThreshold2( address _instance, address _attester, uint256 _amount @@ -328,7 +332,7 @@ contract WithdrawTest is WithGSE { assertEq(gse.getDelegatee(_instance, _attester), _instance); assertEq(gse.getConfig(_instance, _attester).withdrawer, WITHDRAWER); - amount = bound(_amount, 0, balance - gse.MINIMUM_STAKE()); + amount = bound(_amount, 0, balance - gse.EJECTION_THRESHOLD()); } // He will not be removed diff --git a/l1-contracts/test/governance/gse/delegationlib/DelegationLibWrapper.sol b/l1-contracts/test/governance/gse/stakedelegationlib/StakeDelegationLibWrapper.sol similarity index 86% rename from l1-contracts/test/governance/gse/delegationlib/DelegationLibWrapper.sol rename to l1-contracts/test/governance/gse/stakedelegationlib/StakeDelegationLibWrapper.sol index c0b67978ae3b..a1181a18c486 100644 --- a/l1-contracts/test/governance/gse/delegationlib/DelegationLibWrapper.sol +++ b/l1-contracts/test/governance/gse/stakedelegationlib/StakeDelegationLibWrapper.sol @@ -2,13 +2,16 @@ // Copyright 2024 Aztec Labs. pragma solidity >=0.8.27; -import {DelegationLib, DelegationData} from "@aztec/governance/libraries/DelegationLib.sol"; +import { + DepositDelegationLib, + DepositAndDelegationAccounting +} from "@aztec/governance/libraries/DepositDelegationLib.sol"; import {Timestamp} from "@aztec/shared/libraries/TimeMath.sol"; -contract DelegationLibWrapper { - using DelegationLib for DelegationData; +contract StakeDelegationLibWrapper { + using DepositDelegationLib for DepositAndDelegationAccounting; - DelegationData internal self; + DepositAndDelegationAccounting internal self; function increaseBalance(address _instance, address _attester, uint256 _amount) external { self.increaseBalance(_instance, _attester, _amount); diff --git a/l1-contracts/test/governance/gse/delegationlib/base.sol b/l1-contracts/test/governance/gse/stakedelegationlib/base.sol similarity index 85% rename from l1-contracts/test/governance/gse/delegationlib/base.sol rename to l1-contracts/test/governance/gse/stakedelegationlib/base.sol index e612a0e9003d..4cb376f2247c 100644 --- a/l1-contracts/test/governance/gse/delegationlib/base.sol +++ b/l1-contracts/test/governance/gse/stakedelegationlib/base.sol @@ -3,10 +3,10 @@ pragma solidity >=0.8.27; import {Test} from "forge-std/Test.sol"; -import {DelegationLibWrapper} from "./DelegationLibWrapper.sol"; +import {StakeDelegationLibWrapper} from "./StakeDelegationLibWrapper.sol"; contract WithDelegationLib is Test { - DelegationLibWrapper internal delegationLib = new DelegationLibWrapper(); + StakeDelegationLibWrapper internal delegationLib = new StakeDelegationLibWrapper(); /** * @notice A helper function to assert the number of writes performed diff --git a/l1-contracts/test/governance/gse/delegationlib/decreaseBalance.t.sol b/l1-contracts/test/governance/gse/stakedelegationlib/decreaseBalance.t.sol similarity index 100% rename from l1-contracts/test/governance/gse/delegationlib/decreaseBalance.t.sol rename to l1-contracts/test/governance/gse/stakedelegationlib/decreaseBalance.t.sol diff --git a/l1-contracts/test/governance/gse/delegationlib/decreaseBalance.tree b/l1-contracts/test/governance/gse/stakedelegationlib/decreaseBalance.tree similarity index 100% rename from l1-contracts/test/governance/gse/delegationlib/decreaseBalance.tree rename to l1-contracts/test/governance/gse/stakedelegationlib/decreaseBalance.tree diff --git a/l1-contracts/test/governance/gse/delegationlib/delegate.t.sol b/l1-contracts/test/governance/gse/stakedelegationlib/delegate.t.sol similarity index 98% rename from l1-contracts/test/governance/gse/delegationlib/delegate.t.sol rename to l1-contracts/test/governance/gse/stakedelegationlib/delegate.t.sol index a580c0308646..078f8f604dd9 100644 --- a/l1-contracts/test/governance/gse/delegationlib/delegate.t.sol +++ b/l1-contracts/test/governance/gse/stakedelegationlib/delegate.t.sol @@ -3,7 +3,7 @@ pragma solidity >=0.8.27; import {Test} from "forge-std/Test.sol"; -import {DelegationLibWrapper} from "./DelegationLibWrapper.sol"; +import {StakeDelegationLibWrapper} from "./StakeDelegationLibWrapper.sol"; import {WithDelegationLib} from "./base.sol"; diff --git a/l1-contracts/test/governance/gse/delegationlib/delegate.tree b/l1-contracts/test/governance/gse/stakedelegationlib/delegate.tree similarity index 100% rename from l1-contracts/test/governance/gse/delegationlib/delegate.tree rename to l1-contracts/test/governance/gse/stakedelegationlib/delegate.tree diff --git a/l1-contracts/test/governance/gse/delegationlib/increaseBalance.t.sol b/l1-contracts/test/governance/gse/stakedelegationlib/increaseBalance.t.sol similarity index 100% rename from l1-contracts/test/governance/gse/delegationlib/increaseBalance.t.sol rename to l1-contracts/test/governance/gse/stakedelegationlib/increaseBalance.t.sol diff --git a/l1-contracts/test/governance/gse/delegationlib/increaseBalance.tree b/l1-contracts/test/governance/gse/stakedelegationlib/increaseBalance.tree similarity index 100% rename from l1-contracts/test/governance/gse/delegationlib/increaseBalance.tree rename to l1-contracts/test/governance/gse/stakedelegationlib/increaseBalance.tree diff --git a/l1-contracts/test/governance/gse/delegationlib/usePower.t.sol b/l1-contracts/test/governance/gse/stakedelegationlib/usePower.t.sol similarity index 95% rename from l1-contracts/test/governance/gse/delegationlib/usePower.t.sol rename to l1-contracts/test/governance/gse/stakedelegationlib/usePower.t.sol index a7eb0b9941ca..75a78f7ed5fe 100644 --- a/l1-contracts/test/governance/gse/delegationlib/usePower.t.sol +++ b/l1-contracts/test/governance/gse/stakedelegationlib/usePower.t.sol @@ -6,10 +6,10 @@ import {Timestamp} from "@aztec/shared/libraries/TimeMath.sol"; import {Test} from "forge-std/Test.sol"; import {Errors} from "@aztec/governance/libraries/Errors.sol"; -import {DelegationLibWrapper} from "./DelegationLibWrapper.sol"; +import {StakeDelegationLibWrapper} from "./StakeDelegationLibWrapper.sol"; contract UsePowerTest is Test { - DelegationLibWrapper internal delegationLib = new DelegationLibWrapper(); + StakeDelegationLibWrapper internal delegationLib = new StakeDelegationLibWrapper(); function test_GivenPowerUsedPlusAmountGtPowerAt( address _delegatee, diff --git a/l1-contracts/test/governance/gse/delegationlib/usePower.tree b/l1-contracts/test/governance/gse/stakedelegationlib/usePower.tree similarity index 100% rename from l1-contracts/test/governance/gse/delegationlib/usePower.tree rename to l1-contracts/test/governance/gse/stakedelegationlib/usePower.tree diff --git a/l1-contracts/test/governance/scenario/AddRollup.t.sol b/l1-contracts/test/governance/scenario/AddRollup.t.sol index ae8fff215e5c..e5841075f47e 100644 --- a/l1-contracts/test/governance/scenario/AddRollup.t.sol +++ b/l1-contracts/test/governance/scenario/AddRollup.t.sol @@ -93,9 +93,9 @@ contract AddRollupTest is TestBase { } MultiAdder multiAdder = new MultiAdder(address(rollup), address(this)); - uint256 depositAmount = rollup.getDepositAmount(); + uint256 activationThreshold = rollup.getActivationThreshold(); vm.prank(token.owner()); - token.mint(address(multiAdder), depositAmount * VALIDATOR_COUNT); + token.mint(address(multiAdder), activationThreshold * VALIDATOR_COUNT); multiAdder.addValidators(initialValidators); registry.transferOwnership(address(governance)); @@ -153,13 +153,13 @@ contract AddRollupTest is TestBase { // We need 1/3 of the total supply to be off canonical // So we add 1/2 of the initial supply to the specific instance // The result is that 1/3 of the new total supply is off canonical - uint256 validatorsNeeded = (gse.totalSupply() / 2) / rollup.getDepositAmount() + 1; + uint256 validatorsNeeded = (gse.totalSupply() / 2) / rollup.getActivationThreshold() + 1; - uint256 depositAmount = rollup.getDepositAmount(); + uint256 activationThreshold = rollup.getActivationThreshold(); while (val <= validatorsNeeded) { vm.prank(token.owner()); - token.mint(address(this), depositAmount); - token.approve(address(rollup), depositAmount); + token.mint(address(this), activationThreshold); + token.approve(address(rollup), activationThreshold); rollup.deposit(address(uint160(val)), address(this), false); val++; } diff --git a/l1-contracts/test/harnesses/TestConstants.sol b/l1-contracts/test/harnesses/TestConstants.sol index 637b8f3fe13c..8c0085aaef0d 100644 --- a/l1-contracts/test/harnesses/TestConstants.sol +++ b/l1-contracts/test/harnesses/TestConstants.sol @@ -36,8 +36,8 @@ library TestConstants { uint256 internal constant AZTEC_EXIT_DELAY_SECONDS = 2 * 24 * 60 * 60; // 2 days EthValue internal constant AZTEC_PROVING_COST_PER_MANA = EthValue.wrap(100); - uint256 internal constant DEPOSIT_AMOUNT = 100e18; - uint256 internal constant MINIMUM_STAKE = 50e18; + uint256 internal constant ACTIVATION_THRESHOLD = 100e18; + uint256 internal constant EJECTION_THRESHOLD = 50e18; // Genesis state bytes32 internal constant GENESIS_ARCHIVE_ROOT = bytes32(Constants.GENESIS_ARCHIVE_ROOT); diff --git a/l1-contracts/test/staking/15050.t.sol b/l1-contracts/test/staking/15050.t.sol index c9656fb92910..9d057301dfb3 100644 --- a/l1-contracts/test/staking/15050.t.sol +++ b/l1-contracts/test/staking/15050.t.sol @@ -23,8 +23,8 @@ contract Test15050 is StakingBase { function test_15050() external { vm.prank(stakingAsset.owner()); - stakingAsset.mint(address(this), DEPOSIT_AMOUNT); - stakingAsset.approve(address(staking), DEPOSIT_AMOUNT); + stakingAsset.mint(address(this), ACTIVATION_THRESHOLD); + stakingAsset.approve(address(staking), ACTIVATION_THRESHOLD); staking.deposit({_attester: ATTESTER, _withdrawer: WITHDRAWER, _moveWithLatestRollup: true}); staking.flushEntryQueue(); @@ -32,11 +32,11 @@ contract Test15050 is StakingBase { address[] memory validators = new address[](1); validators[0] = ATTESTER; uint96[] memory amounts = new uint96[](1); - amounts[0] = uint96(DEPOSIT_AMOUNT); + amounts[0] = uint96(ACTIVATION_THRESHOLD); AttesterView memory attesterView = staking.getAttesterView(ATTESTER); assertTrue(attesterView.status == Status.VALIDATING); - assertEq(attesterView.effectiveBalance, DEPOSIT_AMOUNT); + assertEq(attesterView.effectiveBalance, ACTIVATION_THRESHOLD); assertEq(attesterView.exit.amount, 0); assertEq(attesterView.exit.exitableAt, 0); assertEq(attesterView.exit.isRecipient, false); @@ -83,7 +83,7 @@ contract Test15050 is StakingBase { attesterView = staking.getAttesterView(ATTESTER); assertTrue(attesterView.status == Status.VALIDATING); - assertEq(attesterView.effectiveBalance, DEPOSIT_AMOUNT); + assertEq(attesterView.effectiveBalance, ACTIVATION_THRESHOLD); assertEq(attesterView.exit.amount, 0); assertEq(attesterView.exit.exitableAt, 0); assertEq(attesterView.exit.isRecipient, false); diff --git a/l1-contracts/test/staking/base.t.sol b/l1-contracts/test/staking/base.t.sol index a97d65bf13ca..c50339be38c9 100644 --- a/l1-contracts/test/staking/base.t.sol +++ b/l1-contracts/test/staking/base.t.sol @@ -17,8 +17,8 @@ contract StakingBase is TestBase { address internal constant WITHDRAWER = address(bytes20("WITHDRAWER")); address internal constant RECIPIENT = address(bytes20("RECIPIENT")); - uint256 internal DEPOSIT_AMOUNT; - uint256 internal MINIMUM_STAKE; + uint256 internal ACTIVATION_THRESHOLD; + uint256 internal EJECTION_THRESHOLD; uint256 internal EPOCH_DURATION_SECONDS; @@ -38,8 +38,8 @@ contract StakingBase is TestBase { staking = IStaking(address(builder.getConfig().rollup)); stakingAsset = builder.getConfig().testERC20; - DEPOSIT_AMOUNT = staking.getDepositAmount(); - MINIMUM_STAKE = staking.getMinimumStake(); + ACTIVATION_THRESHOLD = staking.getActivationThreshold(); + EJECTION_THRESHOLD = staking.getEjectionThreshold(); SLASHER = staking.getSlasher(); } diff --git a/l1-contracts/test/staking/deposit.t.sol b/l1-contracts/test/staking/deposit.t.sol index fdb11d2313bb..27c848765aff 100644 --- a/l1-contracts/test/staking/deposit.t.sol +++ b/l1-contracts/test/staking/deposit.t.sol @@ -24,7 +24,7 @@ contract DepositTest is StakingBase { vm.expectRevert( abi.encodeWithSelector( - IERC20Errors.ERC20InsufficientAllowance.selector, address(staking), 0, DEPOSIT_AMOUNT + IERC20Errors.ERC20InsufficientAllowance.selector, address(staking), 0, ACTIVATION_THRESHOLD ) ); @@ -32,7 +32,7 @@ contract DepositTest is StakingBase { } modifier givenCallerHasSufficientAllowance() { - stakingAsset.approve(address(staking), DEPOSIT_AMOUNT); + stakingAsset.approve(address(staking), ACTIVATION_THRESHOLD); _; } @@ -41,7 +41,7 @@ contract DepositTest is StakingBase { vm.expectRevert( abi.encodeWithSelector( - IERC20Errors.ERC20InsufficientBalance.selector, address(this), 0, DEPOSIT_AMOUNT + IERC20Errors.ERC20InsufficientBalance.selector, address(this), 0, ACTIVATION_THRESHOLD ) ); @@ -49,7 +49,7 @@ contract DepositTest is StakingBase { } modifier givenCallerHasSufficientFunds() { - mint(address(this), DEPOSIT_AMOUNT); + mint(address(this), ACTIVATION_THRESHOLD); _; } @@ -63,7 +63,7 @@ contract DepositTest is StakingBase { staking.deposit({_attester: ATTESTER, _withdrawer: WITHDRAWER, _moveWithLatestRollup: true}); staking.flushEntryQueue(); - mint(address(this), DEPOSIT_AMOUNT); + mint(address(this), ACTIVATION_THRESHOLD); stakingAsset.approve(address(staking), type(uint256).max); // Now reset the next flushable epoch to 0 @@ -82,7 +82,7 @@ contract DepositTest is StakingBase { staking.flushEntryQueue(); vm.prank(SLASHER); - staking.slash(ATTESTER, DEPOSIT_AMOUNT - MINIMUM_STAKE + 1); + staking.slash(ATTESTER, ACTIVATION_THRESHOLD - EJECTION_THRESHOLD + 1); assertEq(uint256(staking.getStatus(ATTESTER)), uint256(Status.ZOMBIE)); vm.expectRevert(abi.encodeWithSelector(Errors.Staking__AlreadyExiting.selector, ATTESTER)); @@ -124,7 +124,7 @@ contract DepositTest is StakingBase { staking.deposit({_attester: ATTESTER, _withdrawer: WITHDRAWER, _moveWithLatestRollup: true}); // the money is in the staking contract - assertEq(stakingAsset.balanceOf(address(staking)), DEPOSIT_AMOUNT); + assertEq(stakingAsset.balanceOf(address(staking)), ACTIVATION_THRESHOLD); // the money is not in the GSE assertEq(stakingAsset.balanceOf(address(staking.getGSE())), 0); // nor in governance diff --git a/l1-contracts/test/staking/finaliseWithdraw.t.sol b/l1-contracts/test/staking/finaliseWithdraw.t.sol index b4ab414159c4..b63afc53fc0f 100644 --- a/l1-contracts/test/staking/finaliseWithdraw.t.sol +++ b/l1-contracts/test/staking/finaliseWithdraw.t.sol @@ -13,8 +13,8 @@ contract FinaliseWithdrawTest is StakingBase { vm.expectRevert(abi.encodeWithSelector(Errors.Staking__NotExiting.selector, ATTESTER)); staking.finaliseWithdraw(ATTESTER); - mint(address(this), DEPOSIT_AMOUNT); - stakingAsset.approve(address(staking), DEPOSIT_AMOUNT); + mint(address(this), ACTIVATION_THRESHOLD); + stakingAsset.approve(address(staking), ACTIVATION_THRESHOLD); staking.deposit({_attester: ATTESTER, _withdrawer: WITHDRAWER, _moveWithLatestRollup: true}); staking.flushEntryQueue(); @@ -23,7 +23,7 @@ contract FinaliseWithdrawTest is StakingBase { staking.finaliseWithdraw(ATTESTER); vm.prank(SLASHER); - staking.slash(ATTESTER, DEPOSIT_AMOUNT); + staking.slash(ATTESTER, ACTIVATION_THRESHOLD); vm.expectRevert(abi.encodeWithSelector(Errors.Staking__NotExiting.selector, ATTESTER)); staking.finaliseWithdraw(ATTESTER); @@ -32,8 +32,8 @@ contract FinaliseWithdrawTest is StakingBase { modifier givenStatusIsExiting() { // We deposit and initiate a withdraw - mint(address(this), DEPOSIT_AMOUNT); - stakingAsset.approve(address(staking), DEPOSIT_AMOUNT); + mint(address(this), ACTIVATION_THRESHOLD); + stakingAsset.approve(address(staking), ACTIVATION_THRESHOLD); staking.deposit({_attester: ATTESTER, _withdrawer: WITHDRAWER, _moveWithLatestRollup: true}); staking.flushEntryQueue(); @@ -77,11 +77,11 @@ contract FinaliseWithdrawTest is StakingBase { address lookup = _claimedFromGov ? address(staking) : address(staking.getGSE().getGovernance()); - assertEq(stakingAsset.balanceOf(lookup), DEPOSIT_AMOUNT); + assertEq(stakingAsset.balanceOf(lookup), ACTIVATION_THRESHOLD); assertEq(stakingAsset.balanceOf(RECIPIENT), 0); vm.expectEmit(true, true, true, true, address(staking)); - emit IStakingCore.WithdrawFinalised(ATTESTER, RECIPIENT, DEPOSIT_AMOUNT); + emit IStakingCore.WithdrawFinalised(ATTESTER, RECIPIENT, ACTIVATION_THRESHOLD); staking.finaliseWithdraw(ATTESTER); attesterView = staking.getAttesterView(ATTESTER); @@ -90,6 +90,6 @@ contract FinaliseWithdrawTest is StakingBase { assertTrue(attesterView.status == Status.NONE); assertEq(stakingAsset.balanceOf(lookup), 0); - assertEq(stakingAsset.balanceOf(RECIPIENT), DEPOSIT_AMOUNT); + assertEq(stakingAsset.balanceOf(RECIPIENT), ACTIVATION_THRESHOLD); } } diff --git a/l1-contracts/test/staking/flushEntryQueue.t.sol b/l1-contracts/test/staking/flushEntryQueue.t.sol index 5129d63d9f65..f8e6da4234a8 100644 --- a/l1-contracts/test/staking/flushEntryQueue.t.sol +++ b/l1-contracts/test/staking/flushEntryQueue.t.sol @@ -200,8 +200,8 @@ contract FlushEntryQueueTest is StakingBase { function _help_deposit(address _attester, address _withdrawer, bool _moveWithLatestRollup) internal { - mint(address(this), DEPOSIT_AMOUNT); - stakingAsset.approve(address(staking), DEPOSIT_AMOUNT); + mint(address(this), ACTIVATION_THRESHOLD); + stakingAsset.approve(address(staking), ACTIVATION_THRESHOLD); uint256 balance = stakingAsset.balanceOf(address(staking)); staking.deposit({ @@ -210,7 +210,9 @@ contract FlushEntryQueueTest is StakingBase { _moveWithLatestRollup: _moveWithLatestRollup }); - assertEq(stakingAsset.balanceOf(address(staking)), balance + DEPOSIT_AMOUNT, "invalid balance"); + assertEq( + stakingAsset.balanceOf(address(staking)), balance + ACTIVATION_THRESHOLD, "invalid balance" + ); } function _help_flushEntryQueue(uint256 _numValidators, uint256 _expectedFlushSize) internal { @@ -233,7 +235,9 @@ contract FlushEntryQueueTest is StakingBase { "depositors should not be active" ); assertEq( - stakingAsset.balanceOf(address(staking)), _numValidators * DEPOSIT_AMOUNT, "invalid balance" + stakingAsset.balanceOf(address(staking)), + _numValidators * ACTIVATION_THRESHOLD, + "invalid balance" ); uint256 flushSize = staking.getEntryQueueFlushSize(); @@ -262,7 +266,7 @@ contract FlushEntryQueueTest is StakingBase { } depositCount++; vm.expectEmit(true, true, true, true); - emit IStakingCore.Deposit(attester, withdrawer, DEPOSIT_AMOUNT); + emit IStakingCore.Deposit(attester, withdrawer, ACTIVATION_THRESHOLD); } } @@ -278,20 +282,20 @@ contract FlushEntryQueueTest is StakingBase { assertEq( stakingAsset.balanceOf(address(staking)), - numStillInQueue * DEPOSIT_AMOUNT, + numStillInQueue * ACTIVATION_THRESHOLD, "rollup should still have some balance" ); assertEq( stakingAsset.balanceOf(address(staking.getGSE().getGovernance())), - (depositCount + initialActiveAttesterCount) * DEPOSIT_AMOUNT, + (depositCount + initialActiveAttesterCount) * ACTIVATION_THRESHOLD, "governance should have received the deposits from successful deposits" ); if (numDequeued > 1) { assertEq( stakingAsset.balanceOf(address(uint160(1 * 2 + 1))), - DEPOSIT_AMOUNT, + ACTIVATION_THRESHOLD, "withdrawer should have received the deposit" ); } @@ -305,7 +309,7 @@ contract FlushEntryQueueTest is StakingBase { assertTrue(attesterView.status == Status.NONE, "invalid status"); } else { attesterView = staking.getAttesterView(attester); - assertEq(attesterView.effectiveBalance, DEPOSIT_AMOUNT, "invalid effective balance"); + assertEq(attesterView.effectiveBalance, ACTIVATION_THRESHOLD, "invalid effective balance"); assertEq(attesterView.config.withdrawer, withdrawer, "invalid withdrawer"); assertTrue(attesterView.status == Status.VALIDATING, "invalid status"); } diff --git a/l1-contracts/test/staking/getters.t.sol b/l1-contracts/test/staking/getters.t.sol index 6c41ee51f56c..50c637dcd5b1 100644 --- a/l1-contracts/test/staking/getters.t.sol +++ b/l1-contracts/test/staking/getters.t.sol @@ -8,8 +8,8 @@ contract GettersTest is StakingBase { super.setUp(); vm.prank(stakingAsset.owner()); - stakingAsset.mint(address(this), DEPOSIT_AMOUNT); - stakingAsset.approve(address(staking), DEPOSIT_AMOUNT); + stakingAsset.mint(address(this), ACTIVATION_THRESHOLD); + stakingAsset.approve(address(staking), ACTIVATION_THRESHOLD); staking.deposit({_attester: ATTESTER, _withdrawer: WITHDRAWER, _moveWithLatestRollup: true}); staking.flushEntryQueue(); } diff --git a/l1-contracts/test/staking/initiateWithdraw.t.sol b/l1-contracts/test/staking/initiateWithdraw.t.sol index 961f33396268..29d5773aa3de 100644 --- a/l1-contracts/test/staking/initiateWithdraw.t.sol +++ b/l1-contracts/test/staking/initiateWithdraw.t.sol @@ -16,8 +16,8 @@ contract InitiateWithdrawTest is StakingBase { } modifier whenAttesterIsRegistered() { - mint(address(this), DEPOSIT_AMOUNT); - stakingAsset.approve(address(staking), DEPOSIT_AMOUNT); + mint(address(this), ACTIVATION_THRESHOLD); + stakingAsset.approve(address(staking), ACTIVATION_THRESHOLD); staking.deposit({_attester: ATTESTER, _withdrawer: WITHDRAWER, _moveWithLatestRollup: true}); staking.flushEntryQueue(); _; @@ -87,7 +87,7 @@ contract InitiateWithdrawTest is StakingBase { address lookup = address(staking.getGSE().getGovernance()); - assertEq(stakingAsset.balanceOf(lookup), DEPOSIT_AMOUNT); + assertEq(stakingAsset.balanceOf(lookup), ACTIVATION_THRESHOLD); assertEq(stakingAsset.balanceOf(RECIPIENT), 0); AttesterView memory attesterView = staking.getAttesterView(ATTESTER); assertTrue(attesterView.status == Status.VALIDATING); @@ -100,14 +100,14 @@ contract InitiateWithdrawTest is StakingBase { assertEq(staking.getActiveAttesterCount(), 1); vm.expectEmit(true, true, true, true, address(staking)); - emit IStakingCore.WithdrawInitiated(ATTESTER, RECIPIENT, DEPOSIT_AMOUNT); + emit IStakingCore.WithdrawInitiated(ATTESTER, RECIPIENT, ACTIVATION_THRESHOLD); vm.prank(WITHDRAWER); staking.initiateWithdraw(ATTESTER, RECIPIENT); // @todo We should look at updating these, the location of balance depends on time // and whether the governance.finaliseWithdraw have been called now. - assertEq(stakingAsset.balanceOf(lookup), DEPOSIT_AMOUNT); + assertEq(stakingAsset.balanceOf(lookup), ACTIVATION_THRESHOLD); assertEq(stakingAsset.balanceOf(RECIPIENT), 0); attesterView = staking.getAttesterView(ATTESTER); @@ -127,16 +127,16 @@ contract InitiateWithdrawTest is StakingBase { address lookup = address(staking.getGSE().getGovernance()); - assertEq(stakingAsset.balanceOf(lookup), DEPOSIT_AMOUNT); + assertEq(stakingAsset.balanceOf(lookup), ACTIVATION_THRESHOLD); - uint256 slashAmount = DEPOSIT_AMOUNT - MINIMUM_STAKE + 1; + uint256 slashAmount = ACTIVATION_THRESHOLD - EJECTION_THRESHOLD + 1; vm.prank(SLASHER); staking.slash(ATTESTER, slashAmount); // @todo Again, need to cover more cases because funds could be many places now. // But if not called, the funds should still be in the governance - assertEq(stakingAsset.balanceOf(lookup), DEPOSIT_AMOUNT); + assertEq(stakingAsset.balanceOf(lookup), ACTIVATION_THRESHOLD); assertEq(stakingAsset.balanceOf(RECIPIENT), 0); AttesterView memory attesterView = staking.getAttesterView(ATTESTER); @@ -144,24 +144,24 @@ contract InitiateWithdrawTest is StakingBase { assertEq(attesterView.exit.exitableAt, Timestamp.wrap(block.timestamp) + staking.getExitDelay()); assertEq(attesterView.exit.exists, true); assertEq(attesterView.exit.isRecipient, false); - assertEq(attesterView.exit.amount, DEPOSIT_AMOUNT - slashAmount); + assertEq(attesterView.exit.amount, ACTIVATION_THRESHOLD - slashAmount); assertEq(attesterView.exit.recipientOrWithdrawer, WITHDRAWER); assertEq(staking.getActiveAttesterCount(), 0); vm.expectEmit(true, true, true, true, address(staking)); - emit IStakingCore.WithdrawInitiated(ATTESTER, RECIPIENT, DEPOSIT_AMOUNT - slashAmount); + emit IStakingCore.WithdrawInitiated(ATTESTER, RECIPIENT, ACTIVATION_THRESHOLD - slashAmount); vm.prank(WITHDRAWER); staking.initiateWithdraw(ATTESTER, RECIPIENT); - assertEq(stakingAsset.balanceOf(lookup), DEPOSIT_AMOUNT); + assertEq(stakingAsset.balanceOf(lookup), ACTIVATION_THRESHOLD); assertEq(stakingAsset.balanceOf(RECIPIENT), 0); attesterView = staking.getAttesterView(ATTESTER); assertEq(attesterView.exit.exitableAt, Timestamp.wrap(block.timestamp) + staking.getExitDelay()); assertEq(attesterView.exit.exists, true); assertEq(attesterView.exit.isRecipient, true); - assertEq(attesterView.exit.amount, DEPOSIT_AMOUNT - slashAmount); + assertEq(attesterView.exit.amount, ACTIVATION_THRESHOLD - slashAmount); assertEq(attesterView.exit.recipientOrWithdrawer, RECIPIENT); assertTrue(attesterView.status == Status.EXITING); assertEq(staking.getActiveAttesterCount(), 0); diff --git a/l1-contracts/test/staking/move.t.sol b/l1-contracts/test/staking/move.t.sol index 88f1c78ec0bf..730086efaeb4 100644 --- a/l1-contracts/test/staking/move.t.sol +++ b/l1-contracts/test/staking/move.t.sol @@ -43,8 +43,8 @@ contract MoveTest is StakingBase { staking = IStaking(address(builder.getConfig().rollup)); stakingAsset = builder.getConfig().testERC20; - DEPOSIT_AMOUNT = staking.getDepositAmount(); - MINIMUM_STAKE = staking.getMinimumStake(); + ACTIVATION_THRESHOLD = staking.getActivationThreshold(); + EJECTION_THRESHOLD = staking.getEjectionThreshold(); SLASHER = staking.getSlasher(); } @@ -63,8 +63,8 @@ contract MoveTest is StakingBase { IInstance oldRollup = IInstance(address(staking)); IInstance newRollup = IInstance(address(builder.getConfig().rollup)); - mint(address(this), DEPOSIT_AMOUNT * n); - stakingAsset.approve(address(oldRollup), DEPOSIT_AMOUNT * n); + mint(address(this), ACTIVATION_THRESHOLD * n); + stakingAsset.approve(address(oldRollup), ACTIVATION_THRESHOLD * n); for (uint256 i = 0; i < n; i++) { bool moveWithLatestRollup = i % 2 == 0; @@ -168,7 +168,7 @@ contract MoveTest is StakingBase { vm.warp(Timestamp.unwrap(attesterView.exit.exitableAt)); vm.expectEmit(true, true, true, true, address(newRollup)); - emit IStakingCore.WithdrawFinalised(attesterToExit, RECIPIENT, DEPOSIT_AMOUNT); + emit IStakingCore.WithdrawFinalised(attesterToExit, RECIPIENT, ACTIVATION_THRESHOLD); newRollup.finaliseWithdraw(attesterToExit); attesterView = newRollup.getAttesterView(attesterToExit); @@ -177,6 +177,6 @@ contract MoveTest is StakingBase { assertTrue(attesterView.status == Status.NONE); assertEq(stakingAsset.balanceOf(address(newRollup)), 0); - assertEq(stakingAsset.balanceOf(RECIPIENT), DEPOSIT_AMOUNT); + assertEq(stakingAsset.balanceOf(RECIPIENT), ACTIVATION_THRESHOLD); } } diff --git a/l1-contracts/test/staking/slash.t.sol b/l1-contracts/test/staking/slash.t.sol index 8a6dd5722b86..7250e71e4e05 100644 --- a/l1-contracts/test/staking/slash.t.sol +++ b/l1-contracts/test/staking/slash.t.sol @@ -15,8 +15,8 @@ contract SlashTest is StakingBase { } function test_WhenCallerIsNotTheSlasher() external { - mint(address(this), DEPOSIT_AMOUNT); - stakingAsset.approve(address(staking), DEPOSIT_AMOUNT); + mint(address(this), ACTIVATION_THRESHOLD); + stakingAsset.approve(address(staking), ACTIVATION_THRESHOLD); staking.deposit({_attester: ATTESTER, _withdrawer: WITHDRAWER, _moveWithLatestRollup: true}); staking.flushEntryQueue(); @@ -40,8 +40,8 @@ contract SlashTest is StakingBase { } modifier whenAttesterIsRegistered() { - mint(address(this), DEPOSIT_AMOUNT); - stakingAsset.approve(address(staking), DEPOSIT_AMOUNT); + mint(address(this), ACTIVATION_THRESHOLD); + stakingAsset.approve(address(staking), ACTIVATION_THRESHOLD); staking.deposit({_attester: ATTESTER, _withdrawer: WITHDRAWER, _moveWithLatestRollup: true}); staking.flushEntryQueue(); @@ -84,7 +84,7 @@ contract SlashTest is StakingBase { AttesterView memory attesterView = staking.getAttesterView(ATTESTER); assertEq(attesterView.effectiveBalance, 0); - assertEq(attesterView.exit.amount, DEPOSIT_AMOUNT, "Invalid exit amount"); + assertEq(attesterView.exit.amount, ACTIVATION_THRESHOLD, "Invalid exit amount"); assertTrue(attesterView.status == Status.EXITING); vm.expectEmit(true, true, true, true, address(staking)); @@ -94,7 +94,7 @@ contract SlashTest is StakingBase { attesterView = staking.getAttesterView(ATTESTER); assertEq(attesterView.effectiveBalance, 0); - assertEq(attesterView.exit.amount, DEPOSIT_AMOUNT - 1, "Invalid exit amount 2"); + assertEq(attesterView.exit.amount, ACTIVATION_THRESHOLD - 1, "Invalid exit amount 2"); assertTrue(attesterView.status == Status.EXITING); } @@ -112,7 +112,7 @@ contract SlashTest is StakingBase { assertEq(staking.getActiveAttesterCount(), isAlive ? 1 : 0, "Invalid active attester count"); uint256 balance = isAlive ? attesterView.effectiveBalance : attesterView.exit.amount; - slashingAmount = isAlive ? DEPOSIT_AMOUNT / 3 : balance; + slashingAmount = isAlive ? ACTIVATION_THRESHOLD / 3 : balance; vm.expectEmit(true, true, true, true, address(staking)); emit IStakingCore.Slashed(ATTESTER, slashingAmount); @@ -145,9 +145,9 @@ contract SlashTest is StakingBase { } } - modifier whenAttesterIsValidatingAndStakeIsBelowMinimumStake() { + modifier whenAttesterIsValidatingAndStakeIsBelowejectionThreshold() { AttesterView memory attesterView = staking.getAttesterView(ATTESTER); - uint256 targetBalance = MINIMUM_STAKE - 1; + uint256 targetBalance = EJECTION_THRESHOLD - 1; slashingAmount = attesterView.effectiveBalance - targetBalance; _; @@ -157,7 +157,7 @@ contract SlashTest is StakingBase { external whenCallerIsTheSlasher whenAttesterIsRegistered - whenAttesterIsValidatingAndStakeIsBelowMinimumStake + whenAttesterIsValidatingAndStakeIsBelowejectionThreshold { // it reverts @@ -169,7 +169,7 @@ contract SlashTest is StakingBase { external whenCallerIsTheSlasher whenAttesterIsRegistered - whenAttesterIsValidatingAndStakeIsBelowMinimumStake + whenAttesterIsValidatingAndStakeIsBelowejectionThreshold { // it reduce stake by amount // it remove from active attesters diff --git a/l1-contracts/test/staking_asset_handler/addValidator.t.sol b/l1-contracts/test/staking_asset_handler/addValidator.t.sol index 188caefb6f2a..f6b3d12c3753 100644 --- a/l1-contracts/test/staking_asset_handler/addValidator.t.sol +++ b/l1-contracts/test/staking_asset_handler/addValidator.t.sol @@ -47,7 +47,7 @@ contract AddValidatorTest is StakingAssetHandlerBase { AttesterView memory attesterView = staking.getAttesterView(_attester); assertEq(attesterView.config.withdrawer, WITHDRAWER); - assertEq(attesterView.effectiveBalance, DEPOSIT_AMOUNT); + assertEq(attesterView.effectiveBalance, ACTIVATION_THRESHOLD); assertTrue(attesterView.status == Status.VALIDATING); } @@ -56,14 +56,14 @@ contract AddValidatorTest is StakingAssetHandlerBase { _; } - modifier givenBalanceLTDepositamount() { + modifier givenBalanceLTactivationThreshold() { _; } function test_WhenInsufficientTimePassed(address _caller, address _attester) external whenCallerIsNotUnhinged(_caller) - givenBalanceLTDepositamount + givenBalanceLTactivationThreshold givenPassportProofIsValid { // it reverts @@ -83,7 +83,7 @@ contract AddValidatorTest is StakingAssetHandlerBase { function test_WhenSufficientTimePassed(address _caller, address _attester) external whenCallerIsNotUnhinged(_caller) - givenBalanceLTDepositamount + givenBalanceLTactivationThreshold givenPassportProofIsValid { // it adds the validator to the queue @@ -99,7 +99,7 @@ contract AddValidatorTest is StakingAssetHandlerBase { vm.warp(revertTimestamp); vm.expectEmit(true, true, true, true, address(stakingAssetHandler)); - emit IStakingAssetHandler.ToppedUp(DEPOSIT_AMOUNT * depositsPerMint); + emit IStakingAssetHandler.ToppedUp(ACTIVATION_THRESHOLD * depositsPerMint); vm.expectEmit(true, true, true, true, address(stakingAssetHandler)); emit IStakingAssetHandler.ValidatorAdded(address(staking), _attester, WITHDRAWER); vm.prank(_caller); @@ -107,7 +107,7 @@ contract AddValidatorTest is StakingAssetHandlerBase { AttesterView memory attesterView = staking.getAttesterView(_attester); assertEq(attesterView.config.withdrawer, WITHDRAWER); - assertEq(attesterView.effectiveBalance, DEPOSIT_AMOUNT); + assertEq(attesterView.effectiveBalance, ACTIVATION_THRESHOLD); assertTrue(attesterView.status == Status.VALIDATING); assertEq(stakingAssetHandler.lastMintTimestamp(), block.timestamp); @@ -124,14 +124,14 @@ contract AddValidatorTest is StakingAssetHandlerBase { _; } - modifier givenBalanceGEDepositAmount() { + modifier givenBalanceGEactivationThreshold() { _; } function test_WhenUserIsNew(address _caller, address _attester) external whenCallerIsNotUnhinged(_caller) - givenBalanceGEDepositAmount + givenBalanceGEactivationThreshold givenPassportProofIsValid { // it exits the attester if needed @@ -146,7 +146,7 @@ contract AddValidatorTest is StakingAssetHandlerBase { vm.warp(revertTimestamp); vm.expectEmit(true, true, true, true, address(stakingAssetHandler)); - emit IStakingAssetHandler.ToppedUp(DEPOSIT_AMOUNT * depositsPerMint); + emit IStakingAssetHandler.ToppedUp(ACTIVATION_THRESHOLD * depositsPerMint); vm.expectEmit(true, true, true, true, address(stakingAssetHandler)); emit IStakingAssetHandler.ValidatorAdded(address(staking), _attester, WITHDRAWER); vm.prank(_caller); @@ -154,7 +154,7 @@ contract AddValidatorTest is StakingAssetHandlerBase { AttesterView memory attesterView = staking.getAttesterView(_attester); assertEq(attesterView.config.withdrawer, WITHDRAWER); - assertEq(attesterView.effectiveBalance, DEPOSIT_AMOUNT); + assertEq(attesterView.effectiveBalance, ACTIVATION_THRESHOLD); assertTrue(attesterView.status == Status.VALIDATING); assertEq(stakingAssetHandler.lastMintTimestamp(), block.timestamp); @@ -163,7 +163,7 @@ contract AddValidatorTest is StakingAssetHandlerBase { function test_WhenPassportProofHasBeenUsed(address _caller, address _attester) external whenCallerIsNotUnhinged(_caller) - givenBalanceGEDepositAmount + givenBalanceGEactivationThreshold givenPassportProofIsValid { // it reverts @@ -196,7 +196,7 @@ contract AddValidatorTest is StakingAssetHandlerBase { function test_WhenPassportProofIsInDevMode(address _caller, address _attester) external whenCallerIsNotUnhinged(_caller) - givenBalanceGEDepositAmount + givenBalanceGEactivationThreshold givenPassportProofIsValid { // it reverts @@ -217,7 +217,7 @@ contract AddValidatorTest is StakingAssetHandlerBase { function test_WhenPassportProofIsInThePast(address _caller, uint16 _daysInFuture) external whenCallerIsNotUnhinged(_caller) - givenBalanceGEDepositAmount + givenBalanceGEactivationThreshold givenPassportProofIsValid { // it reverts @@ -238,7 +238,7 @@ contract AddValidatorTest is StakingAssetHandlerBase { function test_WhenFlushEntryQueueReverts(address _caller, address _attester) external whenCallerIsNotUnhinged(_caller) - givenBalanceGEDepositAmount + givenBalanceGEactivationThreshold givenPassportProofIsValid { // it deposits into the rollup @@ -264,7 +264,7 @@ contract AddValidatorTest is StakingAssetHandlerBase { uint256 queueLengthBefore = staking.getEntryQueueLength(); vm.expectEmit(true, true, true, true, address(stakingAssetHandler)); - emit IStakingAssetHandler.ToppedUp(DEPOSIT_AMOUNT * depositsPerMint); + emit IStakingAssetHandler.ToppedUp(ACTIVATION_THRESHOLD * depositsPerMint); vm.expectEmit(true, true, true, true, address(stakingAssetHandler)); emit IStakingAssetHandler.ValidatorAdded(address(staking), _attester, WITHDRAWER); vm.prank(_caller); @@ -285,7 +285,7 @@ contract AddValidatorTest is StakingAssetHandlerBase { // Now validator should be active attesterView = staking.getAttesterView(_attester); assertEq(attesterView.config.withdrawer, WITHDRAWER); - assertEq(attesterView.effectiveBalance, DEPOSIT_AMOUNT); + assertEq(attesterView.effectiveBalance, ACTIVATION_THRESHOLD); assertTrue(attesterView.status == Status.VALIDATING); } } diff --git a/l1-contracts/test/staking_asset_handler/addValidator.tree b/l1-contracts/test/staking_asset_handler/addValidator.tree index 6cf8676a2235..9b81c4c39ce1 100644 --- a/l1-contracts/test/staking_asset_handler/addValidator.tree +++ b/l1-contracts/test/staking_asset_handler/addValidator.tree @@ -5,7 +5,7 @@ AddValidatorTest │ ├── it does not need a valid proof │ └── it emits a {ValidatorAdded} event └── when caller is not unhinged - ├── given balance LT depositamount + ├── given balance LT activationThreshold │ ├── when insufficient time passed │ │ └── it reverts │ └── when sufficient time passed @@ -17,7 +17,7 @@ AddValidatorTest │ ├── it pops the validator from the queue │ ├── it deposits into the rollup │ └── it emits a {ValidatorAdded} event - └── given balance GE depositAmount + └── given balance GE activationThreshold ├── given passport proof is not valid │ └── it reverts ├── given passport proof is valid diff --git a/l1-contracts/test/staking_asset_handler/base.t.sol b/l1-contracts/test/staking_asset_handler/base.t.sol index ef851593274f..4243038e3f44 100644 --- a/l1-contracts/test/staking_asset_handler/base.t.sol +++ b/l1-contracts/test/staking_asset_handler/base.t.sol @@ -26,7 +26,7 @@ contract StakingAssetHandlerBase is ZKPassportBase, TestBase { bytes internal EMPTY_PROOF = bytes(string("")); bytes32[] internal EMPTY_PUBLIC_INPUTS = new bytes32[](0); - uint256 internal DEPOSIT_AMOUNT; + uint256 internal ACTIVATION_THRESHOLD; uint256 internal mintInterval = 1; uint256 internal depositsPerMint = 1; @@ -42,7 +42,7 @@ contract StakingAssetHandlerBase is ZKPassportBase, TestBase { stakingAsset = builder.getConfig().testERC20; registry = builder.getConfig().registry; - DEPOSIT_AMOUNT = builder.getConfig().rollup.getDepositAmount(); + ACTIVATION_THRESHOLD = builder.getConfig().rollup.getActivationThreshold(); staking = IStaking(address(builder.getConfig().rollup)); StakingAssetHandler.StakingAssetHandlerArgs memory stakingAssetHandlerArgs = StakingAssetHandler diff --git a/l1-contracts/test/validator-selection/ValidatorSelection.t.sol b/l1-contracts/test/validator-selection/ValidatorSelection.t.sol index e627d415f425..6aaa32be45c7 100644 --- a/l1-contracts/test/validator-selection/ValidatorSelection.t.sol +++ b/l1-contracts/test/validator-selection/ValidatorSelection.t.sol @@ -118,10 +118,10 @@ contract ValidatorSelectionTest is ValidatorSelectionTestBase { address expectedProposer = rollup.getCurrentProposer(); // Add a validator which will also setup the epoch - uint256 depositAmount = rollup.getDepositAmount(); + uint256 activationThreshold = rollup.getActivationThreshold(); vm.prank(testERC20.owner()); - testERC20.mint(address(this), depositAmount); - testERC20.approve(address(rollup), depositAmount); + testERC20.mint(address(this), activationThreshold); + testERC20.approve(address(rollup), activationThreshold); rollup.deposit(address(0xdead), address(0xdead), true); address actualProposer = rollup.getCurrentProposer(); @@ -167,10 +167,10 @@ contract ValidatorSelectionTest is ValidatorSelectionTestBase { vm.warp(ts2); // add a new validator - uint256 depositAmount = rollup.getDepositAmount(); + uint256 activationThreshold = rollup.getActivationThreshold(); vm.prank(testERC20.owner()); - testERC20.mint(address(this), depositAmount); - testERC20.approve(address(rollup), depositAmount); + testERC20.mint(address(this), activationThreshold); + testERC20.approve(address(rollup), activationThreshold); rollup.deposit(address(0xdead), address(0xdead), true); rollup.flushEntryQueue(); diff --git a/l1-contracts/test/validator-selection/setupEpoch.t.sol b/l1-contracts/test/validator-selection/setupEpoch.t.sol index f45d77a41a84..71b39a27ecd4 100644 --- a/l1-contracts/test/validator-selection/setupEpoch.t.sol +++ b/l1-contracts/test/validator-selection/setupEpoch.t.sol @@ -236,7 +236,7 @@ contract SetupEpochTest is ValidatorSelectionTestBase { } MultiAdder multiAdder = new MultiAdder(address(rollup), address(this)); - uint256 amount = rollup.getDepositAmount() * validators.length; + uint256 amount = rollup.getActivationThreshold() * validators.length; vm.prank(testERC20.owner()); testERC20.mint(address(multiAdder), amount); multiAdder.addValidators(validators); diff --git a/yarn-project/aztec/src/cli/chain_l2_config.ts b/yarn-project/aztec/src/cli/chain_l2_config.ts index 008abf862295..80a8d0b20995 100644 --- a/yarn-project/aztec/src/cli/chain_l2_config.ts +++ b/yarn-project/aztec/src/cli/chain_l2_config.ts @@ -41,9 +41,9 @@ export type L2ChainConfig = { /** The number of epochs after an epoch ends that proofs are still accepted. */ aztecProofSubmissionEpochs: number; /** The deposit amount for a validator */ - depositAmount: bigint; + activationThreshold: bigint; /** The minimum stake for a validator. */ - minimumStake: bigint; + ejectionThreshold: bigint; /** The slashing quorum */ slashingQuorum: number; /** The slashing round size */ @@ -103,9 +103,9 @@ export const testnetIgnitionL2ChainConfig: L2ChainConfig = { /** The number of epochs after an epoch ends that proofs are still accepted. */ aztecProofSubmissionEpochs: 1, /** The deposit amount for a validator */ - depositAmount: DefaultL1ContractsConfig.depositAmount, + activationThreshold: DefaultL1ContractsConfig.activationThreshold, /** The minimum stake for a validator. */ - minimumStake: DefaultL1ContractsConfig.minimumStake, + ejectionThreshold: DefaultL1ContractsConfig.ejectionThreshold, /** The slashing quorum */ slashingQuorum: DefaultL1ContractsConfig.slashingQuorum, /** The slashing round size */ @@ -167,9 +167,9 @@ export const alphaTestnetL2ChainConfig: L2ChainConfig = { /** The number of epochs after an epoch ends that proofs are still accepted. */ aztecProofSubmissionEpochs: 1, /** The deposit amount for a validator */ - depositAmount: DefaultL1ContractsConfig.depositAmount, + activationThreshold: DefaultL1ContractsConfig.activationThreshold, /** The minimum stake for a validator. */ - minimumStake: DefaultL1ContractsConfig.minimumStake, + ejectionThreshold: DefaultL1ContractsConfig.ejectionThreshold, /** The slashing quorum */ slashingQuorum: 101, /** The slashing round size */ @@ -186,16 +186,16 @@ export const alphaTestnetL2ChainConfig: L2ChainConfig = { // slashing stuff slashPayloadTtlSeconds: 36 * 32 * 24, // 24 epochs slashPruneEnabled: true, - slashPrunePenalty: 17n * (DefaultL1ContractsConfig.depositAmount / 100n), - slashPruneMaxPenalty: 17n * (DefaultL1ContractsConfig.depositAmount / 100n), + slashPrunePenalty: 17n * (DefaultL1ContractsConfig.activationThreshold / 100n), + slashPruneMaxPenalty: 17n * (DefaultL1ContractsConfig.activationThreshold / 100n), slashInactivityEnabled: true, slashInactivityCreateTargetPercentage: 1, slashInactivitySignalTargetPercentage: 0.67, - slashInactivityCreatePenalty: 17n * (DefaultL1ContractsConfig.depositAmount / 100n), - slashInactivityMaxPenalty: 17n * (DefaultL1ContractsConfig.depositAmount / 100n), + slashInactivityCreatePenalty: 17n * (DefaultL1ContractsConfig.activationThreshold / 100n), + slashInactivityMaxPenalty: 17n * (DefaultL1ContractsConfig.activationThreshold / 100n), slashInvalidBlockEnabled: true, - slashInvalidBlockPenalty: DefaultL1ContractsConfig.depositAmount, - slashInvalidBlockMaxPenalty: DefaultL1ContractsConfig.depositAmount, + slashInvalidBlockPenalty: DefaultL1ContractsConfig.activationThreshold, + slashInvalidBlockMaxPenalty: DefaultL1ContractsConfig.activationThreshold, sentinelEnabled: true, }; @@ -336,8 +336,8 @@ export async function enrichEnvironmentWithChainConfig(networkName: NetworkNames enrichVar('AZTEC_EPOCH_DURATION', config.aztecEpochDuration.toString()); enrichVar('AZTEC_TARGET_COMMITTEE_SIZE', config.aztecTargetCommitteeSize.toString()); enrichVar('AZTEC_PROOF_SUBMISSION_EPOCHS', config.aztecProofSubmissionEpochs.toString()); - enrichVar('AZTEC_DEPOSIT_AMOUNT', config.depositAmount.toString()); - enrichVar('AZTEC_MINIMUM_STAKE', config.minimumStake.toString()); + enrichVar('AZTEC_ACTIVATION_THRESHOLD', config.activationThreshold.toString()); + enrichVar('AZTEC_EJECTION_THRESHOLD', config.ejectionThreshold.toString()); enrichVar('AZTEC_SLASHING_QUORUM', config.slashingQuorum.toString()); enrichVar('AZTEC_SLASHING_ROUND_SIZE', config.slashingRoundSize.toString()); enrichVar('AZTEC_GOVERNANCE_PROPOSER_QUORUM', config.governanceProposerQuorum.toString()); diff --git a/yarn-project/cli/src/cmds/infrastructure/sequencers.ts b/yarn-project/cli/src/cmds/infrastructure/sequencers.ts index fe76911bab7f..59d940cc1caa 100644 --- a/yarn-project/cli/src/cmds/infrastructure/sequencers.ts +++ b/yarn-project/cli/src/cmds/infrastructure/sequencers.ts @@ -74,8 +74,8 @@ export async function sequencers(opts: { await Promise.all( [ - await stakingAsset.write.mint([walletClient.account.address, config.depositAmount], {} as any), - await stakingAsset.write.approve([rollup.address, config.depositAmount], {} as any), + await stakingAsset.write.mint([walletClient.account.address, config.activationThreshold], {} as any), + await stakingAsset.write.approve([rollup.address, config.activationThreshold], {} as any), ].map(txHash => publicClient.waitForTransactionReceipt({ hash: txHash })), ); diff --git a/yarn-project/end-to-end/src/e2e_lending_contract.test.ts b/yarn-project/end-to-end/src/e2e_lending_contract.test.ts index 8f30c1bbfe75..5fc84cbfcaf3 100644 --- a/yarn-project/end-to-end/src/e2e_lending_contract.test.ts +++ b/yarn-project/end-to-end/src/e2e_lending_contract.test.ts @@ -127,19 +127,19 @@ describe('e2e_lending_contract', () => { describe('Deposits', () => { it('Depositing 🥸 : 💰 -> 🏦', async () => { - const depositAmount = 420n; + const activationThreshold = 420n; const authwitNonce = Fr.random(); const transferToPublicAuthwit = await wallet.createAuthWit({ caller: lendingContract.address, action: collateralAsset.methods.transfer_to_public( lendingAccount.address, lendingContract.address, - depositAmount, + activationThreshold, authwitNonce, ), }); await lendingSim.progressSlots(SLOT_JUMP, dateProvider); - lendingSim.depositPrivate(lendingAccount.address, await lendingAccount.key(), depositAmount); + lendingSim.depositPrivate(lendingAccount.address, await lendingAccount.key(), activationThreshold); // Make a private deposit of funds into own account. // This should: @@ -150,7 +150,7 @@ describe('e2e_lending_contract', () => { await lendingContract.methods .deposit_private( lendingAccount.address, - depositAmount, + activationThreshold, authwitNonce, lendingAccount.secret, 0n, @@ -161,20 +161,20 @@ describe('e2e_lending_contract', () => { }); it('Depositing 🥸 on behalf of recipient: 💰 -> 🏦', async () => { - const depositAmount = 421n; + const activationThreshold = 421n; const authwitNonce = Fr.random(); const transferToPublicAuthwit = await wallet.createAuthWit({ caller: lendingContract.address, action: collateralAsset.methods.transfer_to_public( lendingAccount.address, lendingContract.address, - depositAmount, + activationThreshold, authwitNonce, ), }); await lendingSim.progressSlots(SLOT_JUMP, dateProvider); - lendingSim.depositPrivate(lendingAccount.address, lendingAccount.address.toField(), depositAmount); + lendingSim.depositPrivate(lendingAccount.address, lendingAccount.address.toField(), activationThreshold); // Make a private deposit of funds into another account, in this case, a public account. // This should: // - increase the interest accumulator @@ -184,7 +184,7 @@ describe('e2e_lending_contract', () => { await lendingContract.methods .deposit_private( lendingAccount.address, - depositAmount, + activationThreshold, authwitNonce, 0n, lendingAccount.address, @@ -195,7 +195,7 @@ describe('e2e_lending_contract', () => { }); it('Depositing: 💰 -> 🏦', async () => { - const depositAmount = 211n; + const activationThreshold = 211n; const authwitNonce = Fr.random(); @@ -206,7 +206,7 @@ describe('e2e_lending_contract', () => { action: collateralAsset.methods.transfer_in_public( lendingAccount.address, lendingContract.address, - depositAmount, + activationThreshold, authwitNonce, ), }, @@ -215,7 +215,7 @@ describe('e2e_lending_contract', () => { await validateAction.send().wait(); await lendingSim.progressSlots(SLOT_JUMP, dateProvider); - lendingSim.depositPublic(lendingAccount.address, lendingAccount.address.toField(), depositAmount); + lendingSim.depositPublic(lendingAccount.address, lendingAccount.address.toField(), activationThreshold); // Make a public deposit of funds into self. // This should: @@ -225,7 +225,7 @@ describe('e2e_lending_contract', () => { logger.info('Depositing: 💰 -> 🏦'); await lendingContract.methods - .deposit_public(depositAmount, authwitNonce, lendingAccount.address, collateralAsset.address) + .deposit_public(activationThreshold, authwitNonce, lendingAccount.address, collateralAsset.address) .send() .wait(); }); diff --git a/yarn-project/end-to-end/src/e2e_p2p/data_withholding_slash.test.ts b/yarn-project/end-to-end/src/e2e_p2p/data_withholding_slash.test.ts index 76693977cde9..0d09dac2818d 100644 --- a/yarn-project/end-to-end/src/e2e_p2p/data_withholding_slash.test.ts +++ b/yarn-project/end-to-end/src/e2e_p2p/data_withholding_slash.test.ts @@ -94,7 +94,7 @@ describe('e2e_p2p_data_withholding_slash', () => { await debugRollup(); } - const slashingAmount = (await rollup.getDepositAmount()) - (await rollup.getMinimumStake()) + 1n; + const slashingAmount = (await rollup.getActivationThreshold()) - (await rollup.getEjectionThreshold()) + 1n; t.ctx.aztecNodeConfig.slashPruneEnabled = true; t.ctx.aztecNodeConfig.slashPrunePenalty = slashingAmount; t.ctx.aztecNodeConfig.slashPruneMaxPenalty = slashingAmount; diff --git a/yarn-project/end-to-end/src/e2e_p2p/p2p_network.ts b/yarn-project/end-to-end/src/e2e_p2p/p2p_network.ts index 50c6c8932bef..9a151c0696b5 100644 --- a/yarn-project/end-to-end/src/e2e_p2p/p2p_network.ts +++ b/yarn-project/end-to-end/src/e2e_p2p/p2p_network.ts @@ -245,7 +245,7 @@ export class P2PNetworkTest { client: deployL1ContractsValues.l1Client, }); - const stakeNeeded = l1ContractsConfig.depositAmount * BigInt(this.numberOfValidators); + const stakeNeeded = l1ContractsConfig.activationThreshold * BigInt(this.numberOfValidators); await Promise.all( [await stakingAsset.write.mint([multiAdder.address, stakeNeeded], {} as any)].map(txHash => deployL1ContractsValues.l1Client.waitForTransactionReceipt({ hash: txHash }), diff --git a/yarn-project/end-to-end/src/e2e_p2p/upgrade_governance_proposer.test.ts b/yarn-project/end-to-end/src/e2e_p2p/upgrade_governance_proposer.test.ts index a6d293116faf..fee8e21f5580 100644 --- a/yarn-project/end-to-end/src/e2e_p2p/upgrade_governance_proposer.test.ts +++ b/yarn-project/end-to-end/src/e2e_p2p/upgrade_governance_proposer.test.ts @@ -50,8 +50,8 @@ describe('e2e_p2p_governance_proposer', () => { listenAddress: '127.0.0.1', governanceProposerQuorum: 6, governanceProposerRoundSize: 10, - depositAmount: 10n ** 22n, - minimumStake: 5n ** 22n, + activationThreshold: 10n ** 22n, + ejectionThreshold: 5n ** 22n, }, }); diff --git a/yarn-project/end-to-end/src/e2e_p2p/valid_epoch_pruned.test.ts b/yarn-project/end-to-end/src/e2e_p2p/valid_epoch_pruned.test.ts index 27857aec8dbf..ee7716676b05 100644 --- a/yarn-project/end-to-end/src/e2e_p2p/valid_epoch_pruned.test.ts +++ b/yarn-project/end-to-end/src/e2e_p2p/valid_epoch_pruned.test.ts @@ -77,7 +77,7 @@ describe('e2e_p2p_valid_epoch_pruned', () => { const { rollup, slashingProposer, slashFactory } = await t.getContracts(); - const slashingAmount = (await rollup.getDepositAmount()) - (await rollup.getMinimumStake()) + 1n; + const slashingAmount = (await rollup.getActivationThreshold()) - (await rollup.getEjectionThreshold()) + 1n; t.ctx.aztecNodeConfig.slashPruneEnabled = true; t.ctx.aztecNodeConfig.slashPrunePenalty = slashingAmount; t.ctx.aztecNodeConfig.slashPruneMaxPenalty = slashingAmount; diff --git a/yarn-project/end-to-end/src/e2e_p2p/validators_sentinel.test.ts b/yarn-project/end-to-end/src/e2e_p2p/validators_sentinel.test.ts index c8fb89cbd514..9063bd380770 100644 --- a/yarn-project/end-to-end/src/e2e_p2p/validators_sentinel.test.ts +++ b/yarn-project/end-to-end/src/e2e_p2p/validators_sentinel.test.ts @@ -62,7 +62,7 @@ describe('e2e_p2p_validators_sentinel', () => { await t.setup(); const { rollup } = await t.getContracts(); - slashingAmount = (await rollup.getDepositAmount()) - (await rollup.getMinimumStake()) + 1n; + slashingAmount = (await rollup.getActivationThreshold()) - (await rollup.getEjectionThreshold()) + 1n; t.ctx.aztecNodeConfig.slashInactivityEnabled = true; t.ctx.aztecNodeConfig.slashInactivityCreatePenalty = slashingAmount; t.ctx.aztecNodeConfig.slashInactivityMaxPenalty = slashingAmount; diff --git a/yarn-project/ethereum/src/config.ts b/yarn-project/ethereum/src/config.ts index 9d61560133f6..005010ac344f 100644 --- a/yarn-project/ethereum/src/config.ts +++ b/yarn-project/ethereum/src/config.ts @@ -29,9 +29,9 @@ export type L1ContractsConfig = { /** The number of epochs after an epoch ends that proofs are still accepted. */ aztecProofSubmissionEpochs: number; /** The deposit amount for a validator */ - depositAmount: bigint; + activationThreshold: bigint; /** The minimum stake for a validator. */ - minimumStake: bigint; + ejectionThreshold: bigint; /** The slashing quorum, i.e. how many slots must signal for the same payload in a round for it to be submittable to the Slasher */ slashingQuorum: number; /** The slashing round size, i.e. how many slots are in a round */ @@ -60,8 +60,8 @@ export const DefaultL1ContractsConfig = { aztecEpochDuration: 32, aztecTargetCommitteeSize: 48, aztecProofSubmissionEpochs: 1, // you have a full epoch to submit a proof after the epoch to prove ends - depositAmount: BigInt(100e18), - minimumStake: BigInt(50e18), + activationThreshold: BigInt(100e18), + ejectionThreshold: BigInt(50e18), slashingQuorum: 101, slashingRoundSize: 200, slashingLifetimeInRounds: 5, @@ -91,7 +91,7 @@ const LocalGovernanceConfiguration = { const TestnetGovernanceConfiguration = { proposeConfig: { lockDelay: 60n * 60n * 24n, - lockAmount: DefaultL1ContractsConfig.depositAmount * 100n, + lockAmount: DefaultL1ContractsConfig.activationThreshold * 100n, }, votingDelay: 60n, votingDuration: 60n * 60n, @@ -99,7 +99,7 @@ const TestnetGovernanceConfiguration = { gracePeriod: 60n * 60n * 24n * 7n, quorum: 3n * 10n ** 17n, // 30% requiredYeaMargin: 4n * 10n ** 16n, // 4% - minimumVotes: DefaultL1ContractsConfig.minimumStake * 200n, + minimumVotes: DefaultL1ContractsConfig.ejectionThreshold * 200n, }; export const getGovernanceConfiguration = (networkName: NetworkNames) => { @@ -110,13 +110,13 @@ export const getGovernanceConfiguration = (networkName: NetworkNames) => { }; const TestnetGSEConfiguration = { - depositAmount: BigInt(100e18), - minimumStake: BigInt(50e18), + activationThreshold: BigInt(100e18), + ejectionThreshold: BigInt(50e18), }; const LocalGSEConfiguration = { - depositAmount: BigInt(100e18), - minimumStake: BigInt(50e18), + activationThreshold: BigInt(100e18), + ejectionThreshold: BigInt(50e18), }; export const getGSEConfiguration = (networkName: NetworkNames) => { @@ -221,15 +221,15 @@ export const l1ContractsConfigMappings: ConfigMappingsType = description: 'The number of epochs after an epoch ends that proofs are still accepted.', ...numberConfigHelper(DefaultL1ContractsConfig.aztecProofSubmissionEpochs), }, - depositAmount: { - env: 'AZTEC_DEPOSIT_AMOUNT', + activationThreshold: { + env: 'AZTEC_ACTIVATION_THRESHOLD', description: 'The deposit amount for a validator', - ...bigintConfigHelper(DefaultL1ContractsConfig.depositAmount), + ...bigintConfigHelper(DefaultL1ContractsConfig.activationThreshold), }, - minimumStake: { - env: 'AZTEC_MINIMUM_STAKE', + ejectionThreshold: { + env: 'AZTEC_EJECTION_THRESHOLD', description: 'The minimum stake for a validator.', - ...bigintConfigHelper(DefaultL1ContractsConfig.minimumStake), + ...bigintConfigHelper(DefaultL1ContractsConfig.ejectionThreshold), }, slashingQuorum: { env: 'AZTEC_SLASHING_QUORUM', diff --git a/yarn-project/ethereum/src/contracts/rollup.ts b/yarn-project/ethereum/src/contracts/rollup.ts index db025d40c54e..493b81f11081 100644 --- a/yarn-project/ethereum/src/contracts/rollup.ts +++ b/yarn-project/ethereum/src/contracts/rollup.ts @@ -186,13 +186,13 @@ export class RollupContract { } @memoize - getMinimumStake() { - return this.rollup.read.getMinimumStake(); + getEjectionThreshold() { + return this.rollup.read.getEjectionThreshold(); } @memoize - getDepositAmount() { - return this.rollup.read.getDepositAmount(); + getActivationThreshold() { + return this.rollup.read.getActivationThreshold(); } @memoize diff --git a/yarn-project/ethereum/src/deploy_l1_contracts.ts b/yarn-project/ethereum/src/deploy_l1_contracts.ts index 38626605820a..68c1371c149f 100644 --- a/yarn-project/ethereum/src/deploy_l1_contracts.ts +++ b/yarn-project/ethereum/src/deploy_l1_contracts.ts @@ -182,8 +182,8 @@ export const deploySharedContracts = async ( const gseAddress = await deployer.deploy(GSEArtifact, [ l1Client.account.address.toString(), stakingAssetAddress.toString(), - gseConfiguration.depositAmount, - gseConfiguration.minimumStake, + gseConfiguration.activationThreshold, + gseConfiguration.ejectionThreshold, ]); logger.verbose(`Deployed GSE at ${gseAddress}`); @@ -431,7 +431,7 @@ export const deployRollupForUpgrade = async ( extendedClient: ExtendedViemWalletClient, args: Omit< DeployL1ContractsArgs, - 'governanceProposerQuorum' | 'governanceProposerRoundSize' | 'minimumStake' | 'depositAmount' + 'governanceProposerQuorum' | 'governanceProposerRoundSize' | 'ejectionThreshold' | 'activationThreshold' >, registryAddress: EthAddress, logger: Logger, @@ -481,7 +481,7 @@ export const deployRollup = async ( deployer: L1Deployer, args: Omit< DeployL1ContractsArgs, - 'governanceProposerQuorum' | 'governanceProposerRoundSize' | 'minimumStake' | 'depositAmount' + 'governanceProposerQuorum' | 'governanceProposerRoundSize' | 'ejectionThreshold' | 'activationThreshold' >, addresses: Pick< L1ContractAddresses, @@ -740,7 +740,7 @@ export const addMultipleValidators = async ( logger: Logger, ) => { const rollup = new RollupContract(extendedClient, rollupAddress); - const depositAmount = await rollup.getDepositAmount(); + const activationThreshold = await rollup.getActivationThreshold(); if (validators && validators.length > 0) { // Check if some of the initial validators are already registered, so we support idempotent deployments if (!acceleratedTestDeployments) { @@ -771,7 +771,7 @@ export const addMultipleValidators = async ( })); // Mint tokens, approve them, use cheat code to initialise validator set without setting up the epoch. - const stakeNeeded = depositAmount * BigInt(validators.length); + const stakeNeeded = activationThreshold * BigInt(validators.length); const { txHash } = await deployer.sendTransaction({ to: stakingAssetAddress, data: encodeFunctionData({ diff --git a/yarn-project/ethereum/src/queries.ts b/yarn-project/ethereum/src/queries.ts index 236bd304c009..6662a9f22cfa 100644 --- a/yarn-project/ethereum/src/queries.ts +++ b/yarn-project/ethereum/src/queries.ts @@ -37,8 +37,8 @@ export async function getL1ContractsConfig( aztecSlotDuration, aztecProofSubmissionEpochs, aztecTargetCommitteeSize, - depositAmount, - minimumStake, + activationThreshold, + ejectionThreshold, governanceProposerQuorum, governanceProposerRoundSize, slashingQuorum, @@ -58,8 +58,8 @@ export async function getL1ContractsConfig( rollup.getSlotDuration(), rollup.getProofSubmissionEpochs(), rollup.getTargetCommitteeSize(), - rollup.getDepositAmount(), - rollup.getMinimumStake(), + rollup.getActivationThreshold(), + rollup.getEjectionThreshold(), governanceProposer.getQuorumSize(), governanceProposer.getRoundSize(), slasherProposer.getQuorumSize(), @@ -83,8 +83,8 @@ export async function getL1ContractsConfig( aztecTargetCommitteeSize: Number(aztecTargetCommitteeSize), governanceProposerQuorum: Number(governanceProposerQuorum), governanceProposerRoundSize: Number(governanceProposerRoundSize), - depositAmount, - minimumStake, + activationThreshold, + ejectionThreshold, slashingQuorum: Number(slashingQuorum), slashingRoundSize: Number(slashingRoundSize), slashingLifetimeInRounds: Number(slashingLifetimeInRounds), diff --git a/yarn-project/foundation/src/config/env_var.ts b/yarn-project/foundation/src/config/env_var.ts index 02878108e66e..644e9d3e3184 100644 --- a/yarn-project/foundation/src/config/env_var.ts +++ b/yarn-project/foundation/src/config/env_var.ts @@ -251,8 +251,8 @@ export type EnvVar = | 'AZTEC_EPOCH_DURATION' | 'AZTEC_TARGET_COMMITTEE_SIZE' | 'AZTEC_PROOF_SUBMISSION_EPOCHS' - | 'AZTEC_DEPOSIT_AMOUNT' - | 'AZTEC_MINIMUM_STAKE' + | 'AZTEC_ACTIVATION_THRESHOLD' + | 'AZTEC_EJECTION_THRESHOLD' | 'AZTEC_MANA_TARGET' | 'AZTEC_PROVING_COST_PER_MANA' | 'AZTEC_SLASHING_QUORUM' diff --git a/yarn-project/slasher/src/slasher_client.test.ts b/yarn-project/slasher/src/slasher_client.test.ts index bfed8833df6c..246033144521 100644 --- a/yarn-project/slasher/src/slasher_client.test.ts +++ b/yarn-project/slasher/src/slasher_client.test.ts @@ -56,7 +56,7 @@ describe('SlasherClient', () => { let rollup: RollupContract; let slashingProposer: SlashingProposerContract; let l1TxUtils: L1TxUtils; - let depositAmount: bigint; + let activationThreshold: bigint; let slasherL1Client: ExtendedViemWalletClient; let testHarnessL1Client: ExtendedViemWalletClient; let ethCheatCodes: EthCheatCodes; @@ -132,7 +132,7 @@ describe('SlasherClient', () => { rollup = new RollupContract(l1TxUtils.client, deployed.l1ContractAddresses.rollupAddress); slashingProposer = await rollup.getSlashingProposer(); - depositAmount = await rollup.getDepositAmount(); + activationThreshold = await rollup.getActivationThreshold(); await retryUntil( async () => { @@ -155,8 +155,8 @@ describe('SlasherClient', () => { }); it('creates payloads when the watcher signals', async () => { - const slashAmount = depositAmount - 1n; - expect(slashAmount).toBeLessThan(depositAmount); + const slashAmount = activationThreshold - 1n; + expect(slashAmount).toBeLessThan(activationThreshold); const committee = await rollup.getCurrentEpochCommittee(); if (!committee) { throw new Error('No committee found'); @@ -253,7 +253,7 @@ describe('SlasherClient', () => { const info = await rollup.getAttesterView(slasherL1Client.account.address); expect(info.effectiveBalance).toBe(0n); - expect(info.exit.amount).toBe(depositAmount - slashAmount); + expect(info.exit.amount).toBe(activationThreshold - slashAmount); }); it('drops payloads beyond TTL', async () => { @@ -264,7 +264,7 @@ describe('SlasherClient', () => { dummyWatcher.triggerSlash([ { validator: EthAddress.random(), - amount: depositAmount, + amount: activationThreshold, offense: Offense.UNKNOWN, }, ]); @@ -284,7 +284,7 @@ describe('SlasherClient', () => { dummyWatcher.triggerSlash([ { validator: EthAddress.random(), - amount: depositAmount, + amount: activationThreshold, offense: Offense.UNKNOWN, }, ]); @@ -308,7 +308,7 @@ describe('SlasherClient', () => { dummyWatcher.triggerSlash([ { validator: EthAddress.random(), - amount: depositAmount, + amount: activationThreshold, offense: Offense.UNKNOWN, }, ]); @@ -378,7 +378,7 @@ describe('SlasherClient', () => { dummyWatcher.triggerSlash([ { validator, - amount: depositAmount, + amount: activationThreshold, offense: Offense.UNKNOWN, }, ]); @@ -389,7 +389,7 @@ describe('SlasherClient', () => { dummyWatcher.triggerSlash([ { validator, - amount: depositAmount, + amount: activationThreshold, offense: Offense.UNKNOWN, }, ]); @@ -398,13 +398,13 @@ describe('SlasherClient', () => { expect(slasherClient.getMonitoredPayloads().length).toEqual(1); expect(slasherClient.getMonitoredPayloads()[0].validators).toEqual([validator]); - expect(slasherClient.getMonitoredPayloads()[0].amounts).toEqual([depositAmount]); + expect(slasherClient.getMonitoredPayloads()[0].amounts).toEqual([activationThreshold]); expect(slasherClient.getMonitoredPayloads()[0].offenses).toEqual([Offense.UNKNOWN]); dummyWatcher.triggerSlash([ { validator, - amount: depositAmount, + amount: activationThreshold, offense: Offense.UNKNOWN, }, ]); @@ -416,7 +416,7 @@ describe('SlasherClient', () => { await awaitMonitoredPayloads(slasherClient); expect(slasherClient.getMonitoredPayloads().length).toEqual(1); expect(slasherClient.getMonitoredPayloads()[0].validators).toEqual([validator]); - expect(slasherClient.getMonitoredPayloads()[0].amounts).toEqual([depositAmount]); + expect(slasherClient.getMonitoredPayloads()[0].amounts).toEqual([activationThreshold]); expect(slasherClient.getMonitoredPayloads()[0].offenses).toEqual([Offense.UNKNOWN]); }); @@ -427,7 +427,7 @@ describe('SlasherClient', () => { dummyWatcher.triggerSlash([ { validator, - amount: depositAmount - 1n, + amount: activationThreshold - 1n, offense: Offense.UNKNOWN, }, ]); @@ -436,7 +436,7 @@ describe('SlasherClient', () => { dummyWatcher.triggerSlash([ { validator, - amount: depositAmount, + amount: activationThreshold, offense: Offense.UNKNOWN, }, ]); @@ -444,10 +444,10 @@ describe('SlasherClient', () => { expect(slasherClient.getMonitoredPayloads().length).toEqual(2); expect(slasherClient.getMonitoredPayloads()[0].validators).toEqual([validator]); - expect(slasherClient.getMonitoredPayloads()[0].amounts).toEqual([depositAmount]); + expect(slasherClient.getMonitoredPayloads()[0].amounts).toEqual([activationThreshold]); expect(slasherClient.getMonitoredPayloads()[0].offenses).toEqual([Offense.UNKNOWN]); expect(slasherClient.getMonitoredPayloads()[1].validators).toEqual([validator]); - expect(slasherClient.getMonitoredPayloads()[1].amounts).toEqual([depositAmount - 1n]); + expect(slasherClient.getMonitoredPayloads()[1].amounts).toEqual([activationThreshold - 1n]); expect(slasherClient.getMonitoredPayloads()[1].offenses).toEqual([Offense.UNKNOWN]); const firstPayload = await slasherClient.getSlashPayload(await rollup.getSlotNumber()); @@ -459,7 +459,7 @@ describe('SlasherClient', () => { expect(slasherClient.getMonitoredPayloads().length).toEqual(1); expect(slasherClient.getMonitoredPayloads()[0].validators).toEqual([validator]); - expect(slasherClient.getMonitoredPayloads()[0].amounts).toEqual([depositAmount - 1n]); + expect(slasherClient.getMonitoredPayloads()[0].amounts).toEqual([activationThreshold - 1n]); expect(slasherClient.getMonitoredPayloads()[0].offenses).toEqual([Offense.UNKNOWN]); });