Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Governor: Sequential Proposal Ids #5290

Open
wants to merge 26 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
a25d139
feat: governor sequential proposal id
arr00 Oct 25, 2024
a4ee283
use super hash
arr00 Oct 25, 2024
e34a8b9
Make `numberOfProposals` private
arr00 Oct 30, 2024
3cf1b80
Update contracts/governance/extensions/GovernorSequentialProposalId.sol
arr00 Oct 31, 2024
9063080
use internal `getProposalId` function
arr00 Nov 1, 2024
8755aa6
hash proposal is view
arr00 Nov 1, 2024
c52f001
Add `_setNextProposalId` helper func
arr00 Nov 4, 2024
d9f3477
Revert if next proposal id set and current proposal not 0
arr00 Nov 4, 2024
b063a61
Add `getNextProposalId` func
arr00 Nov 4, 2024
19dfdf8
Add view function `getProposalId`
arr00 Nov 18, 2024
185b6a3
Set proposal count instead of next
arr00 Nov 18, 2024
cb91e76
tests
Amxx Nov 18, 2024
5ff56da
revert when calling getProposalId before propose
Amxx Nov 18, 2024
f0e9fb5
Rename `getProposalCount` to `proposalCount`
arr00 Nov 19, 2024
becc77a
Update test/helpers/governance.js
Amxx Nov 19, 2024
8ffad72
fix test
arr00 Nov 19, 2024
3e49fb9
add patch
arr00 Nov 22, 2024
41d49c4
fix repropose bug
arr00 Nov 22, 2024
f8cfe02
interface Id
Amxx Nov 25, 2024
76d57a2
code style uniformity
Amxx Nov 25, 2024
74bdb35
require proposal count to be strictly increasing
arr00 Nov 26, 2024
3206080
Merge branch 'master' into feat/sequential-proposal-id-alt-2
arr00 Nov 26, 2024
c174090
update comment
arr00 Nov 26, 2024
9786e76
only allow setting the proposal count from 0
arr00 Nov 27, 2024
df711fe
update docs
arr00 Nov 27, 2024
a04b47f
fix test
arr00 Nov 27, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions contracts/governance/Governor.sol
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ abstract contract Governor is Context, ERC165, EIP712, Nonces, IGovernor, IERC72
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
return
interfaceId == type(IGovernor).interfaceId ||
interfaceId == type(IGovernor).interfaceId ^ IGovernor.getProposalId.selector ||
Amxx marked this conversation as resolved.
Show resolved Hide resolved
interfaceId == type(IERC1155Receiver).interfaceId ||
super.supportsInterface(interfaceId);
}
Expand Down Expand Up @@ -132,6 +132,15 @@ abstract contract Governor is Context, ERC165, EIP712, Nonces, IGovernor, IERC72
return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash)));
}

function getProposalId(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public view virtual returns (uint256) {
return hashProposal(targets, values, calldatas, descriptionHash);
}

/**
* @dev See {IGovernor-state}.
*/
Expand Down Expand Up @@ -317,7 +326,7 @@ abstract contract Governor is Context, ERC165, EIP712, Nonces, IGovernor, IERC72
string memory description,
address proposer
) internal virtual returns (uint256 proposalId) {
proposalId = hashProposal(targets, values, calldatas, keccak256(bytes(description)));
proposalId = getProposalId(targets, values, calldatas, keccak256(bytes(description)));

if (targets.length != values.length || targets.length != calldatas.length || targets.length == 0) {
revert GovernorInvalidProposalLength(targets.length, calldatas.length, values.length);
Expand Down Expand Up @@ -358,7 +367,7 @@ abstract contract Governor is Context, ERC165, EIP712, Nonces, IGovernor, IERC72
bytes[] memory calldatas,
bytes32 descriptionHash
) public virtual returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
uint256 proposalId = getProposalId(targets, values, calldatas, descriptionHash);

_validateStateBitmap(proposalId, _encodeStateBitmap(ProposalState.Succeeded));

Expand Down Expand Up @@ -406,7 +415,7 @@ abstract contract Governor is Context, ERC165, EIP712, Nonces, IGovernor, IERC72
bytes[] memory calldatas,
bytes32 descriptionHash
) public payable virtual returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
uint256 proposalId = getProposalId(targets, values, calldatas, descriptionHash);

