Fix .gitignore: stop tracking ignored files

This commit is contained in:
5t4l1n
2025-07-27 10:39:02 +05:30
parent b42747e9a3
commit 3a87ef0576
625 changed files with 88566 additions and 63 deletions
@@ -0,0 +1,699 @@
const { constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const ethSigUtil = require('eth-sig-util');
const Wallet = require('ethereumjs-wallet').default;
const { fromRpcSig } = require('ethereumjs-util');
const Enums = require('../helpers/enums');
const { getDomain, domainType } = require('../helpers/eip712');
const { GovernorHelper } = require('../helpers/governance');
const { clockFromReceipt } = require('../helpers/time');
const { shouldSupportInterfaces } = require('../utils/introspection/SupportsInterface.behavior');
const { shouldBehaveLikeEIP6372 } = require('./utils/EIP6372.behavior');
const Governor = artifacts.require('$GovernorMock');
const CallReceiver = artifacts.require('CallReceiverMock');
const ERC721 = artifacts.require('$ERC721');
const ERC1155 = artifacts.require('$ERC1155');
const TOKENS = [
{ Token: artifacts.require('$ERC20Votes'), mode: 'blocknumber' },
{ Token: artifacts.require('$ERC20VotesTimestampMock'), mode: 'timestamp' },
{ Token: artifacts.require('$ERC20VotesLegacyMock'), mode: 'blocknumber' },
];
contract('Governor', function (accounts) {
const [owner, proposer, voter1, voter2, voter3, voter4] = accounts;
const name = 'OZ-Governor';
const tokenName = 'MockToken';
const tokenSymbol = 'MTKN';
const tokenSupply = web3.utils.toWei('100');
const votingDelay = web3.utils.toBN(4);
const votingPeriod = web3.utils.toBN(16);
const value = web3.utils.toWei('1');
for (const { mode, Token } of TOKENS) {
describe(`using ${Token._json.contractName}`, function () {
beforeEach(async function () {
this.chainId = await web3.eth.getChainId();
this.token = await Token.new(tokenName, tokenSymbol, tokenName);
this.mock = await Governor.new(
name, // name
votingDelay, // initialVotingDelay
votingPeriod, // initialVotingPeriod
0, // initialProposalThreshold
this.token.address, // tokenAddress
10, // quorumNumeratorValue
);
this.receiver = await CallReceiver.new();
this.helper = new GovernorHelper(this.mock, mode);
await web3.eth.sendTransaction({ from: owner, to: this.mock.address, value });
await this.token.$_mint(owner, tokenSupply);
await this.helper.delegate({ token: this.token, to: voter1, value: web3.utils.toWei('10') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter2, value: web3.utils.toWei('7') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter3, value: web3.utils.toWei('5') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter4, value: web3.utils.toWei('2') }, { from: owner });
this.proposal = this.helper.setProposal(
[
{
target: this.receiver.address,
data: this.receiver.contract.methods.mockFunction().encodeABI(),
value,
},
],
'<proposal description>',
);
});
shouldSupportInterfaces(['ERC165', 'ERC1155Receiver', 'Governor', 'GovernorWithParams', 'GovernorCancel']);
shouldBehaveLikeEIP6372(mode);
it('deployment check', async function () {
expect(await this.mock.name()).to.be.equal(name);
expect(await this.mock.token()).to.be.equal(this.token.address);
expect(await this.mock.votingDelay()).to.be.bignumber.equal(votingDelay);
expect(await this.mock.votingPeriod()).to.be.bignumber.equal(votingPeriod);
expect(await this.mock.quorum(0)).to.be.bignumber.equal('0');
expect(await this.mock.COUNTING_MODE()).to.be.equal('support=bravo&quorum=for,abstain');
});
it('nominal workflow', async function () {
// Before
expect(await this.mock.proposalProposer(this.proposal.id)).to.be.equal(constants.ZERO_ADDRESS);
expect(await this.mock.hasVoted(this.proposal.id, owner)).to.be.equal(false);
expect(await this.mock.hasVoted(this.proposal.id, voter1)).to.be.equal(false);
expect(await this.mock.hasVoted(this.proposal.id, voter2)).to.be.equal(false);
expect(await web3.eth.getBalance(this.mock.address)).to.be.bignumber.equal(value);
expect(await web3.eth.getBalance(this.receiver.address)).to.be.bignumber.equal('0');
// Run proposal
const txPropose = await this.helper.propose({ from: proposer });
expectEvent(txPropose, 'ProposalCreated', {
proposalId: this.proposal.id,
proposer,
targets: this.proposal.targets,
// values: this.proposal.values,
signatures: this.proposal.signatures,
calldatas: this.proposal.data,
voteStart: web3.utils.toBN(await clockFromReceipt[mode](txPropose.receipt)).add(votingDelay),
voteEnd: web3.utils
.toBN(await clockFromReceipt[mode](txPropose.receipt))
.add(votingDelay)
.add(votingPeriod),
description: this.proposal.description,
});
await this.helper.waitForSnapshot();
expectEvent(
await this.helper.vote({ support: Enums.VoteType.For, reason: 'This is nice' }, { from: voter1 }),
'VoteCast',
{
voter: voter1,
support: Enums.VoteType.For,
reason: 'This is nice',
weight: web3.utils.toWei('10'),
},
);
expectEvent(await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 }), 'VoteCast', {
voter: voter2,
support: Enums.VoteType.For,
weight: web3.utils.toWei('7'),
});
expectEvent(await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter3 }), 'VoteCast', {
voter: voter3,
support: Enums.VoteType.Against,
weight: web3.utils.toWei('5'),
});
expectEvent(await this.helper.vote({ support: Enums.VoteType.Abstain }, { from: voter4 }), 'VoteCast', {
voter: voter4,
support: Enums.VoteType.Abstain,
weight: web3.utils.toWei('2'),
});
await this.helper.waitForDeadline();
const txExecute = await this.helper.execute();
expectEvent(txExecute, 'ProposalExecuted', { proposalId: this.proposal.id });
await expectEvent.inTransaction(txExecute.tx, this.receiver, 'MockFunctionCalled');
// After
expect(await this.mock.proposalProposer(this.proposal.id)).to.be.equal(proposer);
expect(await this.mock.hasVoted(this.proposal.id, owner)).to.be.equal(false);
expect(await this.mock.hasVoted(this.proposal.id, voter1)).to.be.equal(true);
expect(await this.mock.hasVoted(this.proposal.id, voter2)).to.be.equal(true);
expect(await web3.eth.getBalance(this.mock.address)).to.be.bignumber.equal('0');
expect(await web3.eth.getBalance(this.receiver.address)).to.be.bignumber.equal(value);
});
it('vote with signature', async function () {
const voterBySig = Wallet.generate();
const voterBySigAddress = web3.utils.toChecksumAddress(voterBySig.getAddressString());
const signature = (contract, message) =>
getDomain(contract)
.then(domain => ({
primaryType: 'Ballot',
types: {
EIP712Domain: domainType(domain),
Ballot: [
{ name: 'proposalId', type: 'uint256' },
{ name: 'support', type: 'uint8' },
],
},
domain,
message,
}))
.then(data => ethSigUtil.signTypedMessage(voterBySig.getPrivateKey(), { data }))
.then(fromRpcSig);
await this.token.delegate(voterBySigAddress, { from: voter1 });
// Run proposal
await this.helper.propose();
await this.helper.waitForSnapshot();
expectEvent(await this.helper.vote({ support: Enums.VoteType.For, signature }), 'VoteCast', {
voter: voterBySigAddress,
support: Enums.VoteType.For,
});
await this.helper.waitForDeadline();
await this.helper.execute();
// After
expect(await this.mock.hasVoted(this.proposal.id, owner)).to.be.equal(false);
expect(await this.mock.hasVoted(this.proposal.id, voter1)).to.be.equal(false);
expect(await this.mock.hasVoted(this.proposal.id, voter2)).to.be.equal(false);
expect(await this.mock.hasVoted(this.proposal.id, voterBySigAddress)).to.be.equal(true);
});
it('send ethers', async function () {
const empty = web3.utils.toChecksumAddress(web3.utils.randomHex(20));
this.proposal = this.helper.setProposal(
[
{
target: empty,
value,
},
],
'<proposal description>',
);
// Before
expect(await web3.eth.getBalance(this.mock.address)).to.be.bignumber.equal(value);
expect(await web3.eth.getBalance(empty)).to.be.bignumber.equal('0');
// Run proposal
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.execute();
// After
expect(await web3.eth.getBalance(this.mock.address)).to.be.bignumber.equal('0');
expect(await web3.eth.getBalance(empty)).to.be.bignumber.equal(value);
});
describe('should revert', function () {
describe('on propose', function () {
it('if proposal already exists', async function () {
await this.helper.propose();
await expectRevert(this.helper.propose(), 'Governor: proposal already exists');
});
});
describe('on vote', function () {
it('if proposal does not exist', async function () {
await expectRevert(
this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }),
'Governor: unknown proposal id',
);
});
it('if voting has not started', async function () {
await this.helper.propose();
await expectRevert(
this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }),
'Governor: vote not currently active',
);
});
it('if support value is invalid', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await expectRevert(
this.helper.vote({ support: web3.utils.toBN('255') }),
'GovernorVotingSimple: invalid value for enum VoteType',
);
});
it('if vote was already casted', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await expectRevert(
this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }),
'GovernorVotingSimple: vote already cast',
);
});
it('if voting is over', async function () {
await this.helper.propose();
await this.helper.waitForDeadline();
await expectRevert(
this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }),
'Governor: vote not currently active',
);
});
});
describe('on execute', function () {
it('if proposal does not exist', async function () {
await expectRevert(this.helper.execute(), 'Governor: unknown proposal id');
});
it('if quorum is not reached', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter3 });
await expectRevert(this.helper.execute(), 'Governor: proposal not successful');
});
it('if score not reached', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter1 });
await expectRevert(this.helper.execute(), 'Governor: proposal not successful');
});
it('if voting is not over', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await expectRevert(this.helper.execute(), 'Governor: proposal not successful');
});
it('if receiver revert without reason', async function () {
this.proposal = this.helper.setProposal(
[
{
target: this.receiver.address,
data: this.receiver.contract.methods.mockFunctionRevertsNoReason().encodeABI(),
},
],
'<proposal description>',
);
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await expectRevert(this.helper.execute(), 'Governor: call reverted without message');
});
it('if receiver revert with reason', async function () {
this.proposal = this.helper.setProposal(
[
{
target: this.receiver.address,
data: this.receiver.contract.methods.mockFunctionRevertsReason().encodeABI(),
},
],
'<proposal description>',
);
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await expectRevert(this.helper.execute(), 'CallReceiverMock: reverting');
});
it('if proposal was already executed', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.execute();
await expectRevert(this.helper.execute(), 'Governor: proposal not successful');
});
});
});
describe('state', function () {
it('Unset', async function () {
await expectRevert(this.mock.state(this.proposal.id), 'Governor: unknown proposal id');
});
it('Pending & Active', async function () {
await this.helper.propose();
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Pending);
await this.helper.waitForSnapshot();
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Pending);
await this.helper.waitForSnapshot(+1);
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Active);
});
it('Defeated', async function () {
await this.helper.propose();
await this.helper.waitForDeadline();
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Active);
await this.helper.waitForDeadline(+1);
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Defeated);
});
it('Succeeded', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Active);
await this.helper.waitForDeadline(+1);
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Succeeded);
});
it('Executed', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.execute();
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Executed);
});
});
describe('cancel', function () {
describe('internal', function () {
it('before proposal', async function () {
await expectRevert(this.helper.cancel('internal'), 'Governor: unknown proposal id');
});
it('after proposal', async function () {
await this.helper.propose();
await this.helper.cancel('internal');
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled);
await this.helper.waitForSnapshot();
await expectRevert(
this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }),
'Governor: vote not currently active',
);
});
it('after vote', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.cancel('internal');
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled);
await this.helper.waitForDeadline();
await expectRevert(this.helper.execute(), 'Governor: proposal not successful');
});
it('after deadline', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.cancel('internal');
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled);
await expectRevert(this.helper.execute(), 'Governor: proposal not successful');
});
it('after execution', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.execute();
await expectRevert(this.helper.cancel('internal'), 'Governor: proposal not active');
});
});
describe('public', function () {
it('before proposal', async function () {
await expectRevert(this.helper.cancel('external'), 'Governor: unknown proposal id');
});
it('after proposal', async function () {
await this.helper.propose();
await this.helper.cancel('external');
});
it('after proposal - restricted to proposer', async function () {
await this.helper.propose();
await expectRevert(this.helper.cancel('external', { from: owner }), 'Governor: only proposer can cancel');
});
it('after vote started', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot(1); // snapshot + 1 block
await expectRevert(this.helper.cancel('external'), 'Governor: too late to cancel');
});
it('after vote', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await expectRevert(this.helper.cancel('external'), 'Governor: too late to cancel');
});
it('after deadline', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await expectRevert(this.helper.cancel('external'), 'Governor: too late to cancel');
});
it('after execution', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.execute();
await expectRevert(this.helper.cancel('external'), 'Governor: too late to cancel');
});
});
});
describe('proposal length', function () {
it('empty', async function () {
this.helper.setProposal([], '<proposal description>');
await expectRevert(this.helper.propose(), 'Governor: empty proposal');
});
it('mismatch #1', async function () {
this.helper.setProposal(
{
targets: [],
values: [web3.utils.toWei('0')],
data: [this.receiver.contract.methods.mockFunction().encodeABI()],
},
'<proposal description>',
);
await expectRevert(this.helper.propose(), 'Governor: invalid proposal length');
});
it('mismatch #2', async function () {
this.helper.setProposal(
{
targets: [this.receiver.address],
values: [],
data: [this.receiver.contract.methods.mockFunction().encodeABI()],
},
'<proposal description>',
);
await expectRevert(this.helper.propose(), 'Governor: invalid proposal length');
});
it('mismatch #3', async function () {
this.helper.setProposal(
{
targets: [this.receiver.address],
values: [web3.utils.toWei('0')],
data: [],
},
'<proposal description>',
);
await expectRevert(this.helper.propose(), 'Governor: invalid proposal length');
});
});
describe('onlyGovernance updates', function () {
it('setVotingDelay is protected', async function () {
await expectRevert(this.mock.setVotingDelay('0'), 'Governor: onlyGovernance');
});
it('setVotingPeriod is protected', async function () {
await expectRevert(this.mock.setVotingPeriod('32'), 'Governor: onlyGovernance');
});
it('setProposalThreshold is protected', async function () {
await expectRevert(this.mock.setProposalThreshold('1000000000000000000'), 'Governor: onlyGovernance');
});
it('can setVotingDelay through governance', async function () {
this.helper.setProposal(
[
{
target: this.mock.address,
data: this.mock.contract.methods.setVotingDelay('0').encodeABI(),
},
],
'<proposal description>',
);
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
expectEvent(await this.helper.execute(), 'VotingDelaySet', { oldVotingDelay: '4', newVotingDelay: '0' });
expect(await this.mock.votingDelay()).to.be.bignumber.equal('0');
});
it('can setVotingPeriod through governance', async function () {
this.helper.setProposal(
[
{
target: this.mock.address,
data: this.mock.contract.methods.setVotingPeriod('32').encodeABI(),
},
],
'<proposal description>',
);
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
expectEvent(await this.helper.execute(), 'VotingPeriodSet', { oldVotingPeriod: '16', newVotingPeriod: '32' });
expect(await this.mock.votingPeriod()).to.be.bignumber.equal('32');
});
it('cannot setVotingPeriod to 0 through governance', async function () {
this.helper.setProposal(
[
{
target: this.mock.address,
data: this.mock.contract.methods.setVotingPeriod('0').encodeABI(),
},
],
'<proposal description>',
);
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await expectRevert(this.helper.execute(), 'GovernorSettings: voting period too low');
});
it('can setProposalThreshold to 0 through governance', async function () {
this.helper.setProposal(
[
{
target: this.mock.address,
data: this.mock.contract.methods.setProposalThreshold('1000000000000000000').encodeABI(),
},
],
'<proposal description>',
);
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
expectEvent(await this.helper.execute(), 'ProposalThresholdSet', {
oldProposalThreshold: '0',
newProposalThreshold: '1000000000000000000',
});
expect(await this.mock.proposalThreshold()).to.be.bignumber.equal('1000000000000000000');
});
});
describe('safe receive', function () {
describe('ERC721', function () {
const name = 'Non Fungible Token';
const symbol = 'NFT';
const tokenId = web3.utils.toBN(1);
beforeEach(async function () {
this.token = await ERC721.new(name, symbol);
await this.token.$_mint(owner, tokenId);
});
it('can receive an ERC721 safeTransfer', async function () {
await this.token.safeTransferFrom(owner, this.mock.address, tokenId, { from: owner });
});
});
describe('ERC1155', function () {
const uri = 'https://token-cdn-domain/{id}.json';
const tokenIds = {
1: web3.utils.toBN(1000),
2: web3.utils.toBN(2000),
3: web3.utils.toBN(3000),
};
beforeEach(async function () {
this.token = await ERC1155.new(uri);
await this.token.$_mintBatch(owner, Object.keys(tokenIds), Object.values(tokenIds), '0x');
});
it('can receive ERC1155 safeTransfer', async function () {
await this.token.safeTransferFrom(
owner,
this.mock.address,
...Object.entries(tokenIds)[0], // id + amount
'0x',
{ from: owner },
);
});
it('can receive ERC1155 safeBatchTransfer', async function () {
await this.token.safeBatchTransferFrom(
owner,
this.mock.address,
Object.keys(tokenIds),
Object.values(tokenIds),
'0x',
{ from: owner },
);
});
});
});
});
}
});
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,283 @@
const { expectEvent, expectRevert } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const RLP = require('rlp');
const Enums = require('../../helpers/enums');
const { GovernorHelper } = require('../../helpers/governance');
const { clockFromReceipt } = require('../../helpers/time');
const Timelock = artifacts.require('CompTimelock');
const Governor = artifacts.require('$GovernorCompatibilityBravoMock');
const CallReceiver = artifacts.require('CallReceiverMock');
const { shouldBehaveLikeEIP6372 } = require('../utils/EIP6372.behavior');
function makeContractAddress(creator, nonce) {
return web3.utils.toChecksumAddress(
web3.utils
.sha3(RLP.encode([creator, nonce]))
.slice(12)
.substring(14),
);
}
const TOKENS = [
{ Token: artifacts.require('$ERC20VotesComp'), mode: 'blocknumber' },
{ Token: artifacts.require('$ERC20VotesCompTimestampMock'), mode: 'timestamp' },
];
contract('GovernorCompatibilityBravo', function (accounts) {
const [owner, proposer, voter1, voter2, voter3, voter4, other] = accounts;
const name = 'OZ-Governor';
// const version = '1';
const tokenName = 'MockToken';
const tokenSymbol = 'MTKN';
const tokenSupply = web3.utils.toWei('100');
const votingDelay = web3.utils.toBN(4);
const votingPeriod = web3.utils.toBN(16);
const proposalThreshold = web3.utils.toWei('10');
const value = web3.utils.toWei('1');
for (const { mode, Token } of TOKENS) {
describe(`using ${Token._json.contractName}`, function () {
beforeEach(async function () {
const [deployer] = await web3.eth.getAccounts();
this.token = await Token.new(tokenName, tokenSymbol, tokenName);
// Need to predict governance address to set it as timelock admin with a delayed transfer
const nonce = await web3.eth.getTransactionCount(deployer);
const predictGovernor = makeContractAddress(deployer, nonce + 1);
this.timelock = await Timelock.new(predictGovernor, 2 * 86400);
this.mock = await Governor.new(
name,
votingDelay,
votingPeriod,
proposalThreshold,
this.timelock.address,
this.token.address,
);
this.receiver = await CallReceiver.new();
this.helper = new GovernorHelper(this.mock, mode);
await web3.eth.sendTransaction({ from: owner, to: this.timelock.address, value });
await this.token.$_mint(owner, tokenSupply);
await this.helper.delegate({ token: this.token, to: proposer, value: proposalThreshold }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter1, value: web3.utils.toWei('10') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter2, value: web3.utils.toWei('7') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter3, value: web3.utils.toWei('5') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter4, value: web3.utils.toWei('2') }, { from: owner });
// default proposal
this.proposal = this.helper.setProposal(
[
{
target: this.receiver.address,
value,
signature: 'mockFunction()',
},
],
'<proposal description>',
);
});
shouldBehaveLikeEIP6372(mode);
it('deployment check', async function () {
expect(await this.mock.name()).to.be.equal(name);
expect(await this.mock.token()).to.be.equal(this.token.address);
expect(await this.mock.votingDelay()).to.be.bignumber.equal(votingDelay);
expect(await this.mock.votingPeriod()).to.be.bignumber.equal(votingPeriod);
expect(await this.mock.quorum(0)).to.be.bignumber.equal('0');
expect(await this.mock.quorumVotes()).to.be.bignumber.equal('0');
expect(await this.mock.COUNTING_MODE()).to.be.equal('support=bravo&quorum=bravo');
});
it('nominal workflow', async function () {
// Before
expect(await this.mock.hasVoted(this.proposal.id, owner)).to.be.equal(false);
expect(await this.mock.hasVoted(this.proposal.id, voter1)).to.be.equal(false);
expect(await this.mock.hasVoted(this.proposal.id, voter2)).to.be.equal(false);
expect(await web3.eth.getBalance(this.mock.address)).to.be.bignumber.equal('0');
expect(await web3.eth.getBalance(this.timelock.address)).to.be.bignumber.equal(value);
expect(await web3.eth.getBalance(this.receiver.address)).to.be.bignumber.equal('0');
// Run proposal
const txPropose = await this.helper.propose({ from: proposer });
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For, reason: 'This is nice' }, { from: voter1 });
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 });
await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter3 });
await this.helper.vote({ support: Enums.VoteType.Abstain }, { from: voter4 });
await this.helper.waitForDeadline();
await this.helper.queue();
await this.helper.waitForEta();
const txExecute = await this.helper.execute();
// After
expect(await this.mock.hasVoted(this.proposal.id, owner)).to.be.equal(false);
expect(await this.mock.hasVoted(this.proposal.id, voter1)).to.be.equal(true);
expect(await this.mock.hasVoted(this.proposal.id, voter2)).to.be.equal(true);
expect(await web3.eth.getBalance(this.mock.address)).to.be.bignumber.equal('0');
expect(await web3.eth.getBalance(this.timelock.address)).to.be.bignumber.equal('0');
expect(await web3.eth.getBalance(this.receiver.address)).to.be.bignumber.equal(value);
const proposal = await this.mock.proposals(this.proposal.id);
expect(proposal.id).to.be.bignumber.equal(this.proposal.id);
expect(proposal.proposer).to.be.equal(proposer);
expect(proposal.eta).to.be.bignumber.equal(await this.mock.proposalEta(this.proposal.id));
expect(proposal.startBlock).to.be.bignumber.equal(await this.mock.proposalSnapshot(this.proposal.id));
expect(proposal.endBlock).to.be.bignumber.equal(await this.mock.proposalDeadline(this.proposal.id));
expect(proposal.canceled).to.be.equal(false);
expect(proposal.executed).to.be.equal(true);
const action = await this.mock.getActions(this.proposal.id);
expect(action.targets).to.be.deep.equal(this.proposal.targets);
// expect(action.values).to.be.deep.equal(this.proposal.values);
expect(action.signatures).to.be.deep.equal(this.proposal.signatures);
expect(action.calldatas).to.be.deep.equal(this.proposal.data);
const voteReceipt1 = await this.mock.getReceipt(this.proposal.id, voter1);
expect(voteReceipt1.hasVoted).to.be.equal(true);
expect(voteReceipt1.support).to.be.bignumber.equal(Enums.VoteType.For);
expect(voteReceipt1.votes).to.be.bignumber.equal(web3.utils.toWei('10'));
const voteReceipt2 = await this.mock.getReceipt(this.proposal.id, voter2);
expect(voteReceipt2.hasVoted).to.be.equal(true);
expect(voteReceipt2.support).to.be.bignumber.equal(Enums.VoteType.For);
expect(voteReceipt2.votes).to.be.bignumber.equal(web3.utils.toWei('7'));
const voteReceipt3 = await this.mock.getReceipt(this.proposal.id, voter3);
expect(voteReceipt3.hasVoted).to.be.equal(true);
expect(voteReceipt3.support).to.be.bignumber.equal(Enums.VoteType.Against);
expect(voteReceipt3.votes).to.be.bignumber.equal(web3.utils.toWei('5'));
const voteReceipt4 = await this.mock.getReceipt(this.proposal.id, voter4);
expect(voteReceipt4.hasVoted).to.be.equal(true);
expect(voteReceipt4.support).to.be.bignumber.equal(Enums.VoteType.Abstain);
expect(voteReceipt4.votes).to.be.bignumber.equal(web3.utils.toWei('2'));
expectEvent(txPropose, 'ProposalCreated', {
proposalId: this.proposal.id,
proposer,
targets: this.proposal.targets,
// values: this.proposal.values,
signatures: this.proposal.signatures.map(() => ''), // this event doesn't contain the proposal detail
calldatas: this.proposal.fulldata,
voteStart: web3.utils.toBN(await clockFromReceipt[mode](txPropose.receipt)).add(votingDelay),
voteEnd: web3.utils
.toBN(await clockFromReceipt[mode](txPropose.receipt))
.add(votingDelay)
.add(votingPeriod),
description: this.proposal.description,
});
expectEvent(txExecute, 'ProposalExecuted', { proposalId: this.proposal.id });
await expectEvent.inTransaction(txExecute.tx, this.receiver, 'MockFunctionCalled');
});
it('double voting is forbidden', async function () {
await this.helper.propose({ from: proposer });
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await expectRevert(
this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }),
'GovernorCompatibilityBravo: vote already cast',
);
});
it('with function selector and arguments', async function () {
const target = this.receiver.address;
this.helper.setProposal(
[
{ target, data: this.receiver.contract.methods.mockFunction().encodeABI() },
{ target, data: this.receiver.contract.methods.mockFunctionWithArgs(17, 42).encodeABI() },
{ target, signature: 'mockFunctionNonPayable()' },
{
target,
signature: 'mockFunctionWithArgs(uint256,uint256)',
data: web3.eth.abi.encodeParameters(['uint256', 'uint256'], [18, 43]),
},
],
'<proposal description>',
);
await this.helper.propose({ from: proposer });
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For, reason: 'This is nice' }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.queue();
await this.helper.waitForEta();
const txExecute = await this.helper.execute();
await expectEvent.inTransaction(txExecute.tx, this.receiver, 'MockFunctionCalled');
await expectEvent.inTransaction(txExecute.tx, this.receiver, 'MockFunctionCalled');
await expectEvent.inTransaction(txExecute.tx, this.receiver, 'MockFunctionCalledWithArgs', {
a: '17',
b: '42',
});
await expectEvent.inTransaction(txExecute.tx, this.receiver, 'MockFunctionCalledWithArgs', {
a: '18',
b: '43',
});
});
it('with inconsistent array size for selector and arguments', async function () {
const target = this.receiver.address;
this.helper.setProposal(
{
targets: [target, target],
values: [0, 0],
signatures: ['mockFunction()'], // One signature
data: ['0x', this.receiver.contract.methods.mockFunctionWithArgs(17, 42).encodeABI()], // Two data entries
},
'<proposal description>',
);
await expectRevert(this.helper.propose({ from: proposer }), 'GovernorBravo: invalid signatures length');
});
describe('should revert', function () {
describe('on propose', function () {
it('if proposal does not meet proposalThreshold', async function () {
await expectRevert(
this.helper.propose({ from: other }),
'Governor: proposer votes below proposal threshold',
);
});
});
describe('on vote', function () {
it('if vote type is invalide', async function () {
await this.helper.propose({ from: proposer });
await this.helper.waitForSnapshot();
await expectRevert(
this.helper.vote({ support: 5 }, { from: voter1 }),
'GovernorCompatibilityBravo: invalid vote type',
);
});
});
});
describe('cancel', function () {
it('proposer can cancel', async function () {
await this.helper.propose({ from: proposer });
await this.helper.cancel('external', { from: proposer });
});
it('anyone can cancel if proposer drop below threshold', async function () {
await this.helper.propose({ from: proposer });
await this.token.transfer(voter1, web3.utils.toWei('1'), { from: proposer });
await this.helper.cancel('external');
});
it('cannot cancel is proposer is still above threshold', async function () {
await this.helper.propose({ from: proposer });
await expectRevert(this.helper.cancel('external'), 'GovernorBravo: proposer above threshold');
});
});
});
}
});
@@ -0,0 +1,88 @@
const { expect } = require('chai');
const Enums = require('../../helpers/enums');
const { GovernorHelper } = require('../../helpers/governance');
const Governor = artifacts.require('$GovernorCompMock');
const CallReceiver = artifacts.require('CallReceiverMock');
const TOKENS = [
{ Token: artifacts.require('$ERC20VotesComp'), mode: 'blocknumber' },
{ Token: artifacts.require('$ERC20VotesCompTimestampMock'), mode: 'timestamp' },
];
contract('GovernorComp', function (accounts) {
const [owner, voter1, voter2, voter3, voter4] = accounts;
const name = 'OZ-Governor';
// const version = '1';
const tokenName = 'MockToken';
const tokenSymbol = 'MTKN';
const tokenSupply = web3.utils.toWei('100');
const votingDelay = web3.utils.toBN(4);
const votingPeriod = web3.utils.toBN(16);
const value = web3.utils.toWei('1');
for (const { mode, Token } of TOKENS) {
describe(`using ${Token._json.contractName}`, function () {
beforeEach(async function () {
this.owner = owner;
this.token = await Token.new(tokenName, tokenSymbol, tokenName);
this.mock = await Governor.new(name, this.token.address);
this.receiver = await CallReceiver.new();
this.helper = new GovernorHelper(this.mock, mode);
await web3.eth.sendTransaction({ from: owner, to: this.mock.address, value });
await this.token.$_mint(owner, tokenSupply);
await this.helper.delegate({ token: this.token, to: voter1, value: web3.utils.toWei('10') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter2, value: web3.utils.toWei('7') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter3, value: web3.utils.toWei('5') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter4, value: web3.utils.toWei('2') }, { from: owner });
// default proposal
this.proposal = this.helper.setProposal(
[
{
target: this.receiver.address,
value,
data: this.receiver.contract.methods.mockFunction().encodeABI(),
},
],
'<proposal description>',
);
});
it('deployment check', async function () {
expect(await this.mock.name()).to.be.equal(name);
expect(await this.mock.token()).to.be.equal(this.token.address);
expect(await this.mock.votingDelay()).to.be.bignumber.equal(votingDelay);
expect(await this.mock.votingPeriod()).to.be.bignumber.equal(votingPeriod);
expect(await this.mock.quorum(0)).to.be.bignumber.equal('0');
});
it('voting with comp token', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 });
await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter3 });
await this.helper.vote({ support: Enums.VoteType.Abstain }, { from: voter4 });
await this.helper.waitForDeadline();
await this.helper.execute();
expect(await this.mock.hasVoted(this.proposal.id, owner)).to.be.equal(false);
expect(await this.mock.hasVoted(this.proposal.id, voter1)).to.be.equal(true);
expect(await this.mock.hasVoted(this.proposal.id, voter2)).to.be.equal(true);
expect(await this.mock.hasVoted(this.proposal.id, voter3)).to.be.equal(true);
expect(await this.mock.hasVoted(this.proposal.id, voter4)).to.be.equal(true);
await this.mock.proposalVotes(this.proposal.id).then(results => {
expect(results.forVotes).to.be.bignumber.equal(web3.utils.toWei('17'));
expect(results.againstVotes).to.be.bignumber.equal(web3.utils.toWei('5'));
expect(results.abstainVotes).to.be.bignumber.equal(web3.utils.toWei('2'));
});
});
});
}
});
@@ -0,0 +1,115 @@
const { expectEvent } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const Enums = require('../../helpers/enums');
const { GovernorHelper } = require('../../helpers/governance');
const Governor = artifacts.require('$GovernorVoteMocks');
const CallReceiver = artifacts.require('CallReceiverMock');
const TOKENS = [
{ Token: artifacts.require('$ERC721Votes'), mode: 'blocknumber' },
{ Token: artifacts.require('$ERC721VotesTimestampMock'), mode: 'timestamp' },
];
contract('GovernorERC721', function (accounts) {
const [owner, voter1, voter2, voter3, voter4] = accounts;
const name = 'OZ-Governor';
// const version = '1';
const tokenName = 'MockNFToken';
const tokenSymbol = 'MTKN';
const NFT0 = web3.utils.toBN(0);
const NFT1 = web3.utils.toBN(1);
const NFT2 = web3.utils.toBN(2);
const NFT3 = web3.utils.toBN(3);
const NFT4 = web3.utils.toBN(4);
const votingDelay = web3.utils.toBN(4);
const votingPeriod = web3.utils.toBN(16);
const value = web3.utils.toWei('1');
for (const { mode, Token } of TOKENS) {
describe(`using ${Token._json.contractName}`, function () {
beforeEach(async function () {
this.owner = owner;
this.token = await Token.new(tokenName, tokenSymbol, tokenName, '1');
this.mock = await Governor.new(name, this.token.address);
this.receiver = await CallReceiver.new();
this.helper = new GovernorHelper(this.mock, mode);
await web3.eth.sendTransaction({ from: owner, to: this.mock.address, value });
await Promise.all([NFT0, NFT1, NFT2, NFT3, NFT4].map(tokenId => this.token.$_mint(owner, tokenId)));
await this.helper.delegate({ token: this.token, to: voter1, tokenId: NFT0 }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter2, tokenId: NFT1 }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter2, tokenId: NFT2 }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter3, tokenId: NFT3 }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter4, tokenId: NFT4 }, { from: owner });
// default proposal
this.proposal = this.helper.setProposal(
[
{
target: this.receiver.address,
value,
data: this.receiver.contract.methods.mockFunction().encodeABI(),
},
],
'<proposal description>',
);
});
it('deployment check', async function () {
expect(await this.mock.name()).to.be.equal(name);
expect(await this.mock.token()).to.be.equal(this.token.address);
expect(await this.mock.votingDelay()).to.be.bignumber.equal(votingDelay);
expect(await this.mock.votingPeriod()).to.be.bignumber.equal(votingPeriod);
expect(await this.mock.quorum(0)).to.be.bignumber.equal('0');
});
it('voting with ERC721 token', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
expectEvent(await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }), 'VoteCast', {
voter: voter1,
support: Enums.VoteType.For,
weight: '1',
});
expectEvent(await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 }), 'VoteCast', {
voter: voter2,
support: Enums.VoteType.For,
weight: '2',
});
expectEvent(await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter3 }), 'VoteCast', {
voter: voter3,
support: Enums.VoteType.Against,
weight: '1',
});
expectEvent(await this.helper.vote({ support: Enums.VoteType.Abstain }, { from: voter4 }), 'VoteCast', {
voter: voter4,
support: Enums.VoteType.Abstain,
weight: '1',
});
await this.helper.waitForDeadline();
await this.helper.execute();
expect(await this.mock.hasVoted(this.proposal.id, owner)).to.be.equal(false);
expect(await this.mock.hasVoted(this.proposal.id, voter1)).to.be.equal(true);
expect(await this.mock.hasVoted(this.proposal.id, voter2)).to.be.equal(true);
expect(await this.mock.hasVoted(this.proposal.id, voter3)).to.be.equal(true);
expect(await this.mock.hasVoted(this.proposal.id, voter4)).to.be.equal(true);
await this.mock.proposalVotes(this.proposal.id).then(results => {
expect(results.forVotes).to.be.bignumber.equal('3');
expect(results.againstVotes).to.be.bignumber.equal('1');
expect(results.abstainVotes).to.be.bignumber.equal('1');
});
});
});
}
});
@@ -0,0 +1,189 @@
const { expectEvent, expectRevert } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const Enums = require('../../helpers/enums');
const { GovernorHelper } = require('../../helpers/governance');
const { clockFromReceipt } = require('../../helpers/time');
const Governor = artifacts.require('$GovernorPreventLateQuorumMock');
const CallReceiver = artifacts.require('CallReceiverMock');
const TOKENS = [
{ Token: artifacts.require('$ERC20Votes'), mode: 'blocknumber' },
{ Token: artifacts.require('$ERC20VotesTimestampMock'), mode: 'timestamp' },
];
contract('GovernorPreventLateQuorum', function (accounts) {
const [owner, proposer, voter1, voter2, voter3, voter4] = accounts;
const name = 'OZ-Governor';
// const version = '1';
const tokenName = 'MockToken';
const tokenSymbol = 'MTKN';
const tokenSupply = web3.utils.toWei('100');
const votingDelay = web3.utils.toBN(4);
const votingPeriod = web3.utils.toBN(16);
const lateQuorumVoteExtension = web3.utils.toBN(8);
const quorum = web3.utils.toWei('1');
const value = web3.utils.toWei('1');
for (const { mode, Token } of TOKENS) {
describe(`using ${Token._json.contractName}`, function () {
beforeEach(async function () {
this.owner = owner;
this.token = await Token.new(tokenName, tokenSymbol, tokenName);
this.mock = await Governor.new(
name,
votingDelay,
votingPeriod,
0,
this.token.address,
lateQuorumVoteExtension,
quorum,
);
this.receiver = await CallReceiver.new();
this.helper = new GovernorHelper(this.mock, mode);
await web3.eth.sendTransaction({ from: owner, to: this.mock.address, value });
await this.token.$_mint(owner, tokenSupply);
await this.helper.delegate({ token: this.token, to: voter1, value: web3.utils.toWei('10') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter2, value: web3.utils.toWei('7') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter3, value: web3.utils.toWei('5') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter4, value: web3.utils.toWei('2') }, { from: owner });
// default proposal
this.proposal = this.helper.setProposal(
[
{
target: this.receiver.address,
value,
data: this.receiver.contract.methods.mockFunction().encodeABI(),
},
],
'<proposal description>',
);
});
it('deployment check', async function () {
expect(await this.mock.name()).to.be.equal(name);
expect(await this.mock.token()).to.be.equal(this.token.address);
expect(await this.mock.votingDelay()).to.be.bignumber.equal(votingDelay);
expect(await this.mock.votingPeriod()).to.be.bignumber.equal(votingPeriod);
expect(await this.mock.quorum(0)).to.be.bignumber.equal(quorum);
expect(await this.mock.lateQuorumVoteExtension()).to.be.bignumber.equal(lateQuorumVoteExtension);
});
it('nominal workflow unaffected', async function () {
const txPropose = await this.helper.propose({ from: proposer });
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 });
await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter3 });
await this.helper.vote({ support: Enums.VoteType.Abstain }, { from: voter4 });
await this.helper.waitForDeadline();
await this.helper.execute();
expect(await this.mock.hasVoted(this.proposal.id, owner)).to.be.equal(false);
expect(await this.mock.hasVoted(this.proposal.id, voter1)).to.be.equal(true);
expect(await this.mock.hasVoted(this.proposal.id, voter2)).to.be.equal(true);
expect(await this.mock.hasVoted(this.proposal.id, voter3)).to.be.equal(true);
expect(await this.mock.hasVoted(this.proposal.id, voter4)).to.be.equal(true);
await this.mock.proposalVotes(this.proposal.id).then(results => {
expect(results.forVotes).to.be.bignumber.equal(web3.utils.toWei('17'));
expect(results.againstVotes).to.be.bignumber.equal(web3.utils.toWei('5'));
expect(results.abstainVotes).to.be.bignumber.equal(web3.utils.toWei('2'));
});
const voteStart = web3.utils.toBN(await clockFromReceipt[mode](txPropose.receipt)).add(votingDelay);
const voteEnd = web3.utils
.toBN(await clockFromReceipt[mode](txPropose.receipt))
.add(votingDelay)
.add(votingPeriod);
expect(await this.mock.proposalSnapshot(this.proposal.id)).to.be.bignumber.equal(voteStart);
expect(await this.mock.proposalDeadline(this.proposal.id)).to.be.bignumber.equal(voteEnd);
expectEvent(txPropose, 'ProposalCreated', {
proposalId: this.proposal.id,
proposer,
targets: this.proposal.targets,
// values: this.proposal.values.map(value => web3.utils.toBN(value)),
signatures: this.proposal.signatures,
calldatas: this.proposal.data,
voteStart,
voteEnd,
description: this.proposal.description,
});
});
it('Delay is extended to prevent last minute take-over', async function () {
const txPropose = await this.helper.propose({ from: proposer });
// compute original schedule
const startBlock = web3.utils.toBN(await clockFromReceipt[mode](txPropose.receipt)).add(votingDelay);
const endBlock = web3.utils
.toBN(await clockFromReceipt[mode](txPropose.receipt))
.add(votingDelay)
.add(votingPeriod);
expect(await this.mock.proposalSnapshot(this.proposal.id)).to.be.bignumber.equal(startBlock);
expect(await this.mock.proposalDeadline(this.proposal.id)).to.be.bignumber.equal(endBlock);
// wait for the last minute to vote
await this.helper.waitForDeadline(-1);
const txVote = await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 });
// cannot execute yet
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Active);
// compute new extended schedule
const extendedDeadline = web3.utils
.toBN(await clockFromReceipt[mode](txVote.receipt))
.add(lateQuorumVoteExtension);
expect(await this.mock.proposalSnapshot(this.proposal.id)).to.be.bignumber.equal(startBlock);
expect(await this.mock.proposalDeadline(this.proposal.id)).to.be.bignumber.equal(extendedDeadline);
// still possible to vote
await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter1 });
await this.helper.waitForDeadline();
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Active);
await this.helper.waitForDeadline(+1);
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Defeated);
// check extension event
expectEvent(txVote, 'ProposalExtended', { proposalId: this.proposal.id, extendedDeadline });
});
describe('onlyGovernance updates', function () {
it('setLateQuorumVoteExtension is protected', async function () {
await expectRevert(this.mock.setLateQuorumVoteExtension(0), 'Governor: onlyGovernance');
});
it('can setLateQuorumVoteExtension through governance', async function () {
this.helper.setProposal(
[
{
target: this.mock.address,
data: this.mock.contract.methods.setLateQuorumVoteExtension('0').encodeABI(),
},
],
'<proposal description>',
);
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
expectEvent(await this.helper.execute(), 'LateQuorumVoteExtensionSet', {
oldVoteExtension: lateQuorumVoteExtension,
newVoteExtension: '0',
});
expect(await this.mock.lateQuorumVoteExtension()).to.be.bignumber.equal('0');
});
});
});
}
});
@@ -0,0 +1,352 @@
const { constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const RLP = require('rlp');
const Enums = require('../../helpers/enums');
const { GovernorHelper } = require('../../helpers/governance');
const { shouldSupportInterfaces } = require('../../utils/introspection/SupportsInterface.behavior');
const Timelock = artifacts.require('CompTimelock');
const Governor = artifacts.require('$GovernorTimelockCompoundMock');
const CallReceiver = artifacts.require('CallReceiverMock');
function makeContractAddress(creator, nonce) {
return web3.utils.toChecksumAddress(
web3.utils
.sha3(RLP.encode([creator, nonce]))
.slice(12)
.substring(14),
);
}
const TOKENS = [
{ Token: artifacts.require('$ERC20Votes'), mode: 'blocknumber' },
{ Token: artifacts.require('$ERC20VotesTimestampMock'), mode: 'timestamp' },
];
contract('GovernorTimelockCompound', function (accounts) {
const [owner, voter1, voter2, voter3, voter4, other] = accounts;
const name = 'OZ-Governor';
// const version = '1';
const tokenName = 'MockToken';
const tokenSymbol = 'MTKN';
const tokenSupply = web3.utils.toWei('100');
const votingDelay = web3.utils.toBN(4);
const votingPeriod = web3.utils.toBN(16);
const value = web3.utils.toWei('1');
for (const { mode, Token } of TOKENS) {
describe(`using ${Token._json.contractName}`, function () {
beforeEach(async function () {
const [deployer] = await web3.eth.getAccounts();
this.token = await Token.new(tokenName, tokenSymbol, tokenName);
// Need to predict governance address to set it as timelock admin with a delayed transfer
const nonce = await web3.eth.getTransactionCount(deployer);
const predictGovernor = makeContractAddress(deployer, nonce + 1);
this.timelock = await Timelock.new(predictGovernor, 2 * 86400);
this.mock = await Governor.new(
name,
votingDelay,
votingPeriod,
0,
this.timelock.address,
this.token.address,
0,
);
this.receiver = await CallReceiver.new();
this.helper = new GovernorHelper(this.mock, mode);
await web3.eth.sendTransaction({ from: owner, to: this.timelock.address, value });
await this.token.$_mint(owner, tokenSupply);
await this.helper.delegate({ token: this.token, to: voter1, value: web3.utils.toWei('10') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter2, value: web3.utils.toWei('7') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter3, value: web3.utils.toWei('5') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter4, value: web3.utils.toWei('2') }, { from: owner });
// default proposal
this.proposal = this.helper.setProposal(
[
{
target: this.receiver.address,
value,
data: this.receiver.contract.methods.mockFunction().encodeABI(),
},
],
'<proposal description>',
);
});
shouldSupportInterfaces(['ERC165', 'Governor', 'GovernorWithParams', 'GovernorTimelock']);
it("doesn't accept ether transfers", async function () {
await expectRevert.unspecified(web3.eth.sendTransaction({ from: owner, to: this.mock.address, value: 1 }));
});
it('post deployment check', async function () {
expect(await this.mock.name()).to.be.equal(name);
expect(await this.mock.token()).to.be.equal(this.token.address);
expect(await this.mock.votingDelay()).to.be.bignumber.equal(votingDelay);
expect(await this.mock.votingPeriod()).to.be.bignumber.equal(votingPeriod);
expect(await this.mock.quorum(0)).to.be.bignumber.equal('0');
expect(await this.mock.timelock()).to.be.equal(this.timelock.address);
expect(await this.timelock.admin()).to.be.equal(this.mock.address);
});
it('nominal', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 });
await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter3 });
await this.helper.vote({ support: Enums.VoteType.Abstain }, { from: voter4 });
await this.helper.waitForDeadline();
const txQueue = await this.helper.queue();
const eta = await this.mock.proposalEta(this.proposal.id);
await this.helper.waitForEta();
const txExecute = await this.helper.execute();
expectEvent(txQueue, 'ProposalQueued', { proposalId: this.proposal.id });
await expectEvent.inTransaction(txQueue.tx, this.timelock, 'QueueTransaction', { eta });
expectEvent(txExecute, 'ProposalExecuted', { proposalId: this.proposal.id });
await expectEvent.inTransaction(txExecute.tx, this.timelock, 'ExecuteTransaction', { eta });
await expectEvent.inTransaction(txExecute.tx, this.receiver, 'MockFunctionCalled');
});
describe('should revert', function () {
describe('on queue', function () {
it('if already queued', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.queue();
await expectRevert(this.helper.queue(), 'Governor: proposal not successful');
});
it('if proposal contains duplicate calls', async function () {
const action = {
target: this.token.address,
data: this.token.contract.methods.approve(this.receiver.address, constants.MAX_UINT256).encodeABI(),
};
this.helper.setProposal([action, action], '<proposal description>');
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await expectRevert(
this.helper.queue(),
'GovernorTimelockCompound: identical proposal action already queued',
);
await expectRevert(this.helper.execute(), 'GovernorTimelockCompound: proposal not yet queued');
});
});
describe('on execute', function () {
it('if not queued', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline(+1);
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Succeeded);
await expectRevert(this.helper.execute(), 'GovernorTimelockCompound: proposal not yet queued');
});
it('if too early', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.queue();
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Queued);
await expectRevert(
this.helper.execute(),
"Timelock::executeTransaction: Transaction hasn't surpassed time lock",
);
});
it('if too late', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.queue();
await this.helper.waitForEta(+30 * 86400);
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Expired);
await expectRevert(this.helper.execute(), 'Governor: proposal not successful');
});
it('if already executed', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.queue();
await this.helper.waitForEta();
await this.helper.execute();
await expectRevert(this.helper.execute(), 'Governor: proposal not successful');
});
});
});
describe('cancel', function () {
it('cancel before queue prevents scheduling', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
expectEvent(await this.helper.cancel('internal'), 'ProposalCanceled', { proposalId: this.proposal.id });
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled);
await expectRevert(this.helper.queue(), 'Governor: proposal not successful');
});
it('cancel after queue prevents executing', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.queue();
expectEvent(await this.helper.cancel('internal'), 'ProposalCanceled', { proposalId: this.proposal.id });
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled);
await expectRevert(this.helper.execute(), 'Governor: proposal not successful');
});
});
describe('onlyGovernance', function () {
describe('relay', function () {
beforeEach(async function () {
await this.token.$_mint(this.mock.address, 1);
});
it('is protected', async function () {
await expectRevert(
this.mock.relay(this.token.address, 0, this.token.contract.methods.transfer(other, 1).encodeABI()),
'Governor: onlyGovernance',
);
});
it('can be executed through governance', async function () {
this.helper.setProposal(
[
{
target: this.mock.address,
data: this.mock.contract.methods
.relay(this.token.address, 0, this.token.contract.methods.transfer(other, 1).encodeABI())
.encodeABI(),
},
],
'<proposal description>',
);
expect(await this.token.balanceOf(this.mock.address), 1);
expect(await this.token.balanceOf(other), 0);
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.queue();
await this.helper.waitForEta();
const txExecute = await this.helper.execute();
expect(await this.token.balanceOf(this.mock.address), 0);
expect(await this.token.balanceOf(other), 1);
await expectEvent.inTransaction(txExecute.tx, this.token, 'Transfer', {
from: this.mock.address,
to: other,
value: '1',
});
});
});
describe('updateTimelock', function () {
beforeEach(async function () {
this.newTimelock = await Timelock.new(this.mock.address, 7 * 86400);
});
it('is protected', async function () {
await expectRevert(this.mock.updateTimelock(this.newTimelock.address), 'Governor: onlyGovernance');
});
it('can be executed through governance to', async function () {
this.helper.setProposal(
[
{
target: this.timelock.address,
data: this.timelock.contract.methods.setPendingAdmin(owner).encodeABI(),
},
{
target: this.mock.address,
data: this.mock.contract.methods.updateTimelock(this.newTimelock.address).encodeABI(),
},
],
'<proposal description>',
);
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.queue();
await this.helper.waitForEta();
const txExecute = await this.helper.execute();
expectEvent(txExecute, 'TimelockChange', {
oldTimelock: this.timelock.address,
newTimelock: this.newTimelock.address,
});
expect(await this.mock.timelock()).to.be.bignumber.equal(this.newTimelock.address);
});
});
it('can transfer timelock to new governor', async function () {
const newGovernor = await Governor.new(name, 8, 32, 0, this.timelock.address, this.token.address, 0);
this.helper.setProposal(
[
{
target: this.timelock.address,
data: this.timelock.contract.methods.setPendingAdmin(newGovernor.address).encodeABI(),
},
],
'<proposal description>',
);
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.queue();
await this.helper.waitForEta();
const txExecute = await this.helper.execute();
await expectEvent.inTransaction(txExecute.tx, this.timelock, 'NewPendingAdmin', {
newPendingAdmin: newGovernor.address,
});
await newGovernor.__acceptAdmin();
expect(await this.timelock.admin()).to.be.bignumber.equal(newGovernor.address);
});
});
});
}
});
@@ -0,0 +1,445 @@
const { constants, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const Enums = require('../../helpers/enums');
const { GovernorHelper } = require('../../helpers/governance');
const { shouldSupportInterfaces } = require('../../utils/introspection/SupportsInterface.behavior');
const Timelock = artifacts.require('TimelockController');
const Governor = artifacts.require('$GovernorTimelockControlMock');
const CallReceiver = artifacts.require('CallReceiverMock');
const TOKENS = [
{ Token: artifacts.require('$ERC20Votes'), mode: 'blocknumber' },
{ Token: artifacts.require('$ERC20VotesTimestampMock'), mode: 'timestamp' },
];
contract('GovernorTimelockControl', function (accounts) {
const [owner, voter1, voter2, voter3, voter4, other] = accounts;
const TIMELOCK_ADMIN_ROLE = web3.utils.soliditySha3('TIMELOCK_ADMIN_ROLE');
const PROPOSER_ROLE = web3.utils.soliditySha3('PROPOSER_ROLE');
const EXECUTOR_ROLE = web3.utils.soliditySha3('EXECUTOR_ROLE');
const CANCELLER_ROLE = web3.utils.soliditySha3('CANCELLER_ROLE');
const name = 'OZ-Governor';
// const version = '1';
const tokenName = 'MockToken';
const tokenSymbol = 'MTKN';
const tokenSupply = web3.utils.toWei('100');
const votingDelay = web3.utils.toBN(4);
const votingPeriod = web3.utils.toBN(16);
const value = web3.utils.toWei('1');
for (const { mode, Token } of TOKENS) {
describe(`using ${Token._json.contractName}`, function () {
beforeEach(async function () {
const [deployer] = await web3.eth.getAccounts();
this.token = await Token.new(tokenName, tokenSymbol, tokenName);
this.timelock = await Timelock.new(3600, [], [], deployer);
this.mock = await Governor.new(
name,
votingDelay,
votingPeriod,
0,
this.timelock.address,
this.token.address,
0,
);
this.receiver = await CallReceiver.new();
this.helper = new GovernorHelper(this.mock, mode);
this.TIMELOCK_ADMIN_ROLE = await this.timelock.TIMELOCK_ADMIN_ROLE();
this.PROPOSER_ROLE = await this.timelock.PROPOSER_ROLE();
this.EXECUTOR_ROLE = await this.timelock.EXECUTOR_ROLE();
this.CANCELLER_ROLE = await this.timelock.CANCELLER_ROLE();
await web3.eth.sendTransaction({ from: owner, to: this.timelock.address, value });
// normal setup: governor is proposer, everyone is executor, timelock is its own admin
await this.timelock.grantRole(PROPOSER_ROLE, this.mock.address);
await this.timelock.grantRole(PROPOSER_ROLE, owner);
await this.timelock.grantRole(CANCELLER_ROLE, this.mock.address);
await this.timelock.grantRole(CANCELLER_ROLE, owner);
await this.timelock.grantRole(EXECUTOR_ROLE, constants.ZERO_ADDRESS);
await this.timelock.revokeRole(TIMELOCK_ADMIN_ROLE, deployer);
await this.token.$_mint(owner, tokenSupply);
await this.helper.delegate({ token: this.token, to: voter1, value: web3.utils.toWei('10') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter2, value: web3.utils.toWei('7') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter3, value: web3.utils.toWei('5') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter4, value: web3.utils.toWei('2') }, { from: owner });
// default proposal
this.proposal = this.helper.setProposal(
[
{
target: this.receiver.address,
value,
data: this.receiver.contract.methods.mockFunction().encodeABI(),
},
],
'<proposal description>',
);
this.proposal.timelockid = await this.timelock.hashOperationBatch(
...this.proposal.shortProposal.slice(0, 3),
'0x0',
this.proposal.shortProposal[3],
);
});
shouldSupportInterfaces(['ERC165', 'Governor', 'GovernorWithParams', 'GovernorTimelock']);
it("doesn't accept ether transfers", async function () {
await expectRevert.unspecified(web3.eth.sendTransaction({ from: owner, to: this.mock.address, value: 1 }));
});
it('post deployment check', async function () {
expect(await this.mock.name()).to.be.equal(name);
expect(await this.mock.token()).to.be.equal(this.token.address);
expect(await this.mock.votingDelay()).to.be.bignumber.equal(votingDelay);
expect(await this.mock.votingPeriod()).to.be.bignumber.equal(votingPeriod);
expect(await this.mock.quorum(0)).to.be.bignumber.equal('0');
expect(await this.mock.timelock()).to.be.equal(this.timelock.address);
});
it('nominal', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 });
await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter3 });
await this.helper.vote({ support: Enums.VoteType.Abstain }, { from: voter4 });
await this.helper.waitForDeadline();
const txQueue = await this.helper.queue();
await this.helper.waitForEta();
const txExecute = await this.helper.execute();
expectEvent(txQueue, 'ProposalQueued', { proposalId: this.proposal.id });
await expectEvent.inTransaction(txQueue.tx, this.timelock, 'CallScheduled', { id: this.proposal.timelockid });
await expectEvent.inTransaction(txQueue.tx, this.timelock, 'CallSalt', {
id: this.proposal.timelockid,
});
expectEvent(txExecute, 'ProposalExecuted', { proposalId: this.proposal.id });
await expectEvent.inTransaction(txExecute.tx, this.timelock, 'CallExecuted', { id: this.proposal.timelockid });
await expectEvent.inTransaction(txExecute.tx, this.receiver, 'MockFunctionCalled');
});
describe('should revert', function () {
describe('on queue', function () {
it('if already queued', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 });
await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter3 });
await this.helper.vote({ support: Enums.VoteType.Abstain }, { from: voter4 });
await this.helper.waitForDeadline();
const txQueue = await this.helper.queue();
await this.helper.waitForEta();
const txExecute = await this.helper.execute();
expectEvent(txQueue, 'ProposalQueued', { proposalId: this.proposal.id });
await expectEvent.inTransaction(txQueue.tx, this.timelock, 'CallScheduled', {
id: this.proposal.timelockid,
});
expectEvent(txExecute, 'ProposalExecuted', { proposalId: this.proposal.id });
await expectEvent.inTransaction(txExecute.tx, this.timelock, 'CallExecuted', {
id: this.proposal.timelockid,
});
await expectEvent.inTransaction(txExecute.tx, this.receiver, 'MockFunctionCalled');
});
describe('should revert', function () {
describe('on queue', function () {
it('if already queued', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.queue();
await expectRevert(this.helper.queue(), 'Governor: proposal not successful');
});
});
describe('on execute', function () {
it('if not queued', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline(+1);
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Succeeded);
await expectRevert(this.helper.execute(), 'TimelockController: operation is not ready');
});
it('if too early', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.queue();
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Queued);
await expectRevert(this.helper.execute(), 'TimelockController: operation is not ready');
});
it('if already executed', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.queue();
await this.helper.waitForEta();
await this.helper.execute();
await expectRevert(this.helper.execute(), 'Governor: proposal not successful');
});
it('if already executed by another proposer', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.queue();
await this.helper.waitForEta();
await this.timelock.executeBatch(
...this.proposal.shortProposal.slice(0, 3),
'0x0',
this.proposal.shortProposal[3],
);
await expectRevert(this.helper.execute(), 'Governor: proposal not successful');
});
});
});
describe('cancel', function () {
it('cancel before queue prevents scheduling', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
expectEvent(await this.helper.cancel('internal'), 'ProposalCanceled', { proposalId: this.proposal.id });
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled);
await expectRevert(this.helper.queue(), 'Governor: proposal not successful');
});
it('cancel after queue prevents executing', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.queue();
expectEvent(await this.helper.cancel('internal'), 'ProposalCanceled', { proposalId: this.proposal.id });
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled);
await expectRevert(this.helper.execute(), 'Governor: proposal not successful');
});
it('cancel on timelock is reflected on governor', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.queue();
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Queued);
expectEvent(await this.timelock.cancel(this.proposal.timelockid, { from: owner }), 'Cancelled', {
id: this.proposal.timelockid,
});
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled);
});
});
describe('onlyGovernance', function () {
describe('relay', function () {
beforeEach(async function () {
await this.token.$_mint(this.mock.address, 1);
});
it('is protected', async function () {
await expectRevert(
this.mock.relay(this.token.address, 0, this.token.contract.methods.transfer(other, 1).encodeABI()),
'Governor: onlyGovernance',
);
});
it('can be executed through governance', async function () {
this.helper.setProposal(
[
{
target: this.mock.address,
data: this.mock.contract.methods
.relay(this.token.address, 0, this.token.contract.methods.transfer(other, 1).encodeABI())
.encodeABI(),
},
],
'<proposal description>',
);
expect(await this.token.balanceOf(this.mock.address), 1);
expect(await this.token.balanceOf(other), 0);
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.queue();
await this.helper.waitForEta();
const txExecute = await this.helper.execute();
expect(await this.token.balanceOf(this.mock.address), 0);
expect(await this.token.balanceOf(other), 1);
await expectEvent.inTransaction(txExecute.tx, this.token, 'Transfer', {
from: this.mock.address,
to: other,
value: '1',
});
});
it('is payable and can transfer eth to EOA', async function () {
const t2g = web3.utils.toBN(128); // timelock to governor
const g2o = web3.utils.toBN(100); // governor to eoa (other)
this.helper.setProposal(
[
{
target: this.mock.address,
value: t2g,
data: this.mock.contract.methods.relay(other, g2o, '0x').encodeABI(),
},
],
'<proposal description>',
);
expect(await web3.eth.getBalance(this.mock.address)).to.be.bignumber.equal(web3.utils.toBN(0));
const timelockBalance = await web3.eth.getBalance(this.timelock.address).then(web3.utils.toBN);
const otherBalance = await web3.eth.getBalance(other).then(web3.utils.toBN);
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.queue();
await this.helper.waitForEta();
await this.helper.execute();
expect(await web3.eth.getBalance(this.timelock.address)).to.be.bignumber.equal(
timelockBalance.sub(t2g),
);
expect(await web3.eth.getBalance(this.mock.address)).to.be.bignumber.equal(t2g.sub(g2o));
expect(await web3.eth.getBalance(other)).to.be.bignumber.equal(otherBalance.add(g2o));
});
it('protected against other proposers', async function () {
await this.timelock.schedule(
this.mock.address,
web3.utils.toWei('0'),
this.mock.contract.methods.relay(constants.ZERO_ADDRESS, 0, '0x').encodeABI(),
constants.ZERO_BYTES32,
constants.ZERO_BYTES32,
3600,
{ from: owner },
);
await time.increase(3600);
await expectRevert(
this.timelock.execute(
this.mock.address,
web3.utils.toWei('0'),
this.mock.contract.methods.relay(constants.ZERO_ADDRESS, 0, '0x').encodeABI(),
constants.ZERO_BYTES32,
constants.ZERO_BYTES32,
{ from: owner },
),
'TimelockController: underlying transaction reverted',
);
});
});
describe('updateTimelock', function () {
beforeEach(async function () {
this.newTimelock = await Timelock.new(
3600,
[this.mock.address],
[this.mock.address],
constants.ZERO_ADDRESS,
);
});
it('is protected', async function () {
await expectRevert(this.mock.updateTimelock(this.newTimelock.address), 'Governor: onlyGovernance');
});
it('can be executed through governance to', async function () {
this.helper.setProposal(
[
{
target: this.mock.address,
data: this.mock.contract.methods.updateTimelock(this.newTimelock.address).encodeABI(),
},
],
'<proposal description>',
);
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.queue();
await this.helper.waitForEta();
const txExecute = await this.helper.execute();
expectEvent(txExecute, 'TimelockChange', {
oldTimelock: this.timelock.address,
newTimelock: this.newTimelock.address,
});
expect(await this.mock.timelock()).to.be.bignumber.equal(this.newTimelock.address);
});
});
});
it('clear queue of pending governor calls', async function () {
this.helper.setProposal(
[
{
target: this.mock.address,
data: this.mock.contract.methods.nonGovernanceFunction().encodeABI(),
},
],
'<proposal description>',
);
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.queue();
await this.helper.waitForEta();
await this.helper.execute();
// This path clears _governanceCall as part of the afterExecute call,
// but we have not way to check that the cleanup actually happened other
// then coverage reports.
});
});
});
});
}
});
@@ -0,0 +1,154 @@
const { expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const Enums = require('../../helpers/enums');
const { GovernorHelper } = require('../../helpers/governance');
const { clock } = require('../../helpers/time');
const Governor = artifacts.require('$GovernorMock');
const CallReceiver = artifacts.require('CallReceiverMock');
const TOKENS = [
{ Token: artifacts.require('$ERC20Votes'), mode: 'blocknumber' },
{ Token: artifacts.require('$ERC20VotesTimestampMock'), mode: 'timestamp' },
];
contract('GovernorVotesQuorumFraction', function (accounts) {
const [owner, voter1, voter2, voter3, voter4] = accounts;
const name = 'OZ-Governor';
// const version = '1';
const tokenName = 'MockToken';
const tokenSymbol = 'MTKN';
const tokenSupply = web3.utils.toBN(web3.utils.toWei('100'));
const ratio = web3.utils.toBN(8); // percents
const newRatio = web3.utils.toBN(6); // percents
const votingDelay = web3.utils.toBN(4);
const votingPeriod = web3.utils.toBN(16);
const value = web3.utils.toWei('1');
for (const { mode, Token } of TOKENS) {
describe(`using ${Token._json.contractName}`, function () {
beforeEach(async function () {
this.owner = owner;
this.token = await Token.new(tokenName, tokenSymbol, tokenName);
this.mock = await Governor.new(name, votingDelay, votingPeriod, 0, this.token.address, ratio);
this.receiver = await CallReceiver.new();
this.helper = new GovernorHelper(this.mock, mode);
await web3.eth.sendTransaction({ from: owner, to: this.mock.address, value });
await this.token.$_mint(owner, tokenSupply);
await this.helper.delegate({ token: this.token, to: voter1, value: web3.utils.toWei('10') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter2, value: web3.utils.toWei('7') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter3, value: web3.utils.toWei('5') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter4, value: web3.utils.toWei('2') }, { from: owner });
// default proposal
this.proposal = this.helper.setProposal(
[
{
target: this.receiver.address,
value,
data: this.receiver.contract.methods.mockFunction().encodeABI(),
},
],
'<proposal description>',
);
});
it('deployment check', async function () {
expect(await this.mock.name()).to.be.equal(name);
expect(await this.mock.token()).to.be.equal(this.token.address);
expect(await this.mock.votingDelay()).to.be.bignumber.equal(votingDelay);
expect(await this.mock.votingPeriod()).to.be.bignumber.equal(votingPeriod);
expect(await this.mock.quorum(0)).to.be.bignumber.equal('0');
expect(await this.mock.quorumNumerator()).to.be.bignumber.equal(ratio);
expect(await this.mock.quorumDenominator()).to.be.bignumber.equal('100');
expect(await clock[mode]().then(timepoint => this.mock.quorum(timepoint - 1))).to.be.bignumber.equal(
tokenSupply.mul(ratio).divn(100),
);
});
it('quroum reached', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await this.helper.execute();
});
it('quroum not reached', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 });
await this.helper.waitForDeadline();
await expectRevert(this.helper.execute(), 'Governor: proposal not successful');
});
describe('onlyGovernance updates', function () {
it('updateQuorumNumerator is protected', async function () {
await expectRevert(this.mock.updateQuorumNumerator(newRatio), 'Governor: onlyGovernance');
});
it('can updateQuorumNumerator through governance', async function () {
this.helper.setProposal(
[
{
target: this.mock.address,
data: this.mock.contract.methods.updateQuorumNumerator(newRatio).encodeABI(),
},
],
'<proposal description>',
);
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
expectEvent(await this.helper.execute(), 'QuorumNumeratorUpdated', {
oldQuorumNumerator: ratio,
newQuorumNumerator: newRatio,
});
expect(await this.mock.quorumNumerator()).to.be.bignumber.equal(newRatio);
expect(await this.mock.quorumDenominator()).to.be.bignumber.equal('100');
// it takes one block for the new quorum to take effect
expect(await clock[mode]().then(blockNumber => this.mock.quorum(blockNumber - 1))).to.be.bignumber.equal(
tokenSupply.mul(ratio).divn(100),
);
await time.advanceBlock();
expect(await clock[mode]().then(blockNumber => this.mock.quorum(blockNumber - 1))).to.be.bignumber.equal(
tokenSupply.mul(newRatio).divn(100),
);
});
it('cannot updateQuorumNumerator over the maximum', async function () {
this.helper.setProposal(
[
{
target: this.mock.address,
data: this.mock.contract.methods.updateQuorumNumerator('101').encodeABI(),
},
],
'<proposal description>',
);
await this.helper.propose();
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await this.helper.waitForDeadline();
await expectRevert(
this.helper.execute(),
'GovernorVotesQuorumFraction: quorumNumerator over quorumDenominator',
);
});
});
});
}
});
@@ -0,0 +1,173 @@
const { expectEvent } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const ethSigUtil = require('eth-sig-util');
const Wallet = require('ethereumjs-wallet').default;
const { fromRpcSig } = require('ethereumjs-util');
const Enums = require('../../helpers/enums');
const { getDomain, domainType } = require('../../helpers/eip712');
const { GovernorHelper } = require('../../helpers/governance');
const Governor = artifacts.require('$GovernorWithParamsMock');
const CallReceiver = artifacts.require('CallReceiverMock');
const rawParams = {
uintParam: web3.utils.toBN('42'),
strParam: 'These are my params',
};
const encodedParams = web3.eth.abi.encodeParameters(['uint256', 'string'], Object.values(rawParams));
const TOKENS = [
{ Token: artifacts.require('$ERC20Votes'), mode: 'blocknumber' },
{ Token: artifacts.require('$ERC20VotesTimestampMock'), mode: 'timestamp' },
];
contract('GovernorWithParams', function (accounts) {
const [owner, proposer, voter1, voter2, voter3, voter4] = accounts;
const name = 'OZ-Governor';
const tokenName = 'MockToken';
const tokenSymbol = 'MTKN';
const tokenSupply = web3.utils.toWei('100');
const votingDelay = web3.utils.toBN(4);
const votingPeriod = web3.utils.toBN(16);
const value = web3.utils.toWei('1');
for (const { mode, Token } of TOKENS) {
describe(`using ${Token._json.contractName}`, function () {
beforeEach(async function () {
this.chainId = await web3.eth.getChainId();
this.token = await Token.new(tokenName, tokenSymbol, tokenName);
this.mock = await Governor.new(name, this.token.address);
this.receiver = await CallReceiver.new();
this.helper = new GovernorHelper(this.mock, mode);
await web3.eth.sendTransaction({ from: owner, to: this.mock.address, value });
await this.token.$_mint(owner, tokenSupply);
await this.helper.delegate({ token: this.token, to: voter1, value: web3.utils.toWei('10') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter2, value: web3.utils.toWei('7') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter3, value: web3.utils.toWei('5') }, { from: owner });
await this.helper.delegate({ token: this.token, to: voter4, value: web3.utils.toWei('2') }, { from: owner });
// default proposal
this.proposal = this.helper.setProposal(
[
{
target: this.receiver.address,
value,
data: this.receiver.contract.methods.mockFunction().encodeABI(),
},
],
'<proposal description>',
);
});
it('deployment check', async function () {
expect(await this.mock.name()).to.be.equal(name);
expect(await this.mock.token()).to.be.equal(this.token.address);
expect(await this.mock.votingDelay()).to.be.bignumber.equal(votingDelay);
expect(await this.mock.votingPeriod()).to.be.bignumber.equal(votingPeriod);
});
it('nominal is unaffected', async function () {
await this.helper.propose({ from: proposer });
await this.helper.waitForSnapshot();
await this.helper.vote({ support: Enums.VoteType.For, reason: 'This is nice' }, { from: voter1 });
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 });
await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter3 });
await this.helper.vote({ support: Enums.VoteType.Abstain }, { from: voter4 });
await this.helper.waitForDeadline();
await this.helper.execute();
expect(await this.mock.hasVoted(this.proposal.id, owner)).to.be.equal(false);
expect(await this.mock.hasVoted(this.proposal.id, voter1)).to.be.equal(true);
expect(await this.mock.hasVoted(this.proposal.id, voter2)).to.be.equal(true);
expect(await web3.eth.getBalance(this.mock.address)).to.be.bignumber.equal('0');
expect(await web3.eth.getBalance(this.receiver.address)).to.be.bignumber.equal(value);
});
it('Voting with params is properly supported', async function () {
await this.helper.propose({ from: proposer });
await this.helper.waitForSnapshot();
const weight = web3.utils.toBN(web3.utils.toWei('7')).sub(rawParams.uintParam);
const tx = await this.helper.vote(
{
support: Enums.VoteType.For,
reason: 'no particular reason',
params: encodedParams,
},
{ from: voter2 },
);
expectEvent(tx, 'CountParams', { ...rawParams });
expectEvent(tx, 'VoteCastWithParams', {
voter: voter2,
proposalId: this.proposal.id,
support: Enums.VoteType.For,
weight,
reason: 'no particular reason',
params: encodedParams,
});
const votes = await this.mock.proposalVotes(this.proposal.id);
expect(votes.forVotes).to.be.bignumber.equal(weight);
});
it('Voting with params by signature is properly supported', async function () {
const voterBySig = Wallet.generate();
const voterBySigAddress = web3.utils.toChecksumAddress(voterBySig.getAddressString());
const signature = (contract, message) =>
getDomain(contract)
.then(domain => ({
primaryType: 'ExtendedBallot',
types: {
EIP712Domain: domainType(domain),
ExtendedBallot: [
{ name: 'proposalId', type: 'uint256' },
{ name: 'support', type: 'uint8' },
{ name: 'reason', type: 'string' },
{ name: 'params', type: 'bytes' },
],
},
domain,
message,
}))
.then(data => ethSigUtil.signTypedMessage(voterBySig.getPrivateKey(), { data }))
.then(fromRpcSig);
await this.token.delegate(voterBySigAddress, { from: voter2 });
// Run proposal
await this.helper.propose();
await this.helper.waitForSnapshot();
const weight = web3.utils.toBN(web3.utils.toWei('7')).sub(rawParams.uintParam);
const tx = await this.helper.vote({
support: Enums.VoteType.For,
reason: 'no particular reason',
params: encodedParams,
signature,
});
expectEvent(tx, 'CountParams', { ...rawParams });
expectEvent(tx, 'VoteCastWithParams', {
voter: voterBySigAddress,
proposalId: this.proposal.id,
support: Enums.VoteType.For,
weight,
reason: 'no particular reason',
params: encodedParams,
});
const votes = await this.mock.proposalVotes(this.proposal.id);
expect(votes.forVotes).to.be.bignumber.equal(weight);
});
});
}
});
@@ -0,0 +1,23 @@
const { clock } = require('../../helpers/time');
function shouldBehaveLikeEIP6372(mode = 'blocknumber') {
describe('should implement EIP6372', function () {
beforeEach(async function () {
this.mock = this.mock ?? this.token ?? this.votes;
});
it('clock is correct', async function () {
expect(await this.mock.clock()).to.be.bignumber.equal(await clock[mode]().then(web3.utils.toBN));
});
it('CLOCK_MODE is correct', async function () {
const params = new URLSearchParams(await this.mock.CLOCK_MODE());
expect(params.get('mode')).to.be.equal(mode);
expect(params.get('from')).to.be.equal(mode == 'blocknumber' ? 'default' : null);
});
});
}
module.exports = {
shouldBehaveLikeEIP6372,
};
@@ -0,0 +1,361 @@
const { constants, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers');
const { MAX_UINT256, ZERO_ADDRESS } = constants;
const { fromRpcSig } = require('ethereumjs-util');
const ethSigUtil = require('eth-sig-util');
const Wallet = require('ethereumjs-wallet').default;
const { shouldBehaveLikeEIP6372 } = require('./EIP6372.behavior');
const { getDomain, domainType, domainSeparator } = require('../../helpers/eip712');
const { clockFromReceipt } = require('../../helpers/time');
const Delegation = [
{ name: 'delegatee', type: 'address' },
{ name: 'nonce', type: 'uint256' },
{ name: 'expiry', type: 'uint256' },
];
function shouldBehaveLikeVotes(mode = 'blocknumber') {
shouldBehaveLikeEIP6372(mode);
describe('run votes workflow', function () {
it('initial nonce is 0', async function () {
expect(await this.votes.nonces(this.account1)).to.be.bignumber.equal('0');
});
it('domain separator', async function () {
expect(await this.votes.DOMAIN_SEPARATOR()).to.equal(domainSeparator(await getDomain(this.votes)));
});
describe('delegation with signature', function () {
const delegator = Wallet.generate();
const delegatorAddress = web3.utils.toChecksumAddress(delegator.getAddressString());
const nonce = 0;
const buildAndSignData = async (contract, message, pk) => {
const data = await getDomain(contract).then(domain => ({
primaryType: 'Delegation',
types: { EIP712Domain: domainType(domain), Delegation },
domain,
message,
}));
return fromRpcSig(ethSigUtil.signTypedMessage(pk, { data }));
};
beforeEach(async function () {
await this.votes.$_mint(delegatorAddress, this.NFT0);
});
it('accept signed delegation', async function () {
const { v, r, s } = await buildAndSignData(
this.votes,
{
delegatee: delegatorAddress,
nonce,
expiry: MAX_UINT256,
},
delegator.getPrivateKey(),
);
expect(await this.votes.delegates(delegatorAddress)).to.be.equal(ZERO_ADDRESS);
const { receipt } = await this.votes.delegateBySig(delegatorAddress, nonce, MAX_UINT256, v, r, s);
const timepoint = await clockFromReceipt[mode](receipt);
expectEvent(receipt, 'DelegateChanged', {
delegator: delegatorAddress,
fromDelegate: ZERO_ADDRESS,
toDelegate: delegatorAddress,
});
expectEvent(receipt, 'DelegateVotesChanged', {
delegate: delegatorAddress,
previousBalance: '0',
newBalance: '1',
});
expect(await this.votes.delegates(delegatorAddress)).to.be.equal(delegatorAddress);
expect(await this.votes.getVotes(delegatorAddress)).to.be.bignumber.equal('1');
expect(await this.votes.getPastVotes(delegatorAddress, timepoint - 1)).to.be.bignumber.equal('0');
await time.advanceBlock();
expect(await this.votes.getPastVotes(delegatorAddress, timepoint)).to.be.bignumber.equal('1');
});
it('rejects reused signature', async function () {
const { v, r, s } = await buildAndSignData(
this.votes,
{
delegatee: delegatorAddress,
nonce,
expiry: MAX_UINT256,
},
delegator.getPrivateKey(),
);
await this.votes.delegateBySig(delegatorAddress, nonce, MAX_UINT256, v, r, s);
await expectRevert(
this.votes.delegateBySig(delegatorAddress, nonce, MAX_UINT256, v, r, s),
'Votes: invalid nonce',
);
});
it('rejects bad delegatee', async function () {
const { v, r, s } = await buildAndSignData(
this.votes,
{
delegatee: delegatorAddress,
nonce,
expiry: MAX_UINT256,
},
delegator.getPrivateKey(),
);
const receipt = await this.votes.delegateBySig(this.account1Delegatee, nonce, MAX_UINT256, v, r, s);
const { args } = receipt.logs.find(({ event }) => event === 'DelegateChanged');
expect(args.delegator).to.not.be.equal(delegatorAddress);
expect(args.fromDelegate).to.be.equal(ZERO_ADDRESS);
expect(args.toDelegate).to.be.equal(this.account1Delegatee);
});
it('rejects bad nonce', async function () {
const { v, r, s } = await buildAndSignData(
this.votes,
{
delegatee: delegatorAddress,
nonce,
expiry: MAX_UINT256,
},
delegator.getPrivateKey(),
);
await expectRevert(
this.votes.delegateBySig(delegatorAddress, nonce + 1, MAX_UINT256, v, r, s),
'Votes: invalid nonce',
);
});
it('rejects expired permit', async function () {
const expiry = (await time.latest()) - time.duration.weeks(1);
const { v, r, s } = await buildAndSignData(
this.votes,
{
delegatee: delegatorAddress,
nonce,
expiry,
},
delegator.getPrivateKey(),
);
await expectRevert(
this.votes.delegateBySig(delegatorAddress, nonce, expiry, v, r, s),
'Votes: signature expired',
);
});
});
describe('set delegation', function () {
describe('call', function () {
it('delegation with tokens', async function () {
await this.votes.$_mint(this.account1, this.NFT0);
expect(await this.votes.delegates(this.account1)).to.be.equal(ZERO_ADDRESS);
const { receipt } = await this.votes.delegate(this.account1, { from: this.account1 });
const timepoint = await clockFromReceipt[mode](receipt);
expectEvent(receipt, 'DelegateChanged', {
delegator: this.account1,
fromDelegate: ZERO_ADDRESS,
toDelegate: this.account1,
});
expectEvent(receipt, 'DelegateVotesChanged', {
delegate: this.account1,
previousBalance: '0',
newBalance: '1',
});
expect(await this.votes.delegates(this.account1)).to.be.equal(this.account1);
expect(await this.votes.getVotes(this.account1)).to.be.bignumber.equal('1');
expect(await this.votes.getPastVotes(this.account1, timepoint - 1)).to.be.bignumber.equal('0');
await time.advanceBlock();
expect(await this.votes.getPastVotes(this.account1, timepoint)).to.be.bignumber.equal('1');
});
it('delegation without tokens', async function () {
expect(await this.votes.delegates(this.account1)).to.be.equal(ZERO_ADDRESS);
const { receipt } = await this.votes.delegate(this.account1, { from: this.account1 });
expectEvent(receipt, 'DelegateChanged', {
delegator: this.account1,
fromDelegate: ZERO_ADDRESS,
toDelegate: this.account1,
});
expectEvent.notEmitted(receipt, 'DelegateVotesChanged');
expect(await this.votes.delegates(this.account1)).to.be.equal(this.account1);
});
});
});
describe('change delegation', function () {
beforeEach(async function () {
await this.votes.$_mint(this.account1, this.NFT0);
await this.votes.delegate(this.account1, { from: this.account1 });
});
it('call', async function () {
expect(await this.votes.delegates(this.account1)).to.be.equal(this.account1);
const { receipt } = await this.votes.delegate(this.account1Delegatee, { from: this.account1 });
const timepoint = await clockFromReceipt[mode](receipt);
expectEvent(receipt, 'DelegateChanged', {
delegator: this.account1,
fromDelegate: this.account1,
toDelegate: this.account1Delegatee,
});
expectEvent(receipt, 'DelegateVotesChanged', {
delegate: this.account1,
previousBalance: '1',
newBalance: '0',
});
expectEvent(receipt, 'DelegateVotesChanged', {
delegate: this.account1Delegatee,
previousBalance: '0',
newBalance: '1',
});
expect(await this.votes.delegates(this.account1)).to.be.equal(this.account1Delegatee);
expect(await this.votes.getVotes(this.account1)).to.be.bignumber.equal('0');
expect(await this.votes.getVotes(this.account1Delegatee)).to.be.bignumber.equal('1');
expect(await this.votes.getPastVotes(this.account1, timepoint - 1)).to.be.bignumber.equal('1');
expect(await this.votes.getPastVotes(this.account1Delegatee, timepoint - 1)).to.be.bignumber.equal('0');
await time.advanceBlock();
expect(await this.votes.getPastVotes(this.account1, timepoint)).to.be.bignumber.equal('0');
expect(await this.votes.getPastVotes(this.account1Delegatee, timepoint)).to.be.bignumber.equal('1');
});
});
describe('getPastTotalSupply', function () {
beforeEach(async function () {
await this.votes.delegate(this.account1, { from: this.account1 });
});
it('reverts if block number >= current block', async function () {
await expectRevert(this.votes.getPastTotalSupply(5e10), 'future lookup');
});
it('returns 0 if there are no checkpoints', async function () {
expect(await this.votes.getPastTotalSupply(0)).to.be.bignumber.equal('0');
});
it('returns the latest block if >= last checkpoint block', async function () {
const { receipt } = await this.votes.$_mint(this.account1, this.NFT0);
const timepoint = await clockFromReceipt[mode](receipt);
await time.advanceBlock();
await time.advanceBlock();
expect(await this.votes.getPastTotalSupply(timepoint - 1)).to.be.bignumber.equal('0');
expect(await this.votes.getPastTotalSupply(timepoint + 1)).to.be.bignumber.equal('1');
});
it('returns zero if < first checkpoint block', async function () {
await time.advanceBlock();
const { receipt } = await this.votes.$_mint(this.account1, this.NFT1);
const timepoint = await clockFromReceipt[mode](receipt);
await time.advanceBlock();
await time.advanceBlock();
expect(await this.votes.getPastTotalSupply(timepoint - 1)).to.be.bignumber.equal('0');
expect(await this.votes.getPastTotalSupply(timepoint + 1)).to.be.bignumber.equal('1');
});
it('generally returns the voting balance at the appropriate checkpoint', async function () {
const t1 = await this.votes.$_mint(this.account1, this.NFT1);
await time.advanceBlock();
await time.advanceBlock();
const t2 = await this.votes.$_burn(this.NFT1);
await time.advanceBlock();
await time.advanceBlock();
const t3 = await this.votes.$_mint(this.account1, this.NFT2);
await time.advanceBlock();
await time.advanceBlock();
const t4 = await this.votes.$_burn(this.NFT2);
await time.advanceBlock();
await time.advanceBlock();
const t5 = await this.votes.$_mint(this.account1, this.NFT3);
await time.advanceBlock();
await time.advanceBlock();
t1.timepoint = await clockFromReceipt[mode](t1.receipt);
t2.timepoint = await clockFromReceipt[mode](t2.receipt);
t3.timepoint = await clockFromReceipt[mode](t3.receipt);
t4.timepoint = await clockFromReceipt[mode](t4.receipt);
t5.timepoint = await clockFromReceipt[mode](t5.receipt);
expect(await this.votes.getPastTotalSupply(t1.timepoint - 1)).to.be.bignumber.equal('0');
expect(await this.votes.getPastTotalSupply(t1.timepoint)).to.be.bignumber.equal('1');
expect(await this.votes.getPastTotalSupply(t1.timepoint + 1)).to.be.bignumber.equal('1');
expect(await this.votes.getPastTotalSupply(t2.timepoint)).to.be.bignumber.equal('0');
expect(await this.votes.getPastTotalSupply(t2.timepoint + 1)).to.be.bignumber.equal('0');
expect(await this.votes.getPastTotalSupply(t3.timepoint)).to.be.bignumber.equal('1');
expect(await this.votes.getPastTotalSupply(t3.timepoint + 1)).to.be.bignumber.equal('1');
expect(await this.votes.getPastTotalSupply(t4.timepoint)).to.be.bignumber.equal('0');
expect(await this.votes.getPastTotalSupply(t4.timepoint + 1)).to.be.bignumber.equal('0');
expect(await this.votes.getPastTotalSupply(t5.timepoint)).to.be.bignumber.equal('1');
expect(await this.votes.getPastTotalSupply(t5.timepoint + 1)).to.be.bignumber.equal('1');
});
});
// The following tests are a adaptation of
// https://github.com/compound-finance/compound-protocol/blob/master/tests/Governance/CompTest.js.
describe('Compound test suite', function () {
beforeEach(async function () {
await this.votes.$_mint(this.account1, this.NFT0);
await this.votes.$_mint(this.account1, this.NFT1);
await this.votes.$_mint(this.account1, this.NFT2);
await this.votes.$_mint(this.account1, this.NFT3);
});
describe('getPastVotes', function () {
it('reverts if block number >= current block', async function () {
await expectRevert(this.votes.getPastVotes(this.account2, 5e10), 'future lookup');
});
it('returns 0 if there are no checkpoints', async function () {
expect(await this.votes.getPastVotes(this.account2, 0)).to.be.bignumber.equal('0');
});
it('returns the latest block if >= last checkpoint block', async function () {
const { receipt } = await this.votes.delegate(this.account2, { from: this.account1 });
const timepoint = await clockFromReceipt[mode](receipt);
await time.advanceBlock();
await time.advanceBlock();
const latest = await this.votes.getVotes(this.account2);
expect(await this.votes.getPastVotes(this.account2, timepoint)).to.be.bignumber.equal(latest);
expect(await this.votes.getPastVotes(this.account2, timepoint + 1)).to.be.bignumber.equal(latest);
});
it('returns zero if < first checkpoint block', async function () {
await time.advanceBlock();
const { receipt } = await this.votes.delegate(this.account2, { from: this.account1 });
const timepoint = await clockFromReceipt[mode](receipt);
await time.advanceBlock();
await time.advanceBlock();
expect(await this.votes.getPastVotes(this.account2, timepoint - 1)).to.be.bignumber.equal('0');
});
});
});
});
}
module.exports = {
shouldBehaveLikeVotes,
};
@@ -0,0 +1,71 @@
const { expectRevert, BN } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const { getChainId } = require('../../helpers/chainid');
const { clockFromReceipt } = require('../../helpers/time');
const { shouldBehaveLikeVotes } = require('./Votes.behavior');
const MODES = {
blocknumber: artifacts.require('$VotesMock'),
timestamp: artifacts.require('$VotesTimestampMock'),
};
contract('Votes', function (accounts) {
const [account1, account2, account3] = accounts;
for (const [mode, artifact] of Object.entries(MODES)) {
describe(`vote with ${mode}`, function () {
beforeEach(async function () {
this.name = 'My Vote';
this.votes = await artifact.new(this.name, '1');
});
it('starts with zero votes', async function () {
expect(await this.votes.getTotalSupply()).to.be.bignumber.equal('0');
});
describe('performs voting operations', function () {
beforeEach(async function () {
this.tx1 = await this.votes.$_mint(account1, 1);
this.tx2 = await this.votes.$_mint(account2, 1);
this.tx3 = await this.votes.$_mint(account3, 1);
this.tx1.timepoint = await clockFromReceipt[mode](this.tx1.receipt);
this.tx2.timepoint = await clockFromReceipt[mode](this.tx2.receipt);
this.tx3.timepoint = await clockFromReceipt[mode](this.tx3.receipt);
});
it('reverts if block number >= current block', async function () {
await expectRevert(this.votes.getPastTotalSupply(this.tx3.timepoint + 1), 'Votes: future lookup');
});
it('delegates', async function () {
await this.votes.delegate(account3, account2);
expect(await this.votes.delegates(account3)).to.be.equal(account2);
});
it('returns total amount of votes', async function () {
expect(await this.votes.getTotalSupply()).to.be.bignumber.equal('3');
});
});
describe('performs voting workflow', function () {
beforeEach(async function () {
this.chainId = await getChainId();
this.account1 = account1;
this.account2 = account2;
this.account1Delegatee = account2;
this.NFT0 = new BN('10000000000000000000000000');
this.NFT1 = new BN('10');
this.NFT2 = new BN('20');
this.NFT3 = new BN('30');
});
// includes EIP6372 behavior check
shouldBehaveLikeVotes(mode);
});
});
}
});