Add a governance extension that implements super quorum (#5492)

Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Arr00 <13561405+arr00@users.noreply.github.com>
This commit is contained in:
Michalis Kargakis
2025-02-28 21:13:07 +01:00
committed by GitHub
parent ddba55780a
commit 7276774f34
13 changed files with 767 additions and 16 deletions

View File

@ -0,0 +1,168 @@
const { ethers } = require('hardhat');
const { expect } = require('chai');
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
const { GovernorHelper } = require('../../helpers/governance');
const { ProposalState, VoteType } = require('../../helpers/enums');
const time = require('../../helpers/time');
const TOKENS = [
{ Token: '$ERC20Votes', mode: 'blocknumber' },
{ Token: '$ERC20VotesTimestampMock', mode: 'timestamp' },
];
const DEFAULT_ADMIN_ROLE = ethers.ZeroHash;
const PROPOSER_ROLE = ethers.id('PROPOSER_ROLE');
const EXECUTOR_ROLE = ethers.id('EXECUTOR_ROLE');
const CANCELLER_ROLE = ethers.id('CANCELLER_ROLE');
const name = 'OZ-Governor';
const version = '1';
const tokenName = 'MockToken';
const tokenSymbol = 'MTKN';
const tokenSupply = ethers.parseEther('100');
const votingDelay = 4n;
const votingPeriod = 16n;
const quorum = 10n;
const superQuorum = 40n;
const value = ethers.parseEther('1');
const delay = time.duration.hours(1n);
describe('GovernorSuperQuorum', function () {
for (const { Token, mode } of TOKENS) {
const fixture = async () => {
const [proposer, voter1, voter2, voter3, voter4, voter5] = await ethers.getSigners();
const receiver = await ethers.deployContract('CallReceiverMock');
const timelock = await ethers.deployContract('TimelockController', [delay, [], [], proposer]);
const token = await ethers.deployContract(Token, [tokenName, tokenSymbol, tokenName, version]);
const mock = await ethers.deployContract('$GovernorSuperQuorumMock', [
name,
votingDelay, // initialVotingDelay
votingPeriod, // initialVotingPeriod
0n, // initialProposalThreshold
token,
timelock,
quorum,
superQuorum,
]);
await proposer.sendTransaction({ to: timelock, value });
await token.$_mint(proposer, tokenSupply);
await timelock.grantRole(PROPOSER_ROLE, mock);
await timelock.grantRole(PROPOSER_ROLE, proposer);
await timelock.grantRole(CANCELLER_ROLE, mock);
await timelock.grantRole(CANCELLER_ROLE, proposer);
await timelock.grantRole(EXECUTOR_ROLE, ethers.ZeroAddress);
await timelock.revokeRole(DEFAULT_ADMIN_ROLE, proposer);
const helper = new GovernorHelper(mock, mode);
await helper.connect(proposer).delegate({ token, to: voter1, value: 40 });
await helper.connect(proposer).delegate({ token, to: voter2, value: 30 });
await helper.connect(proposer).delegate({ token, to: voter3, value: 20 });
await helper.connect(proposer).delegate({ token, to: voter4, value: 15 });
await helper.connect(proposer).delegate({ token, to: voter5, value: 5 });
return { proposer, voter1, voter2, voter3, voter4, voter5, receiver, token, mock, timelock, helper };
};
describe(`using ${Token}`, function () {
beforeEach(async function () {
Object.assign(this, await loadFixture(fixture));
// default proposal
this.proposal = this.helper.setProposal(
[
{
target: this.receiver.target,
value,
data: this.receiver.interface.encodeFunctionData('mockFunction'),
},
],
'<proposal description>',
);
});
it('deployment check', async function () {
await expect(this.mock.name()).to.eventually.equal(name);
await expect(this.mock.token()).to.eventually.equal(this.token);
await expect(this.mock.quorum(0)).to.eventually.equal(quorum);
await expect(this.mock.superQuorum(0)).to.eventually.equal(superQuorum);
});
it('proposal succeeds early when super quorum is reached', async function () {
await this.helper.connect(this.proposer).propose();
await this.helper.waitForSnapshot();
// Vote with voter2 (30) - above quorum (10) but below super quorum (40)
await this.helper.connect(this.voter2).vote({ support: VoteType.For });
await expect(this.mock.state(this.proposal.id)).to.eventually.equal(ProposalState.Active);
// Vote with voter3 (20) to reach super quorum (50 total > 40)
await this.helper.connect(this.voter3).vote({ support: VoteType.For });
await expect(this.mock.proposalEta(this.proposal.id)).to.eventually.equal(0);
// Should be succeeded since we reached super quorum and no eta is set
await expect(this.mock.state(this.proposal.id)).to.eventually.equal(ProposalState.Succeeded);
});
it('proposal remains active if super quorum is not reached', async function () {
await this.helper.connect(this.proposer).propose();
await this.helper.waitForSnapshot();
// Vote with voter4 (15) - below super quorum (40) but above quorum (10)
await this.helper.connect(this.voter4).vote({ support: VoteType.For });
await expect(this.mock.state(this.proposal.id)).to.eventually.equal(ProposalState.Active);
// Vote with voter5 (5) - still below super quorum (total 20 < 40)
await this.helper.connect(this.voter5).vote({ support: VoteType.For });
await expect(this.mock.state(this.proposal.id)).to.eventually.equal(ProposalState.Active);
// Wait for deadline
await this.helper.waitForDeadline(1n);
// Should succeed since deadline passed and we have enough support (20 > 10 quorum)
await expect(this.mock.state(this.proposal.id)).to.eventually.equal(ProposalState.Succeeded);
});
it('proposal remains active if super quorum is reached but vote fails', async function () {
await this.helper.connect(this.proposer).propose();
await this.helper.waitForSnapshot();
// Vote against with voter2 and voter3 (50)
await this.helper.connect(this.voter2).vote({ support: VoteType.Against });
await this.helper.connect(this.voter3).vote({ support: VoteType.Against });
// Vote for with voter1 (40) (reaching super quorum)
await this.helper.connect(this.voter1).vote({ support: VoteType.For });
// should be active since super quorum is reached but vote fails
await expect(this.mock.state(this.proposal.id)).to.eventually.equal(ProposalState.Active);
// wait for deadline
await this.helper.waitForDeadline(1n);
// should be defeated since against votes are higher
await expect(this.mock.state(this.proposal.id)).to.eventually.equal(ProposalState.Defeated);
});
it('proposal is queued if super quorum is reached and eta is set', async function () {
await this.helper.connect(this.proposer).propose();
await this.helper.waitForSnapshot();
// Vote with voter1 (40) - reaching super quorum
await this.helper.connect(this.voter1).vote({ support: VoteType.For });
await this.helper.queue();
// Queueing should set eta
await expect(this.mock.proposalEta(this.proposal.id)).to.eventually.not.equal(0);
// Should be queued since we reached super quorum and eta is set
await expect(this.mock.state(this.proposal.id)).to.eventually.equal(ProposalState.Queued);
});
});
}
});

View File

@ -0,0 +1,79 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {Test} from "forge-std/Test.sol";
import {GovernorVotesSuperQuorumFractionMock} from "../../../contracts/mocks/governance/GovernorVotesSuperQuorumFractionMock.sol";
import {GovernorVotesQuorumFraction} from "../../../contracts/governance/extensions/GovernorVotesQuorumFraction.sol";
import {GovernorVotesSuperQuorumFraction} from "../../../contracts/governance/extensions/GovernorVotesSuperQuorumFraction.sol";
import {GovernorSettings} from "../../../contracts/governance/extensions/GovernorSettings.sol";
import {GovernorVotes} from "../../../contracts/governance/extensions/GovernorVotes.sol";
import {Governor} from "../../../contracts/governance/Governor.sol";
import {IVotes} from "../../../contracts/governance/utils/IVotes.sol";
import {ERC20VotesExtendedTimestampMock} from "../../../contracts/mocks/token/ERC20VotesAdditionalCheckpointsMock.sol";
import {EIP712} from "../../../contracts/utils/cryptography/EIP712.sol";
import {ERC20} from "../../../contracts/token/ERC20/ERC20.sol";
contract TokenMock is ERC20VotesExtendedTimestampMock {
constructor() ERC20("Mock Token", "MTK") EIP712("Mock Token", "1") {}
}
/**
* Main responsibility: expose the functions that are relevant to the simulation
*/
contract GovernorHandler is GovernorVotesSuperQuorumFractionMock {
constructor(
string memory name_,
uint48 votingDelay_,
uint32 votingPeriod_,
uint256 proposalThreshold_,
IVotes token_,
uint256 quorumNumerator_,
uint256 superQuorumNumerator_
)
Governor(name_)
GovernorSettings(votingDelay_, votingPeriod_, proposalThreshold_)
GovernorVotes(token_)
GovernorVotesQuorumFraction(quorumNumerator_)
GovernorVotesSuperQuorumFraction(superQuorumNumerator_)
{}
// solhint-disable-next-line func-name-mixedcase
function $_updateSuperQuorumNumerator(uint256 newSuperQuorumNumerator) public {
_updateSuperQuorumNumerator(newSuperQuorumNumerator);
}
// solhint-disable-next-line func-name-mixedcase
function $_updateQuorumNumerator(uint256 newQuorumNumerator) public {
_updateQuorumNumerator(newQuorumNumerator);
}
}
contract GovernorSuperQuorumGreaterThanQuorum is Test {
GovernorHandler private _governorHandler;
function setUp() external {
_governorHandler = new GovernorHandler(
"GovernorName",
0, // votingDelay
1e4, // votingPeriod
0, // proposalThreshold
new TokenMock(), // token
10, // quorumNumerator
50 // superQuorumNumerator
);
// limit the fuzzer scope
bytes4[] memory selectors = new bytes4[](2);
selectors[0] = GovernorHandler.$_updateSuperQuorumNumerator.selector;
selectors[1] = GovernorHandler.$_updateQuorumNumerator.selector;
targetContract(address(_governorHandler));
targetSelector(FuzzSelector(address(_governorHandler), selectors));
}
// solhint-disable-next-line func-name-mixedcase
function invariant_superQuorumGreaterThanQuorum() external view {
assertGe(_governorHandler.superQuorumNumerator(), _governorHandler.quorumNumerator());
}
}

View File

@ -0,0 +1,160 @@
const { ethers } = require('hardhat');
const { expect } = require('chai');
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
const { GovernorHelper } = require('../../helpers/governance');
const { ProposalState, VoteType } = require('../../helpers/enums');
const time = require('../../helpers/time');
const TOKENS = [
{ Token: '$ERC20Votes', mode: 'blocknumber' },
{ Token: '$ERC20VotesTimestampMock', mode: 'timestamp' },
];
const name = 'OZ-Governor';
const version = '1';
const tokenName = 'MockToken';
const tokenSymbol = 'MTKN';
const tokenSupply = ethers.parseEther('100');
const quorumRatio = 8n; // percents
const superQuorumRatio = 50n; // percents
const newSuperQuorumRatio = 15n; // percents
const votingDelay = 4n;
const votingPeriod = 16n;
const value = ethers.parseEther('1');
describe('GovernorVotesSuperQuorumFraction', function () {
for (const { Token, mode } of TOKENS) {
const fixture = async () => {
const [owner, voter1, voter2, voter3, voter4] = await ethers.getSigners();
const receiver = await ethers.deployContract('CallReceiverMock');
const token = await ethers.deployContract(Token, [tokenName, tokenSymbol, tokenName, version]);
const mock = await ethers.deployContract('$GovernorVotesSuperQuorumFractionMock', [
name,
votingDelay,
votingPeriod,
0n,
token,
quorumRatio,
superQuorumRatio,
]);
await owner.sendTransaction({ to: mock, value });
await token.$_mint(owner, tokenSupply);
const helper = new GovernorHelper(mock, mode);
await helper.connect(owner).delegate({ token, to: voter1, value: ethers.parseEther('30') });
await helper.connect(owner).delegate({ token, to: voter2, value: ethers.parseEther('20') });
await helper.connect(owner).delegate({ token, to: voter3, value: ethers.parseEther('15') });
await helper.connect(owner).delegate({ token, to: voter4, value: ethers.parseEther('5') });
return { owner, voter1, voter2, voter3, voter4, receiver, token, mock, helper };
};
describe(`using ${Token}`, function () {
beforeEach(async function () {
Object.assign(this, await loadFixture(fixture));
// default proposal
this.proposal = this.helper.setProposal(
[
{
target: this.receiver.target,
value,
data: this.receiver.interface.encodeFunctionData('mockFunction'),
},
],
'<proposal description>',
);
});
it('deployment check', async function () {
await expect(this.mock.name()).to.eventually.eventually.equal(name);
await expect(this.mock.token()).to.eventually.equal(this.token);
await expect(this.mock.votingDelay()).to.eventually.equal(votingDelay);
await expect(this.mock.votingPeriod()).to.eventually.equal(votingPeriod);
await expect(this.mock.quorumNumerator()).to.eventually.equal(quorumRatio);
await expect(this.mock.superQuorumNumerator()).to.eventually.equal(superQuorumRatio);
await expect(this.mock.quorumDenominator()).to.eventually.equal(100n);
await expect(time.clock[mode]().then(clock => this.mock.superQuorum(clock - 1n))).to.eventually.equal(
(tokenSupply * superQuorumRatio) / 100n,
);
});
it('proposal remains active until super quorum is reached', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
// Vote with voter1 (30%) - above quorum (8%) but below super quorum (50%)
await this.helper.connect(this.voter1).vote({ support: VoteType.For });
// Check proposal is still active
await expect(this.mock.state(this.proposal.id)).to.eventually.equal(ProposalState.Active);
// Vote with voter2 (20%) - now matches super quorum
await this.helper.connect(this.voter2).vote({ support: VoteType.For });
// Proposal should no longer be active
await expect(this.mock.state(this.proposal.id)).to.eventually.equal(ProposalState.Succeeded);
});
describe('super quorum updates', function () {
it('updateSuperQuorumNumerator is protected', async function () {
await expect(this.mock.connect(this.owner).updateSuperQuorumNumerator(newSuperQuorumRatio))
.to.be.revertedWithCustomError(this.mock, 'GovernorOnlyExecutor')
.withArgs(this.owner);
});
it('can update super quorum through governance', async function () {
this.helper.setProposal(
[
{
target: this.mock.target,
data: this.mock.interface.encodeFunctionData('updateSuperQuorumNumerator', [newSuperQuorumRatio]),
},
],
'<proposal description>',
);
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.connect(this.voter1).vote({ support: VoteType.For });
await this.helper.connect(this.voter2).vote({ support: VoteType.For });
await this.helper.waitForDeadline();
await expect(this.helper.execute())
.to.emit(this.mock, 'SuperQuorumNumeratorUpdated')
.withArgs(superQuorumRatio, newSuperQuorumRatio);
await expect(this.mock.superQuorumNumerator()).to.eventually.equal(newSuperQuorumRatio);
});
it('cannot set super quorum below quorum', async function () {
const invalidSuperQuorum = quorumRatio - 1n;
await expect(this.mock.$_updateSuperQuorumNumerator(invalidSuperQuorum))
.to.be.revertedWithCustomError(this.mock, 'GovernorInvalidSuperQuorumTooSmall')
.withArgs(invalidSuperQuorum, quorumRatio);
});
it('cannot set super quorum above denominator', async function () {
const denominator = await this.mock.quorumDenominator();
const invalidSuperQuorum = BigInt(denominator) + 1n;
await expect(this.mock.$_updateSuperQuorumNumerator(invalidSuperQuorum))
.to.be.revertedWithCustomError(this.mock, 'GovernorInvalidSuperQuorumFraction')
.withArgs(invalidSuperQuorum, denominator);
});
it('cannot set quorum above super quorum', async function () {
const invalidQuorum = superQuorumRatio + 1n;
await expect(this.mock.$_updateQuorumNumerator(invalidQuorum))
.to.be.revertedWithCustomError(this.mock, 'GovernorInvalidQuorumTooLarge')
.withArgs(invalidQuorum, superQuorumRatio);
});
});
});
}
});