_validateStateBitmap(
proposalId,
Expand Down Expand Up @@ -469,7 +478,7 @@ abstract contract Governor is Context, ERC165, EIP712, Nonces, IGovernor, IERC72
// The proposalId will be recomputed in the `_cancel` call further down. However we need the value before we
// do the internal call, because we need to check the proposal state BEFORE the internal `_cancel` call
// changes it. The `hashProposal` duplication has a cost that is limited, and that we accept.
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
uint256 proposalId = getProposalId(targets, values, calldatas, descriptionHash);

// public cancel restrictions (on top of existing _cancel restrictions).
_validateStateBitmap(proposalId, _encodeStateBitmap(ProposalState.Pending));
Expand All @@ -492,7 +501,7 @@ abstract contract Governor is Context, ERC165, EIP712, Nonces, IGovernor, IERC72
bytes[] memory calldatas,
bytes32 descriptionHash
) internal virtual returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
uint256 proposalId = getProposalId(targets, values, calldatas, descriptionHash);

_validateStateBitmap(
proposalId,
Expand Down
10 changes: 10 additions & 0 deletions contracts/governance/IGovernor.sol
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,16 @@ interface IGovernor is IERC165, IERC6372 {
bytes32 descriptionHash
) external pure returns (uint256);

/**
* @dev Function used to get the proposal id from the proposal details
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* @dev Function used to get the proposal id from the proposal details
* @dev Function used to get the proposal id from the proposal details.

*/
function getProposalId(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) external view returns (uint256);

/**
* @notice module:core
* @dev Current state of a proposal, following Compound's convention
Expand Down
46 changes: 46 additions & 0 deletions contracts/governance/extensions/GovernorSequentialProposalId.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import {Governor} from "../Governor.sol";

abstract contract GovernorSequentialProposalId is Governor {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're missing NatSpec here

uint256 private _proposalCount;
mapping(uint256 proposalHash => uint256 proposalId) private _proposalIds;

function getProposalId(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public view virtual override returns (uint256) {
uint256 proposalHash = hashProposal(targets, values, calldatas, descriptionHash);
uint256 storedProposalId = _proposalIds[proposalHash];
if (storedProposalId == 0) revert GovernorNonexistentProposal(0);
return storedProposalId;
}

function _propose(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing NatSpec here too

address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description,
address proposer
) internal virtual override returns (uint256) {
uint256 proposalHash = hashProposal(targets, values, calldatas, keccak256(bytes(description)));
_proposalIds[proposalHash] = ++_proposalCount;

return super._propose(targets, values, calldatas, description, proposer);
arr00 marked this conversation as resolved.
Show resolved Hide resolved
}

/**
* @dev Internal function to set the sequential proposal ID for the next proposal. This is helpful for transitioning from another governing system.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would add a big caveat about decreasing the proposal count. I'd consider enforcing it in a require statement too, not sure if there are significant downsides to that.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The use-case that @arr00 metionned that someone may set the count to type(uint256).max to (temporarily) disable proposing until the correct number is set.

IMO that usecase (prevent any proposal from being submitted could be more cleanly done using the proposal threshold).

This is the require I proposed: #5290 (comment)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would like to get @wildmolasses thoughts here. I'm leaning towards pushing the above approach of just using the proposal threshold.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I'd keep that use case separate. But I do think it's a concern if setting the count to the max uint permanently blocks the governor from functioning... So this is why I'm not all in on enforcing that the update is an increase. A safer thing would be to allow increases of some reasonable size (like uint32), it seems arbitrary but I think it works.

*/
function _setProposalCount(uint256 newProposalCount) internal virtual {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume the purpose of including this function is to allow DAOs that are upgrading to set an initial proposal count in their initializers. If this is the case, I think this should be documented somewhere

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would be in favor of changing this function's name to indicate better what to do with it. In this case, it suggests developers that it should be used within an initializer.

Suggested change
function _setProposalCount(uint256 newProposalCount) internal virtual {
function _initializeProposalCount(uint256 newProposalCount) internal virtual {

_proposalCount = newProposalCount;
}

function proposalCount() public view virtual returns (uint256) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to document this getter. Also, I'd put it up before the _propose function

return _proposalCount;
}
}
39 changes: 39 additions & 0 deletions contracts/mocks/governance/GovernorSequentialProposalIdMock.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import {Governor} from "../../governance/Governor.sol";
import {GovernorSettings} from "../../governance/extensions/GovernorSettings.sol";
import {GovernorCountingSimple} from "../../governance/extensions/GovernorCountingSimple.sol";
import {GovernorVotesQuorumFraction} from "../../governance/extensions/GovernorVotesQuorumFraction.sol";
import {GovernorSequentialProposalId} from "../../governance/extensions/GovernorSequentialProposalId.sol";

abstract contract GovernorSequentialProposalIdMock is
GovernorSettings,
GovernorVotesQuorumFraction,
GovernorCountingSimple,
GovernorSequentialProposalId
{
function proposalThreshold() public view override(Governor, GovernorSettings) returns (uint256) {
return super.proposalThreshold();
}

function getProposalId(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public view virtual override(Governor, GovernorSequentialProposalId) returns (uint256) {
return super.getProposalId(targets, values, calldatas, descriptionHash);
}

function _propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description,
address proposer
) internal virtual override(Governor, GovernorSequentialProposalId) returns (uint256 proposalId) {
return super._propose(targets, values, calldatas, description, proposer);
}
}
186 changes: 186 additions & 0 deletions test/governance/extensions/GovernorSequentialProposalId.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
const { ethers } = require('hardhat');
const { expect } = require('chai');
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
const { anyValue } = require('@nomicfoundation/hardhat-chai-matchers/withArgs');

const { GovernorHelper } = require('../../helpers/governance');
const { VoteType } = require('../../helpers/enums');
const iterate = require('../../helpers/iterate');

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 votingDelay = 4n;
const votingPeriod = 16n;
const value = ethers.parseEther('1');

async function deployToken(contractName) {
try {
return await ethers.deployContract(contractName, [tokenName, tokenSymbol, tokenName, version]);
} catch (error) {
if (error.message == 'incorrect number of arguments to constructor') {
// ERC20VotesLegacyMock has a different construction that uses version='1' by default.
return ethers.deployContract(contractName, [tokenName, tokenSymbol, tokenName]);
}
throw error;
}
}

describe('GovernorSequentialProposalId', function () {
for (const { Token, mode } of TOKENS) {
const fixture = async () => {
const [owner, proposer, voter1, voter2, voter3, voter4, userEOA] = await ethers.getSigners();
const receiver = await ethers.deployContract('CallReceiverMock');

const token = await deployToken(Token, [tokenName, tokenSymbol, version]);
const mock = await ethers.deployContract('$GovernorSequentialProposalIdMock', [
name, // name
votingDelay, // initialVotingDelay
votingPeriod, // initialVotingPeriod
0n, // initialProposalThreshold
token, // tokenAddress
10n, // quorumNumeratorValue
]);

await owner.sendTransaction({ to: mock, value });
await token.$_mint(owner, tokenSupply);

const helper = new GovernorHelper(mock, mode);
await helper.connect(owner).delegate({ token: token, to: voter1, value: ethers.parseEther('10') });
await helper.connect(owner).delegate({ token: token, to: voter2, value: ethers.parseEther('7') });
await helper.connect(owner).delegate({ token: token, to: voter3, value: ethers.parseEther('5') });
await helper.connect(owner).delegate({ token: token, to: voter4, value: ethers.parseEther('2') });

return {
owner,
proposer,
voter1,
voter2,
voter3,
voter4,
userEOA,
receiver,
token,
mock,
helper,
};
};

describe(`using ${Token}`, function () {
beforeEach(async function () {
Object.assign(this, await loadFixture(fixture));

this.proposal = this.helper.setProposal(
[
{
target: this.receiver.target,
data: this.receiver.interface.encodeFunctionData('mockFunction'),
value,
},
],
'<proposal description>',
);
});

it('sequential proposal ids', async function () {
for (const i of iterate.range(1, 10)) {
this.proposal.description = `<proposal description #${i}>`;

expect(this.mock.hashProposal(...this.proposal.shortProposal)).to.eventually.equal(this.proposal.hash);
await expect(this.mock.getProposalId(...this.proposal.shortProposal)).revertedWithCustomError(
this.mock,
'GovernorNonexistentProposal',
);
expect(this.mock.getProposalCount()).to.eventually.equal(i - 1);

await expect(this.helper.connect(this.proposer).propose())
.to.emit(this.mock, 'ProposalCreated')
.withArgs(
i,
this.proposer,
this.proposal.targets,
this.proposal.values,
this.proposal.signatures,
this.proposal.data,
anyValue,
anyValue,
this.proposal.description,
);

expect(this.mock.hashProposal(...this.proposal.shortProposal)).to.eventually.equal(this.proposal.hash);
expect(this.mock.getProposalId(...this.proposal.shortProposal)).to.eventually.equal(i);
expect(this.mock.getProposalCount()).to.eventually.equal(i);
}
});

it('sequential proposal ids with offset start', async function () {
const offset = 69420;
await this.mock.$_setProposalCount(offset);

for (const i of iterate.range(offset + 1, offset + 10)) {
this.proposal.description = `<proposal description #${i}>`;

expect(this.mock.hashProposal(...this.proposal.shortProposal)).to.eventually.equal(this.proposal.hash);
await expect(this.mock.getProposalId(...this.proposal.shortProposal)).revertedWithCustomError(
this.mock,
'GovernorNonexistentProposal',
);
expect(this.mock.getProposalCount()).to.eventually.equal(i - 1);

await expect(this.helper.connect(this.proposer).propose())
.to.emit(this.mock, 'ProposalCreated')
.withArgs(
i,
this.proposer,
this.proposal.targets,
this.proposal.values,
this.proposal.signatures,
this.proposal.data,
anyValue,
anyValue,
this.proposal.description,
);

expect(this.mock.hashProposal(...this.proposal.shortProposal)).to.eventually.equal(this.proposal.hash);
expect(this.mock.getProposalId(...this.proposal.shortProposal)).to.eventually.equal(i);
expect(this.mock.getProposalCount()).to.eventually.equal(i);
}
});

it('nominal workflow', async function () {
await this.helper.connect(this.proposer).propose();
await this.helper.waitForSnapshot();

await expect(this.mock.connect(this.voter1).castVote(1, VoteType.For))
.to.emit(this.mock, 'VoteCast')
.withArgs(this.voter1, 1, VoteType.For, ethers.parseEther('10'), '');

await expect(this.mock.connect(this.voter2).castVote(1, VoteType.For))
.to.emit(this.mock, 'VoteCast')
.withArgs(this.voter2, 1, VoteType.For, ethers.parseEther('7'), '');

await expect(this.mock.connect(this.voter3).castVote(1, VoteType.For))
.to.emit(this.mock, 'VoteCast')
.withArgs(this.voter3, 1, VoteType.For, ethers.parseEther('5'), '');

await expect(this.mock.connect(this.voter4).castVote(1, VoteType.Abstain))
.to.emit(this.mock, 'VoteCast')
.withArgs(this.voter4, 1, VoteType.Abstain, ethers.parseEther('2'), '');

await this.helper.waitForDeadline();

expect(this.helper.execute())
.to.eventually.emit(this.mock, 'ProposalExecuted')
.withArgs(1)
.emit(this.receiver, 'MockFunctionCalled');
});
});
}
});
Loading
Loading