Commit d85136b4 by github-actions

Merge upstream master into patched/master

parents fdc9cc04 6a5bbfc4
const { BN, constants, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers'); const { BN, expectEvent, expectRevert } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const ethSigUtil = require('eth-sig-util'); const ethSigUtil = require('eth-sig-util');
const Wallet = require('ethereumjs-wallet').default; const Wallet = require('ethereumjs-wallet').default;
const { fromRpcSig } = require('ethereumjs-util');
const Enums = require('../helpers/enums'); const Enums = require('../helpers/enums');
const { EIP712Domain } = require('../helpers/eip712'); const { EIP712Domain } = require('../helpers/eip712');
const { fromRpcSig } = require('ethereumjs-util'); const { GovernorHelper } = require('../helpers/governance');
const {
runGovernorWorkflow,
} = require('./GovernorWorkflow.behavior');
const { const {
shouldSupportInterfaces, shouldSupportInterfaces,
...@@ -19,23 +17,40 @@ const CallReceiver = artifacts.require('CallReceiverMock'); ...@@ -19,23 +17,40 @@ const CallReceiver = artifacts.require('CallReceiverMock');
contract('Governor', function (accounts) { contract('Governor', function (accounts) {
const [ owner, proposer, voter1, voter2, voter3, voter4 ] = accounts; const [ owner, proposer, voter1, voter2, voter3, voter4 ] = accounts;
const empty = web3.utils.toChecksumAddress(web3.utils.randomHex(20));
const name = 'OZ-Governor'; const name = 'OZ-Governor';
const version = '1'; const version = '1';
const tokenName = 'MockToken'; const tokenName = 'MockToken';
const tokenSymbol = 'MTKN'; const tokenSymbol = 'MTKN';
const tokenSupply = web3.utils.toWei('100'); const tokenSupply = web3.utils.toWei('100');
const votingDelay = new BN(4);
const votingPeriod = new BN(16);
const value = web3.utils.toWei('1');
beforeEach(async function () { beforeEach(async function () {
this.owner = owner; this.chainId = await web3.eth.getChainId();
this.token = await Token.new(tokenName, tokenSymbol); this.token = await Token.new(tokenName, tokenSymbol);
this.mock = await Governor.new(name, this.token.address, 4, 16, 10); this.mock = await Governor.new(name, this.token.address, votingDelay, votingPeriod, 10);
this.receiver = await CallReceiver.new(); this.receiver = await CallReceiver.new();
this.helper = new GovernorHelper(this.mock);
await web3.eth.sendTransaction({ from: owner, to: this.mock.address, value });
await this.token.mint(owner, tokenSupply); await this.token.mint(owner, tokenSupply);
await this.token.delegate(voter1, { from: voter1 }); await this.helper.delegate({ token: this.token, to: voter1, value: web3.utils.toWei('10') }, { from: owner });
await this.token.delegate(voter2, { from: voter2 }); await this.helper.delegate({ token: this.token, to: voter2, value: web3.utils.toWei('7') }, { from: owner });
await this.token.delegate(voter3, { from: voter3 }); await this.helper.delegate({ token: this.token, to: voter3, value: web3.utils.toWei('5') }, { from: owner });
await this.token.delegate(voter4, { from: voter4 }); 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([ shouldSupportInterfaces([
...@@ -47,125 +62,110 @@ contract('Governor', function (accounts) { ...@@ -47,125 +62,110 @@ contract('Governor', function (accounts) {
it('deployment check', async function () { it('deployment check', async function () {
expect(await this.mock.name()).to.be.equal(name); expect(await this.mock.name()).to.be.equal(name);
expect(await this.mock.token()).to.be.equal(this.token.address); expect(await this.mock.token()).to.be.equal(this.token.address);
expect(await this.mock.votingDelay()).to.be.bignumber.equal('4'); expect(await this.mock.votingDelay()).to.be.bignumber.equal(votingDelay);
expect(await this.mock.votingPeriod()).to.be.bignumber.equal('16'); 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.quorum(0)).to.be.bignumber.equal('0');
expect(await this.mock.COUNTING_MODE()).to.be.equal('support=bravo&quorum=for,abstain'); expect(await this.mock.COUNTING_MODE()).to.be.equal('support=bravo&quorum=for,abstain');
}); });
describe('scenario', function () { it('nominal workflow', async function () {
describe('nominal', function () { // Before
beforeEach(async function () { expect(await this.mock.hasVoted(this.proposal.id, owner)).to.be.equal(false);
this.value = web3.utils.toWei('1'); 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);
await web3.eth.sendTransaction({ from: owner, to: this.mock.address, value: this.value }); expect(await web3.eth.getBalance(this.mock.address)).to.be.bignumber.equal(value);
expect(await web3.eth.getBalance(this.mock.address)).to.be.bignumber.equal(this.value);
expect(await web3.eth.getBalance(this.receiver.address)).to.be.bignumber.equal('0'); expect(await web3.eth.getBalance(this.receiver.address)).to.be.bignumber.equal('0');
this.settings = { // Run proposal
proposal: [ const txPropose = await this.helper.propose({ from: proposer });
[ this.receiver.address ],
[ this.value ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
proposer,
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('1'), support: Enums.VoteType.For, reason: 'This is nice' },
{ voter: voter2, weight: web3.utils.toWei('7'), support: Enums.VoteType.For },
{ voter: voter3, weight: web3.utils.toWei('5'), support: Enums.VoteType.Against },
{ voter: voter4, weight: web3.utils.toWei('2'), support: Enums.VoteType.Abstain },
],
};
this.votingDelay = await this.mock.votingDelay();
this.votingPeriod = await this.mock.votingPeriod();
});
afterEach(async function () {
expect(await this.mock.hasVoted(this.id, owner)).to.be.equal(false);
expect(await this.mock.hasVoted(this.id, voter1)).to.be.equal(true);
expect(await this.mock.hasVoted(this.id, voter2)).to.be.equal(true);
await this.mock.proposalVotes(this.id).then(result => {
for (const [key, value] of Object.entries(Enums.VoteType)) {
expect(result[`${key.toLowerCase()}Votes`]).to.be.bignumber.equal(
Object.values(this.settings.voters).filter(({ support }) => support === value).reduce(
(acc, { weight }) => acc.add(new BN(weight)),
new BN('0'),
),
);
}
});
expectEvent( expectEvent(
this.receipts.propose, txPropose,
'ProposalCreated', 'ProposalCreated',
{ {
proposalId: this.id, proposalId: this.proposal.id,
proposer, proposer,
targets: this.settings.proposal[0], targets: this.proposal.targets,
// values: this.settings.proposal[1].map(value => new BN(value)), // values: this.proposal.values,
signatures: this.settings.proposal[2].map(() => ''), signatures: this.proposal.signatures,
calldatas: this.settings.proposal[2], calldatas: this.proposal.data,
startBlock: new BN(this.receipts.propose.blockNumber).add(this.votingDelay), startBlock: new BN(txPropose.receipt.blockNumber).add(votingDelay),
endBlock: new BN(this.receipts.propose.blockNumber).add(this.votingDelay).add(this.votingPeriod), endBlock: new BN(txPropose.receipt.blockNumber).add(votingDelay).add(votingPeriod),
description: this.settings.proposal[3], 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'),
}, },
); );
this.receipts.castVote.filter(Boolean).forEach(vote => {
const { voter } = vote.logs.find(Boolean).args;
expectEvent( expectEvent(
vote, await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 }),
'VoteCast', 'VoteCast',
this.settings.voters.find(({ address }) => address === voter), {
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( expectEvent(
this.receipts.execute, txExecute,
'ProposalExecuted', 'ProposalExecuted',
{ proposalId: this.id }, { proposalId: this.proposal.id },
); );
await expectEvent.inTransaction( await expectEvent.inTransaction(
this.receipts.execute.transactionHash, txExecute.tx,
this.receiver, this.receiver,
'MockFunctionCalled', 'MockFunctionCalled',
); );
// 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.mock.address)).to.be.bignumber.equal('0');
expect(await web3.eth.getBalance(this.receiver.address)).to.be.bignumber.equal(this.value); expect(await web3.eth.getBalance(this.receiver.address)).to.be.bignumber.equal(value);
});
runGovernorWorkflow();
}); });
describe('vote with signature', function () { it('vote with signature', async function () {
beforeEach(async function () {
const chainId = await web3.eth.getChainId();
// generate voter by signature wallet
const voterBySig = Wallet.generate(); const voterBySig = Wallet.generate();
this.voter = web3.utils.toChecksumAddress(voterBySig.getAddressString()); const voterBySigAddress = web3.utils.toChecksumAddress(voterBySig.getAddressString());
// use delegateBySig to enable vote delegation for this wallet
const { v, r, s } = fromRpcSig(ethSigUtil.signTypedMessage(
voterBySig.getPrivateKey(),
{
data: {
types: {
EIP712Domain,
Delegation: [
{ name: 'delegatee', type: 'address' },
{ name: 'nonce', type: 'uint256' },
{ name: 'expiry', type: 'uint256' },
],
},
domain: { name: tokenName, version: '1', chainId, verifyingContract: this.token.address },
primaryType: 'Delegation',
message: { delegatee: this.voter, nonce: 0, expiry: constants.MAX_UINT256 },
},
},
));
await this.token.delegateBySig(this.voter, 0, constants.MAX_UINT256, v, r, s);
// prepare signature for vote by signature
const signature = async (message) => { const signature = async (message) => {
return fromRpcSig(ethSigUtil.signTypedMessage( return fromRpcSig(ethSigUtil.signTypedMessage(
voterBySig.getPrivateKey(), voterBySig.getPrivateKey(),
...@@ -178,7 +178,7 @@ contract('Governor', function (accounts) { ...@@ -178,7 +178,7 @@ contract('Governor', function (accounts) {
{ name: 'support', type: 'uint8' }, { name: 'support', type: 'uint8' },
], ],
}, },
domain: { name, version, chainId, verifyingContract: this.mock.address }, domain: { name, version, chainId: this.chainId, verifyingContract: this.mock.address },
primaryType: 'Ballot', primaryType: 'Ballot',
message, message,
}, },
...@@ -186,762 +186,392 @@ contract('Governor', function (accounts) { ...@@ -186,762 +186,392 @@ contract('Governor', function (accounts) {
)); ));
}; };
this.settings = { await this.token.delegate(voterBySigAddress, { from: voter1 });
proposal: [
[ this.receiver.address ],
[ web3.utils.toWei('0') ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
tokenHolder: owner,
voters: [
{ voter: this.voter, signature, weight: web3.utils.toWei('10'), support: Enums.VoteType.For },
],
};
});
afterEach(async function () {
expect(await this.mock.hasVoted(this.id, owner)).to.be.equal(false);
expect(await this.mock.hasVoted(this.id, voter1)).to.be.equal(false);
expect(await this.mock.hasVoted(this.id, voter2)).to.be.equal(false);
expect(await this.mock.hasVoted(this.id, this.voter)).to.be.equal(true);
await this.mock.proposalVotes(this.id).then(result => {
for (const [key, value] of Object.entries(Enums.VoteType)) {
expect(result[`${key.toLowerCase()}Votes`]).to.be.bignumber.equal(
Object.values(this.settings.voters).filter(({ support }) => support === value).reduce(
(acc, { weight }) => acc.add(new BN(weight)),
new BN('0'),
),
);
}
});
// Run proposal
await this.helper.propose();
await this.helper.waitForSnapshot();
expectEvent( expectEvent(
this.receipts.propose, await this.helper.vote({ support: Enums.VoteType.For, signature }),
'ProposalCreated', 'VoteCast',
{ proposalId: this.id }, { voter: voterBySigAddress, support: Enums.VoteType.For },
);
expectEvent(
this.receipts.execute,
'ProposalExecuted',
{ proposalId: this.id },
);
await expectEvent.inTransaction(
this.receipts.execute.transactionHash,
this.receiver,
'MockFunctionCalled',
); );
}); await this.helper.waitForDeadline();
runGovernorWorkflow(); 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);
}); });
describe('send ethers', function () { it('send ethers', async function () {
beforeEach(async function () { this.proposal = this.helper.setProposal([
this.receiver = { address: web3.utils.toChecksumAddress(web3.utils.randomHex(20)) }; {
this.value = web3.utils.toWei('1'); target: empty,
value,
},
], '<proposal description>');
await web3.eth.sendTransaction({ from: owner, to: this.mock.address, value: this.value }); // Before
expect(await web3.eth.getBalance(this.mock.address)).to.be.bignumber.equal(this.value); 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'); expect(await web3.eth.getBalance(empty)).to.be.bignumber.equal('0');
this.settings = { // Run proposal
proposal: [ await this.helper.propose();
[ this.receiver.address ], await this.helper.waitForSnapshot();
[ this.value ], await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
[ '0x' ], await this.helper.waitForDeadline();
'<proposal description>', await this.helper.execute();
],
tokenHolder: owner, // After
voters: [
{ voter: voter1, weight: web3.utils.toWei('5'), support: Enums.VoteType.For },
{ voter: voter2, weight: web3.utils.toWei('5'), support: Enums.VoteType.Abstain },
],
};
});
afterEach(async function () {
expectEvent(
this.receipts.propose,
'ProposalCreated',
{ proposalId: this.id },
);
expectEvent(
this.receipts.execute,
'ProposalExecuted',
{ proposalId: this.id },
);
expect(await web3.eth.getBalance(this.mock.address)).to.be.bignumber.equal('0'); 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(this.value); expect(await web3.eth.getBalance(empty)).to.be.bignumber.equal(value);
});
runGovernorWorkflow();
}); });
describe('receiver revert without reason', function () { describe('should revert', function () {
beforeEach(async function () { describe('on propose', function () {
this.settings = { it('if proposal already exists', async function () {
proposal: [ await this.helper.propose();
[ this.receiver.address ], await expectRevert(this.helper.propose(), 'Governor: proposal already exists');
[ 0 ],
[ this.receiver.contract.methods.mockFunctionRevertsNoReason().encodeABI() ],
'<proposal description>',
],
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For },
],
steps: {
execute: { error: 'Governor: call reverted without message' },
},
};
}); });
runGovernorWorkflow();
}); });
describe('receiver revert with reason', function () { describe('on vote', function () {
beforeEach(async function () { it('if proposal does not exist', async function () {
this.settings = { await expectRevert(
proposal: [ this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }),
[ this.receiver.address ], 'Governor: unknown proposal id',
[ 0 ], );
[ this.receiver.contract.methods.mockFunctionRevertsReason().encodeABI() ],
'<proposal description>',
],
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For },
],
steps: {
execute: { error: 'CallReceiverMock: reverting' },
},
};
});
runGovernorWorkflow();
}); });
describe('missing proposal', function () { it('if voting has not started', async function () {
beforeEach(async function () { await this.helper.propose();
this.settings = { await expectRevert(
proposal: [ this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }),
[ this.receiver.address ], 'Governor: vote not currently active',
[ web3.utils.toWei('0') ], );
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
tokenHolder: owner,
voters: [
{
voter: voter1,
weight: web3.utils.toWei('5'),
support: Enums.VoteType.For,
error: 'Governor: unknown proposal id',
},
{
voter: voter2,
weight: web3.utils.toWei('5'),
support: Enums.VoteType.Abstain,
error: 'Governor: unknown proposal id',
},
],
steps: {
propose: { enable: false },
wait: { enable: false },
execute: { error: 'Governor: unknown proposal id' },
},
};
}); });
runGovernorWorkflow();
it('if support value is invalid', async function () {
await this.helper.propose();
await this.helper.waitForSnapshot();
await expectRevert(
this.helper.vote({ support: new BN('255') }),
'GovernorVotingSimple: invalid value for enum VoteType',
);
}); });
describe('duplicate pending proposal', function () { it('if vote was already casted', async function () {
beforeEach(async function () { await this.helper.propose();
this.settings = { await this.helper.waitForSnapshot();
proposal: [ await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
[ this.receiver.address ], await expectRevert(
[ web3.utils.toWei('0') ], this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }),
[ this.receiver.contract.methods.mockFunction().encodeABI() ], 'GovernorVotingSimple: vote already cast',
'<proposal description>', );
],
steps: {
wait: { enable: false },
execute: { enable: false },
},
};
}); });
afterEach(async function () {
await expectRevert(this.mock.propose(...this.settings.proposal), 'Governor: proposal already exists'); 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',
);
}); });
runGovernorWorkflow();
}); });
describe('duplicate executed proposal', function () { describe('on execute', function () {
beforeEach(async function () { it('if proposal does not exist', async function () {
this.settings = { await expectRevert(this.helper.execute(), 'Governor: unknown proposal id');
proposal: [
[ this.receiver.address ],
[ web3.utils.toWei('0') ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('5'), support: Enums.VoteType.For },
{ voter: voter2, weight: web3.utils.toWei('5'), support: Enums.VoteType.Abstain },
],
};
});
afterEach(async function () {
await expectRevert(this.mock.propose(...this.settings.proposal), 'Governor: proposal already exists');
}); });
runGovernorWorkflow();
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');
}); });
describe('Invalid vote type', function () { it('if score not reached', async function () {
beforeEach(async function () { await this.helper.propose();
this.settings = { await this.helper.waitForSnapshot();
proposal: [ await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter1 });
[ this.receiver.address ], await expectRevert(this.helper.execute(), 'Governor: proposal not successful');
[ web3.utils.toWei('0') ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
tokenHolder: owner,
voters: [
{
voter: voter1,
weight: web3.utils.toWei('10'),
support: new BN('255'),
error: 'GovernorVotingSimple: invalid value for enum VoteType',
},
],
steps: {
wait: { enable: false },
execute: { enable: false },
},
};
}); });
runGovernorWorkflow();
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');
}); });
describe('double cast', function () { it('if receiver revert without reason', async function () {
beforeEach(async function () { this.proposal = this.helper.setProposal([
this.settings = {
proposal: [
[ this.receiver.address ],
[ web3.utils.toWei('0') ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
tokenHolder: owner,
voters: [
{
voter: voter1,
weight: web3.utils.toWei('5'),
support: Enums.VoteType.For,
},
{ {
voter: voter1, target: this.receiver.address,
weight: web3.utils.toWei('5'), data: this.receiver.contract.methods.mockFunctionRevertsNoReason().encodeABI(),
support: Enums.VoteType.For,
error: 'GovernorVotingSimple: vote already cast',
}, },
], ], '<proposal description>');
};
});
runGovernorWorkflow();
});
describe('quorum not reached', function () { await this.helper.propose();
beforeEach(async function () { await this.helper.waitForSnapshot();
this.settings = { await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
proposal: [ await this.helper.waitForDeadline();
[ this.receiver.address ], await expectRevert(this.helper.execute(), 'Governor: call reverted without message');
[ web3.utils.toWei('0') ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('5'), support: Enums.VoteType.For },
{ voter: voter2, weight: web3.utils.toWei('4'), support: Enums.VoteType.Abstain },
{ voter: voter3, weight: web3.utils.toWei('10'), support: Enums.VoteType.Against },
],
steps: {
execute: { error: 'Governor: proposal not successful' },
},
};
});
runGovernorWorkflow();
}); });
describe('score not reached', function () { it('if receiver revert with reason', async function () {
beforeEach(async function () { this.proposal = this.helper.setProposal([
this.settings = { {
proposal: [ target: this.receiver.address,
[ this.receiver.address ], data: this.receiver.contract.methods.mockFunctionRevertsReason().encodeABI(),
[ web3.utils.toWei('0') ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.Against },
],
steps: {
execute: { error: 'Governor: proposal not successful' },
}, },
}; ], '<proposal description>');
});
runGovernorWorkflow(); 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');
}); });
describe('vote not over', function () { it('if proposal was already executed', async function () {
beforeEach(async function () { await this.helper.propose();
this.settings = { await this.helper.waitForSnapshot();
proposal: [ await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
[ this.receiver.address ], await this.helper.waitForDeadline();
[ web3.utils.toWei('0') ], await this.helper.execute();
[ this.receiver.contract.methods.mockFunction().encodeABI() ], await expectRevert(this.helper.execute(), 'Governor: proposal not successful');
'<proposal description>',
],
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For },
],
steps: {
wait: { enable: false },
execute: { error: 'Governor: proposal not successful' },
},
};
}); });
runGovernorWorkflow();
}); });
}); });
describe('state', function () { describe('state', function () {
describe('Unset', function () { it('Unset', async function () {
beforeEach(async function () { await expectRevert(this.mock.state(this.proposal.id), 'Governor: unknown proposal id');
this.settings = {
proposal: [
[ this.receiver.address ],
[ web3.utils.toWei('0') ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
steps: {
propose: { enable: false },
wait: { enable: false },
execute: { enable: false },
},
};
});
afterEach(async function () {
await expectRevert(this.mock.state(this.id), 'Governor: unknown proposal id');
});
runGovernorWorkflow();
}); });
describe('Pending & Active', function () { it('Pending & Active', async function () {
beforeEach(async function () { await this.helper.propose();
this.settings = { expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Pending);
proposal: [ await this.helper.waitForSnapshot();
[ this.receiver.address ], expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Pending);
[ web3.utils.toWei('0') ], await this.helper.waitForSnapshot(+1);
[ this.receiver.contract.methods.mockFunction().encodeABI() ], expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Active);
'<proposal description>',
],
steps: {
propose: { noadvance: true },
wait: { enable: false },
execute: { enable: false },
},
};
}); });
afterEach(async function () {
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Pending);
await time.advanceBlockTo(this.snapshot); it('Defeated', async function () {
await this.helper.propose();
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Pending); await this.helper.waitForDeadline();
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Active);
await time.advanceBlock(); await this.helper.waitForDeadline(+1);
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Defeated);
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Active);
});
runGovernorWorkflow();
}); });
describe('Defeated', function () { it('Succeeded', async function () {
beforeEach(async function () { await this.helper.propose();
this.settings = { await this.helper.waitForSnapshot();
proposal: [ await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
[ this.receiver.address ], await this.helper.waitForDeadline();
[ web3.utils.toWei('0') ], expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Active);
[ this.receiver.contract.methods.mockFunction().encodeABI() ], await this.helper.waitForDeadline(+1);
'<proposal description>', expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Succeeded);
],
steps: {
execute: { enable: false },
},
};
});
afterEach(async function () {
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Defeated);
});
runGovernorWorkflow();
}); });
describe('Succeeded', function () { it('Executed', async function () {
beforeEach(async function () { await this.helper.propose();
this.settings = { await this.helper.waitForSnapshot();
proposal: [ await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
[ this.receiver.address ], await this.helper.waitForDeadline();
[ web3.utils.toWei('0') ], await this.helper.execute();
[ this.receiver.contract.methods.mockFunction().encodeABI() ], expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Executed);
'<proposal description>',
],
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For },
],
steps: {
execute: { enable: false },
},
};
});
afterEach(async function () {
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Succeeded);
}); });
runGovernorWorkflow();
}); });
describe('Executed', function () { describe('cancel', function () {
beforeEach(async function () { it('before proposal', async function () {
this.settings = { await expectRevert(this.helper.cancel(), 'Governor: unknown proposal id');
proposal: [
[ this.receiver.address ],
[ web3.utils.toWei('0') ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For },
],
};
});
afterEach(async function () {
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Executed);
});
runGovernorWorkflow();
});
}); });
describe('Cancel', function () { it('after proposal', async function () {
describe('Before proposal', function () { await this.helper.propose();
beforeEach(async function () {
this.settings = {
proposal: [
[ this.receiver.address ],
[ web3.utils.toWei('0') ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
steps: {
propose: { enable: false },
wait: { enable: false },
execute: { enable: false },
},
};
});
afterEach(async function () {
await expectRevert(
this.mock.cancel(...this.settings.proposal.slice(0, -1), this.descriptionHash),
'Governor: unknown proposal id',
);
});
runGovernorWorkflow();
});
describe('After proposal', function () { await this.helper.cancel();
beforeEach(async function () { expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled);
this.settings = {
proposal: [
[ this.receiver.address ],
[ web3.utils.toWei('0') ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
steps: {
wait: { enable: false },
execute: { enable: false },
},
};
});
afterEach(async function () {
await this.mock.cancel(...this.settings.proposal.slice(0, -1), this.descriptionHash);
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled);
await this.helper.waitForSnapshot();
await expectRevert( await expectRevert(
this.mock.castVote(this.id, new BN('100'), { from: voter1 }), this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }),
'Governor: vote not currently active', 'Governor: vote not currently active',
); );
}); });
runGovernorWorkflow();
});
describe('After vote', function () { it('after vote', async function () {
beforeEach(async function () { await this.helper.propose();
this.settings = { await this.helper.waitForSnapshot();
proposal: [ await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
[ this.receiver.address ],
[ web3.utils.toWei('0') ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For },
],
steps: {
wait: { enable: false },
execute: { enable: false },
},
};
});
afterEach(async function () {
await this.mock.cancel(...this.settings.proposal.slice(0, -1), this.descriptionHash);
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled);
await expectRevert( await this.helper.cancel();
this.mock.execute(...this.settings.proposal.slice(0, -1), this.descriptionHash), expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled);
'Governor: proposal not successful',
);
});
runGovernorWorkflow();
});
describe('After deadline', function () { await this.helper.waitForDeadline();
beforeEach(async function () { await expectRevert(this.helper.execute(), 'Governor: proposal not successful');
this.settings = {
proposal: [
[ this.receiver.address ],
[ web3.utils.toWei('0') ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For },
],
steps: {
execute: { enable: false },
},
};
}); });
afterEach(async function () {
await this.mock.cancel(...this.settings.proposal.slice(0, -1), this.descriptionHash);
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled);
await expectRevert( it('after deadline', async function () {
this.mock.execute(...this.settings.proposal.slice(0, -1), this.descriptionHash), await this.helper.propose();
'Governor: proposal not successful', await this.helper.waitForSnapshot();
); await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
}); await this.helper.waitForDeadline();
runGovernorWorkflow();
});
describe('After execution', function () { await this.helper.cancel();
beforeEach(async function () { expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled);
this.settings = {
proposal: [ await expectRevert(this.helper.execute(), 'Governor: proposal not successful');
[ this.receiver.address ],
[ web3.utils.toWei('0') ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For },
],
};
});
afterEach(async function () {
await expectRevert(
this.mock.cancel(...this.settings.proposal.slice(0, -1), this.descriptionHash),
'Governor: proposal not active',
);
}); });
runGovernorWorkflow();
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(), 'Governor: proposal not active');
}); });
}); });
describe('Proposal length', function () { describe('proposal length', function () {
it('empty', async function () { it('empty', async function () {
await expectRevert( this.helper.setProposal([ ], '<proposal description>');
this.mock.propose( await expectRevert(this.helper.propose(), 'Governor: empty proposal');
[],
[],
[],
'<proposal description>',
),
'Governor: empty proposal',
);
}); });
it('missmatch #1', async function () { it('missmatch #1', async function () {
await expectRevert( this.helper.setProposal({
this.mock.propose( targets: [ ],
[ ], values: [ web3.utils.toWei('0') ],
[ web3.utils.toWei('0') ], data: [ this.receiver.contract.methods.mockFunction().encodeABI() ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ], }, '<proposal description>');
'<proposal description>', await expectRevert(this.helper.propose(), 'Governor: invalid proposal length');
),
'Governor: invalid proposal length',
);
}); });
it('missmatch #2', async function () { it('missmatch #2', async function () {
await expectRevert( this.helper.setProposal({
this.mock.propose( targets: [ this.receiver.address ],
[ this.receiver.address ], values: [ ],
[ ], data: [ this.receiver.contract.methods.mockFunction().encodeABI() ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ], }, '<proposal description>');
'<proposal description>', await expectRevert(this.helper.propose(), 'Governor: invalid proposal length');
),
'Governor: invalid proposal length',
);
}); });
it('missmatch #3', async function () { it('missmatch #3', async function () {
await expectRevert( this.helper.setProposal({
this.mock.propose( targets: [ this.receiver.address ],
[ this.receiver.address ], values: [ web3.utils.toWei('0') ],
[ web3.utils.toWei('0') ], data: [ ],
[ ], }, '<proposal description>');
'<proposal description>', await expectRevert(this.helper.propose(), 'Governor: invalid proposal length');
),
'Governor: invalid proposal length',
);
}); });
}); });
describe('Settings update', function () { describe('onlyGovernance updates', function () {
describe('setVotingDelay', function () { it('setVotingDelay is protected', async function () {
beforeEach(async function () { await expectRevert(this.mock.setVotingDelay('0'), 'Governor: onlyGovernance');
this.settings = {
proposal: [
[ this.mock.address ],
[ web3.utils.toWei('0') ],
[ this.mock.contract.methods.setVotingDelay('0').encodeABI() ],
'<proposal description>',
],
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For },
],
};
}); });
afterEach(async function () {
expect(await this.mock.votingDelay()).to.be.bignumber.equal('0'); 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( expectEvent(
this.receipts.execute, await this.helper.execute(),
'VotingDelaySet', 'VotingDelaySet',
{ oldVotingDelay: '4', newVotingDelay: '0' }, { oldVotingDelay: '4', newVotingDelay: '0' },
); );
});
runGovernorWorkflow();
});
describe('setVotingPeriod', function () { expect(await this.mock.votingDelay()).to.be.bignumber.equal('0');
beforeEach(async function () {
this.settings = {
proposal: [
[ this.mock.address ],
[ web3.utils.toWei('0') ],
[ this.mock.contract.methods.setVotingPeriod('32').encodeABI() ],
'<proposal description>',
],
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For },
],
};
}); });
afterEach(async function () {
expect(await this.mock.votingPeriod()).to.be.bignumber.equal('32'); 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( expectEvent(
this.receipts.execute, await this.helper.execute(),
'VotingPeriodSet', 'VotingPeriodSet',
{ oldVotingPeriod: '16', newVotingPeriod: '32' }, { oldVotingPeriod: '16', newVotingPeriod: '32' },
); );
});
runGovernorWorkflow(); expect(await this.mock.votingPeriod()).to.be.bignumber.equal('32');
}); });
describe('setVotingPeriod to 0', function () { it('cannot setVotingPeriod to 0 through governance', async function () {
beforeEach(async function () { this.helper.setProposal([
this.settings = { {
proposal: [ target: this.mock.address,
[ this.mock.address ], data: this.mock.contract.methods.setVotingPeriod('0').encodeABI(),
[ web3.utils.toWei('0') ],
[ this.mock.contract.methods.setVotingPeriod('0').encodeABI() ],
'<proposal description>',
],
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For },
],
steps: {
execute: { error: 'GovernorSettings: voting period too low' },
}, },
}; ], '<proposal description>');
});
afterEach(async function () {
expect(await this.mock.votingPeriod()).to.be.bignumber.equal('16');
});
runGovernorWorkflow();
});
describe('setProposalThreshold', function () { await this.helper.propose();
beforeEach(async function () { await this.helper.waitForSnapshot();
this.settings = { await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
proposal: [ await this.helper.waitForDeadline();
[ this.mock.address ],
[ web3.utils.toWei('0') ], await expectRevert(this.helper.execute(), 'GovernorSettings: voting period too low');
[ this.mock.contract.methods.setProposalThreshold('1000000000000000000').encodeABI() ],
'<proposal description>',
],
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('10'), support: Enums.VoteType.For },
],
};
}); });
afterEach(async function () {
expect(await this.mock.proposalThreshold()).to.be.bignumber.equal('1000000000000000000'); 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( expectEvent(
this.receipts.execute, await this.helper.execute(),
'ProposalThresholdSet', 'ProposalThresholdSet',
{ oldProposalThreshold: '0', newProposalThreshold: '1000000000000000000' }, { oldProposalThreshold: '0', newProposalThreshold: '1000000000000000000' },
); );
});
runGovernorWorkflow();
});
describe('update protected', function () {
it('setVotingDelay', async function () {
await expectRevert(this.mock.setVotingDelay('0'), 'Governor: onlyGovernance');
});
it('setVotingPeriod', async function () {
await expectRevert(this.mock.setVotingPeriod('32'), 'Governor: onlyGovernance');
});
it('setProposalThreshold', async function () { expect(await this.mock.proposalThreshold()).to.be.bignumber.equal('1000000000000000000');
await expectRevert(this.mock.setProposalThreshold('1000000000000000000'), 'Governor: onlyGovernance');
});
}); });
}); });
}); });
const { expectRevert, time } = require('@openzeppelin/test-helpers');
async function getReceiptOrRevert (promise, error = undefined) {
if (error) {
await expectRevert(promise, error);
return undefined;
} else {
const { receipt } = await promise;
return receipt;
}
}
function tryGet (obj, path = '') {
try {
return path.split('.').reduce((o, k) => o[k], obj);
} catch (_) {
return undefined;
}
}
function zip (...args) {
return Array(Math.max(...args.map(array => array.length)))
.fill()
.map((_, i) => args.map(array => array[i]));
}
function concatHex (...args) {
return web3.utils.bytesToHex([].concat(...args.map(h => web3.utils.hexToBytes(h || '0x'))));
}
function runGovernorWorkflow () {
beforeEach(async function () {
this.receipts = {};
// distinguish depending on the proposal length
// - length 4: propose(address[], uint256[], bytes[], string) → GovernorCore
// - length 5: propose(address[], uint256[], string[], bytes[], string) → GovernorCompatibilityBravo
this.useCompatibilityInterface = this.settings.proposal.length === 5;
// compute description hash
this.descriptionHash = web3.utils.keccak256(this.settings.proposal.slice(-1).find(Boolean));
// condensed proposal, used for queue and execute operation
this.settings.shortProposal = [
// targets
this.settings.proposal[0],
// values
this.settings.proposal[1],
// calldata (prefix selector if necessary)
this.useCompatibilityInterface
? zip(
this.settings.proposal[2].map(selector => selector && web3.eth.abi.encodeFunctionSignature(selector)),
this.settings.proposal[3],
).map(hexs => concatHex(...hexs))
: this.settings.proposal[2],
// descriptionHash
this.descriptionHash,
];
// proposal id
this.id = await this.mock.hashProposal(...this.settings.shortProposal);
});
it('run', async function () {
// transfer tokens
if (tryGet(this.settings, 'voters')) {
for (const voter of this.settings.voters) {
if (voter.weight) {
await this.token.transfer(voter.voter, voter.weight, { from: this.settings.tokenHolder });
} else if (voter.nfts) {
for (const nft of voter.nfts) {
await this.token.transferFrom(this.settings.tokenHolder, voter.voter, nft,
{ from: this.settings.tokenHolder });
}
}
}
}
// propose
if (this.mock.propose && tryGet(this.settings, 'steps.propose.enable') !== false) {
this.receipts.propose = await getReceiptOrRevert(
this.mock.methods[
this.useCompatibilityInterface
? 'propose(address[],uint256[],string[],bytes[],string)'
: 'propose(address[],uint256[],bytes[],string)'
](
...this.settings.proposal,
{ from: this.settings.proposer },
),
tryGet(this.settings, 'steps.propose.error'),
);
if (tryGet(this.settings, 'steps.propose.error') === undefined) {
this.deadline = await this.mock.proposalDeadline(this.id);
this.snapshot = await this.mock.proposalSnapshot(this.id);
}
if (tryGet(this.settings, 'steps.propose.delay')) {
await time.increase(tryGet(this.settings, 'steps.propose.delay'));
}
if (
tryGet(this.settings, 'steps.propose.error') === undefined &&
tryGet(this.settings, 'steps.propose.noadvance') !== true
) {
await time.advanceBlockTo(this.snapshot.addn(1));
}
}
// vote
if (tryGet(this.settings, 'voters')) {
this.receipts.castVote = [];
for (const voter of this.settings.voters.filter(({ support }) => !!support)) {
if (!voter.signature) {
this.receipts.castVote.push(
await getReceiptOrRevert(
voter.reason
? this.mock.castVoteWithReason(this.id, voter.support, voter.reason, { from: voter.voter })
: this.mock.castVote(this.id, voter.support, { from: voter.voter }),
voter.error,
),
);
} else {
const { v, r, s } = await voter.signature({ proposalId: this.id, support: voter.support });
this.receipts.castVote.push(
await getReceiptOrRevert(
this.mock.castVoteBySig(this.id, voter.support, v, r, s),
voter.error,
),
);
}
if (tryGet(voter, 'delay')) {
await time.increase(tryGet(voter, 'delay'));
}
}
}
// fast forward
if (tryGet(this.settings, 'steps.wait.enable') !== false) {
await time.advanceBlockTo(this.deadline.addn(1));
}
// queue
if (this.mock.queue && tryGet(this.settings, 'steps.queue.enable') !== false) {
this.receipts.queue = await getReceiptOrRevert(
this.useCompatibilityInterface
? this.mock.methods['queue(uint256)'](
this.id,
{ from: this.settings.queuer },
)
: this.mock.methods['queue(address[],uint256[],bytes[],bytes32)'](
...this.settings.shortProposal,
{ from: this.settings.queuer },
),
tryGet(this.settings, 'steps.queue.error'),
);
this.eta = await this.mock.proposalEta(this.id);
if (tryGet(this.settings, 'steps.queue.delay')) {
await time.increase(tryGet(this.settings, 'steps.queue.delay'));
}
}
// execute
if (this.mock.execute && tryGet(this.settings, 'steps.execute.enable') !== false) {
this.receipts.execute = await getReceiptOrRevert(
this.useCompatibilityInterface
? this.mock.methods['execute(uint256)'](
this.id,
{ from: this.settings.executer },
)
: this.mock.methods['execute(address[],uint256[],bytes[],bytes32)'](
...this.settings.shortProposal,
{ from: this.settings.executer },
),
tryGet(this.settings, 'steps.execute.error'),
);
if (tryGet(this.settings, 'steps.execute.delay')) {
await time.increase(tryGet(this.settings, 'steps.execute.delay'));
}
}
});
}
module.exports = {
runGovernorWorkflow,
};
const { BN, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); const { BN, expectEvent, expectRevert } = require('@openzeppelin/test-helpers');
const Enums = require('../../helpers/enums'); const { expect } = require('chai');
const RLP = require('rlp'); const RLP = require('rlp');
const Enums = require('../../helpers/enums');
const { const { GovernorHelper } = require('../../helpers/governance');
runGovernorWorkflow,
} = require('../GovernorWorkflow.behavior');
const Token = artifacts.require('ERC20VotesCompMock'); const Token = artifacts.require('ERC20VotesCompMock');
const Timelock = artifacts.require('CompTimelock'); const Timelock = artifacts.require('CompTimelock');
...@@ -23,7 +21,10 @@ contract('GovernorCompatibilityBravo', function (accounts) { ...@@ -23,7 +21,10 @@ contract('GovernorCompatibilityBravo', function (accounts) {
const tokenName = 'MockToken'; const tokenName = 'MockToken';
const tokenSymbol = 'MTKN'; const tokenSymbol = 'MTKN';
const tokenSupply = web3.utils.toWei('100'); const tokenSupply = web3.utils.toWei('100');
const votingDelay = new BN(4);
const votingPeriod = new BN(16);
const proposalThreshold = web3.utils.toWei('10'); const proposalThreshold = web3.utils.toWei('10');
const value = web3.utils.toWei('1');
beforeEach(async function () { beforeEach(async function () {
const [ deployer ] = await web3.eth.getAccounts(); const [ deployer ] = await web3.eth.getAccounts();
...@@ -35,392 +36,220 @@ contract('GovernorCompatibilityBravo', function (accounts) { ...@@ -35,392 +36,220 @@ contract('GovernorCompatibilityBravo', function (accounts) {
const predictGovernor = makeContractAddress(deployer, nonce + 1); const predictGovernor = makeContractAddress(deployer, nonce + 1);
this.timelock = await Timelock.new(predictGovernor, 2 * 86400); this.timelock = await Timelock.new(predictGovernor, 2 * 86400);
this.mock = await Governor.new(name, this.token.address, 4, 16, proposalThreshold, this.timelock.address); this.mock = await Governor.new(
name,
this.token.address,
votingDelay,
votingPeriod,
proposalThreshold,
this.timelock.address,
);
this.receiver = await CallReceiver.new(); this.receiver = await CallReceiver.new();
await this.token.mint(owner, tokenSupply);
await this.token.delegate(voter1, { from: voter1 });
await this.token.delegate(voter2, { from: voter2 });
await this.token.delegate(voter3, { from: voter3 });
await this.token.delegate(voter4, { from: voter4 });
await this.token.transfer(proposer, proposalThreshold, { from: owner }); this.helper = new GovernorHelper(this.mock);
await this.token.delegate(proposer, { from: proposer });
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>');
}); });
it('deployment check', async function () { it('deployment check', async function () {
expect(await this.mock.name()).to.be.equal(name); expect(await this.mock.name()).to.be.equal(name);
expect(await this.mock.token()).to.be.equal(this.token.address); expect(await this.mock.token()).to.be.equal(this.token.address);
expect(await this.mock.votingDelay()).to.be.bignumber.equal('4'); expect(await this.mock.votingDelay()).to.be.bignumber.equal(votingDelay);
expect(await this.mock.votingPeriod()).to.be.bignumber.equal('16'); 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.quorum(0)).to.be.bignumber.equal('0');
expect(await this.mock.quorumVotes()).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'); expect(await this.mock.COUNTING_MODE()).to.be.equal('support=bravo&quorum=bravo');
}); });
describe('nominal', function () { it('nominal workflow', async function () {
beforeEach(async function () { // Before
this.settings = { expect(await this.mock.hasVoted(this.proposal.id, owner)).to.be.equal(false);
proposal: [ expect(await this.mock.hasVoted(this.proposal.id, voter1)).to.be.equal(false);
[ this.receiver.address ], // targets expect(await this.mock.hasVoted(this.proposal.id, voter2)).to.be.equal(false);
[ web3.utils.toWei('0') ], // values expect(await web3.eth.getBalance(this.mock.address)).to.be.bignumber.equal('0');
[ this.receiver.contract.methods.mockFunction().encodeABI() ], // calldatas expect(await web3.eth.getBalance(this.timelock.address)).to.be.bignumber.equal(value);
'<proposal description>', // description expect(await web3.eth.getBalance(this.receiver.address)).to.be.bignumber.equal('0');
],
proposer, // Run proposal
tokenHolder: owner, const txPropose = await this.helper.propose({ from: proposer });
voters: [ await this.helper.waitForSnapshot();
{ await this.helper.vote({ support: Enums.VoteType.For, reason: 'This is nice' }, { from: voter1 });
voter: voter1, await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 });
weight: web3.utils.toWei('1'), await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter3 });
support: Enums.VoteType.Abstain, await this.helper.vote({ support: Enums.VoteType.Abstain }, { from: voter4 });
}, await this.helper.waitForDeadline();
{ await this.helper.queue();
voter: voter2, await this.helper.waitForEta();
weight: web3.utils.toWei('10'), const txExecute = await this.helper.execute();
support: Enums.VoteType.For,
}, // After
{ expect(await this.mock.hasVoted(this.proposal.id, owner)).to.be.equal(false);
voter: voter3, expect(await this.mock.hasVoted(this.proposal.id, voter1)).to.be.equal(true);
weight: web3.utils.toWei('5'), expect(await this.mock.hasVoted(this.proposal.id, voter2)).to.be.equal(true);
support: Enums.VoteType.Against, 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);
voter: voter4,
support: '100', const proposal = await this.mock.proposals(this.proposal.id);
error: 'GovernorCompatibilityBravo: invalid vote type', expect(proposal.id).to.be.bignumber.equal(this.proposal.id);
},
{
voter: voter1,
support: Enums.VoteType.For,
error: 'GovernorCompatibilityBravo: vote already cast',
skip: true,
},
],
steps: {
queue: { delay: 7 * 86400 },
},
};
this.votingDelay = await this.mock.votingDelay();
this.votingPeriod = await this.mock.votingPeriod();
this.receipts = {};
});
afterEach(async function () {
const proposal = await this.mock.proposals(this.id);
expect(proposal.id).to.be.bignumber.equal(this.id);
expect(proposal.proposer).to.be.equal(proposer); expect(proposal.proposer).to.be.equal(proposer);
expect(proposal.eta).to.be.bignumber.equal(this.eta); expect(proposal.eta).to.be.bignumber.equal(await this.mock.proposalEta(this.proposal.id));
expect(proposal.startBlock).to.be.bignumber.equal(this.snapshot); expect(proposal.startBlock).to.be.bignumber.equal(await this.mock.proposalSnapshot(this.proposal.id));
expect(proposal.endBlock).to.be.bignumber.equal(this.deadline); expect(proposal.endBlock).to.be.bignumber.equal(await this.mock.proposalDeadline(this.proposal.id));
expect(proposal.canceled).to.be.equal(false); expect(proposal.canceled).to.be.equal(false);
expect(proposal.executed).to.be.equal(true); expect(proposal.executed).to.be.equal(true);
for (const [key, value] of Object.entries(Enums.VoteType)) { const action = await this.mock.getActions(this.proposal.id);
expect(proposal[`${key.toLowerCase()}Votes`]).to.be.bignumber.equal( expect(action.targets).to.be.deep.equal(this.proposal.targets);
Object.values(this.settings.voters).filter(({ support }) => support === value).reduce( // expect(action.values).to.be.deep.equal(this.proposal.values);
(acc, { weight }) => acc.add(new BN(weight)), expect(action.signatures).to.be.deep.equal(this.proposal.signatures);
new BN('0'), 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 action = await this.mock.getActions(this.id); const voteReceipt2 = await this.mock.getReceipt(this.proposal.id, voter2);
expect(action.targets).to.be.deep.equal(this.settings.proposal[0]); expect(voteReceipt2.hasVoted).to.be.equal(true);
// expect(action.values).to.be.deep.equal(this.settings.proposal[1]); expect(voteReceipt2.support).to.be.bignumber.equal(Enums.VoteType.For);
expect(action.signatures).to.be.deep.equal(Array(this.settings.proposal[2].length).fill('')); expect(voteReceipt2.votes).to.be.bignumber.equal(web3.utils.toWei('7'));
expect(action.calldatas).to.be.deep.equal(this.settings.proposal[2]);
for (const voter of this.settings.voters.filter(({ skip }) => !skip)) { const voteReceipt3 = await this.mock.getReceipt(this.proposal.id, voter3);
expect(await this.mock.hasVoted(this.id, voter.voter)).to.be.equal(voter.error === undefined); 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 receipt = await this.mock.getReceipt(this.id, voter.voter); const voteReceipt4 = await this.mock.getReceipt(this.proposal.id, voter4);
expect(receipt.hasVoted).to.be.equal(voter.error === undefined); expect(voteReceipt4.hasVoted).to.be.equal(true);
expect(receipt.support).to.be.bignumber.equal(voter.error === undefined ? voter.support : '0'); expect(voteReceipt4.support).to.be.bignumber.equal(Enums.VoteType.Abstain);
expect(receipt.votes).to.be.bignumber.equal(voter.error === undefined ? voter.weight : '0'); expect(voteReceipt4.votes).to.be.bignumber.equal(web3.utils.toWei('2'));
}
expectEvent( expectEvent(
this.receipts.propose, txPropose,
'ProposalCreated', 'ProposalCreated',
{ {
proposalId: this.id, proposalId: this.proposal.id,
proposer, proposer,
targets: this.settings.proposal[0], targets: this.proposal.targets,
// values: this.settings.proposal[1].map(value => new BN(value)), // values: this.proposal.values,
signatures: this.settings.proposal[2].map(() => ''), signatures: this.proposal.signatures.map(() => ''), // this event doesn't contain the proposal detail
calldatas: this.settings.proposal[2], calldatas: this.proposal.fulldata,
startBlock: new BN(this.receipts.propose.blockNumber).add(this.votingDelay), startBlock: new BN(txPropose.receipt.blockNumber).add(votingDelay),
endBlock: new BN(this.receipts.propose.blockNumber).add(this.votingDelay).add(this.votingPeriod), endBlock: new BN(txPropose.receipt.blockNumber).add(votingDelay).add(votingPeriod),
description: this.settings.proposal[3], description: this.proposal.description,
}, },
); );
this.receipts.castVote.filter(Boolean).forEach(vote => {
const { voter } = vote.logs.find(Boolean).args;
expectEvent(
vote,
'VoteCast',
this.settings.voters.find(({ address }) => address === voter),
);
});
expectEvent( expectEvent(
this.receipts.execute, txExecute,
'ProposalExecuted', 'ProposalExecuted',
{ proposalId: this.id }, { proposalId: this.proposal.id },
); );
await expectEvent.inTransaction( await expectEvent.inTransaction(
this.receipts.execute.transactionHash, txExecute.tx,
this.receiver, this.receiver,
'MockFunctionCalled', 'MockFunctionCalled',
); );
}); });
runGovernorWorkflow();
});
describe('with function selector and arguments', function () { it('with function selector and arguments', async function () {
beforeEach(async function () { const target = this.receiver.address;
this.settings = { this.helper.setProposal([
proposal: [ { target, data: this.receiver.contract.methods.mockFunction().encodeABI() },
Array(4).fill(this.receiver.address), { target, data: this.receiver.contract.methods.mockFunctionWithArgs(17, 42).encodeABI() },
Array(4).fill(web3.utils.toWei('0')), { target, signature: 'mockFunctionNonPayable()' },
[
'',
'',
'mockFunctionNonPayable()',
'mockFunctionWithArgs(uint256,uint256)',
],
[
this.receiver.contract.methods.mockFunction().encodeABI(),
this.receiver.contract.methods.mockFunctionWithArgs(17, 42).encodeABI(),
'0x',
web3.eth.abi.encodeParameters(['uint256', 'uint256'], [18, 43]),
],
'<proposal description>', // description
],
proposer,
tokenHolder: owner,
voters: [
{ {
voter: voter1, target,
weight: web3.utils.toWei('10'), signature: 'mockFunctionWithArgs(uint256,uint256)',
support: Enums.VoteType.For, data: web3.eth.abi.encodeParameters(['uint256', 'uint256'], [18, 43]),
}, },
], ], '<proposal description>');
steps: {
queue: { delay: 7 * 86400 }, 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();
runGovernorWorkflow(); await this.helper.queue();
afterEach(async function () { await this.helper.waitForEta();
const txExecute = await this.helper.execute();
await expectEvent.inTransaction( await expectEvent.inTransaction(
this.receipts.execute.transactionHash, txExecute.tx,
this.receiver, this.receiver,
'MockFunctionCalled', 'MockFunctionCalled',
); );
await expectEvent.inTransaction( await expectEvent.inTransaction(
this.receipts.execute.transactionHash, txExecute.tx,
this.receiver, this.receiver,
'MockFunctionCalled', 'MockFunctionCalled',
); );
await expectEvent.inTransaction( await expectEvent.inTransaction(
this.receipts.execute.transactionHash, txExecute.tx,
this.receiver, this.receiver,
'MockFunctionCalledWithArgs', 'MockFunctionCalledWithArgs',
{ a: '17', b: '42' }, { a: '17', b: '42' },
); );
await expectEvent.inTransaction( await expectEvent.inTransaction(
this.receipts.execute.transactionHash, txExecute.tx,
this.receiver, this.receiver,
'MockFunctionCalledWithArgs', 'MockFunctionCalledWithArgs',
{ a: '18', b: '43' }, { a: '18', b: '43' },
); );
}); });
});
describe('proposalThreshold not reached', function () {
beforeEach(async function () {
this.settings = {
proposal: [
[ this.receiver.address ], // targets
[ web3.utils.toWei('0') ], // values
[ this.receiver.contract.methods.mockFunction().encodeABI() ], // calldatas
'<proposal description>', // description
],
proposer: other,
steps: {
propose: { error: 'GovernorCompatibilityBravo: proposer votes below proposal threshold' },
wait: { enable: false },
queue: { enable: false },
execute: { enable: false },
},
};
});
runGovernorWorkflow();
});
describe('cancel', function () {
beforeEach(async function () {
this.settings = {
proposal: [
[ this.receiver.address ], // targets
[ web3.utils.toWei('0') ], // values
[ this.receiver.contract.methods.mockFunction().encodeABI() ], // calldatas
'<proposal description>', // description
],
proposer,
tokenHolder: owner,
steps: {
wait: { enable: false },
queue: { enable: false },
execute: { enable: false },
},
};
});
describe('by proposer', function () {
afterEach(async function () {
await this.mock.cancel(this.id, { from: proposer });
});
runGovernorWorkflow();
});
describe('if proposer below threshold', function () { describe('should revert', function () {
afterEach(async function () { describe('on propose', function () {
await this.token.transfer(voter1, web3.utils.toWei('1'), { from: proposer }); it('if proposal doesnt meet proposalThreshold', async function () {
await this.mock.cancel(this.id); await expectRevert(
this.helper.propose({ from: other }),
'GovernorCompatibilityBravo: proposer votes below proposal threshold',
);
}); });
runGovernorWorkflow();
}); });
describe('not if proposer above threshold', function () { describe('on vote', function () {
afterEach(async function () { it('if vote type is invalide', async function () {
await this.helper.propose({ from: proposer });
await this.helper.waitForSnapshot();
await expectRevert( await expectRevert(
this.mock.cancel(this.id), this.helper.vote({ support: 5 }, { from: voter1 }),
'GovernorBravo: proposer above threshold', 'GovernorCompatibilityBravo: invalid vote type',
); );
}); });
runGovernorWorkflow();
}); });
}); });
describe('with compatibility interface', function () { describe('cancel', function () {
beforeEach(async function () { it('proposer can cancel', async function () {
this.settings = { await this.helper.propose({ from: proposer });
proposal: [ await this.helper.cancel({ from: proposer });
[ this.receiver.address ], // targets
[ web3.utils.toWei('0') ], // values
[ 'mockFunction()' ], // signatures
[ '0x' ], // calldatas
'<proposal description>', // description
],
proposer,
tokenHolder: owner,
voters: [
{
voter: voter1,
weight: web3.utils.toWei('1'),
support: Enums.VoteType.Abstain,
},
{
voter: voter2,
weight: web3.utils.toWei('10'),
support: Enums.VoteType.For,
},
{
voter: voter3,
weight: web3.utils.toWei('5'),
support: Enums.VoteType.Against,
},
{
voter: voter4,
support: '100',
error: 'GovernorCompatibilityBravo: invalid vote type',
},
{
voter: voter1,
support: Enums.VoteType.For,
error: 'GovernorCompatibilityBravo: vote already cast',
skip: true,
},
],
steps: {
queue: { delay: 7 * 86400 },
},
};
this.votingDelay = await this.mock.votingDelay();
this.votingPeriod = await this.mock.votingPeriod();
this.receipts = {};
}); });
afterEach(async function () { it('anyone can cancel if proposer drop below threshold', async function () {
const proposal = await this.mock.proposals(this.id); await this.helper.propose({ from: proposer });
expect(proposal.id).to.be.bignumber.equal(this.id); await this.token.transfer(voter1, web3.utils.toWei('1'), { from: proposer });
expect(proposal.proposer).to.be.equal(proposer); await this.helper.cancel();
expect(proposal.eta).to.be.bignumber.equal(this.eta);
expect(proposal.startBlock).to.be.bignumber.equal(this.snapshot);
expect(proposal.endBlock).to.be.bignumber.equal(this.deadline);
expect(proposal.canceled).to.be.equal(false);
expect(proposal.executed).to.be.equal(true);
for (const [key, value] of Object.entries(Enums.VoteType)) {
expect(proposal[`${key.toLowerCase()}Votes`]).to.be.bignumber.equal(
Object.values(this.settings.voters).filter(({ support }) => support === value).reduce(
(acc, { weight }) => acc.add(new BN(weight)),
new BN('0'),
),
);
}
const action = await this.mock.getActions(this.id);
expect(action.targets).to.be.deep.equal(this.settings.proposal[0]);
// expect(action.values).to.be.deep.equal(this.settings.proposal[1]);
expect(action.signatures).to.be.deep.equal(this.settings.proposal[2]);
expect(action.calldatas).to.be.deep.equal(this.settings.proposal[3]);
for (const voter of this.settings.voters.filter(({ skip }) => !skip)) {
expect(await this.mock.hasVoted(this.id, voter.voter)).to.be.equal(voter.error === undefined);
const receipt = await this.mock.getReceipt(this.id, voter.voter);
expect(receipt.hasVoted).to.be.equal(voter.error === undefined);
expect(receipt.support).to.be.bignumber.equal(voter.error === undefined ? voter.support : '0');
expect(receipt.votes).to.be.bignumber.equal(voter.error === undefined ? voter.weight : '0');
}
expectEvent(
this.receipts.propose,
'ProposalCreated',
{
proposalId: this.id,
proposer,
targets: this.settings.proposal[0],
// values: this.settings.proposal[1].map(value => new BN(value)),
signatures: this.settings.proposal[2].map(_ => ''),
calldatas: this.settings.shortProposal[2],
startBlock: new BN(this.receipts.propose.blockNumber).add(this.votingDelay),
endBlock: new BN(this.receipts.propose.blockNumber).add(this.votingDelay).add(this.votingPeriod),
description: this.settings.proposal[4],
},
);
this.receipts.castVote.filter(Boolean).forEach(vote => {
const { voter } = vote.logs.find(Boolean).args;
expectEvent(
vote,
'VoteCast',
this.settings.voters.find(({ address }) => address === voter),
);
}); });
expectEvent(
this.receipts.execute, it('cannot cancel is proposer is still above threshold', async function () {
'ProposalExecuted', await this.helper.propose({ from: proposer });
{ proposalId: this.id }, await expectRevert(this.helper.cancel(), 'GovernorBravo: proposer above threshold');
);
await expectEvent.inTransaction(
this.receipts.execute.transactionHash,
this.receiver,
'MockFunctionCalled',
);
}); });
runGovernorWorkflow();
}); });
}); });
const { BN, expectEvent } = require('@openzeppelin/test-helpers'); const { BN } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const Enums = require('../../helpers/enums'); const Enums = require('../../helpers/enums');
const { GovernorHelper } = require('../../helpers/governance');
const {
runGovernorWorkflow,
} = require('./../GovernorWorkflow.behavior');
const Token = artifacts.require('ERC20VotesCompMock'); const Token = artifacts.require('ERC20VotesCompMock');
const Governor = artifacts.require('GovernorCompMock'); const Governor = artifacts.require('GovernorCompMock');
...@@ -17,71 +15,64 @@ contract('GovernorComp', function (accounts) { ...@@ -17,71 +15,64 @@ contract('GovernorComp', function (accounts) {
const tokenName = 'MockToken'; const tokenName = 'MockToken';
const tokenSymbol = 'MTKN'; const tokenSymbol = 'MTKN';
const tokenSupply = web3.utils.toWei('100'); const tokenSupply = web3.utils.toWei('100');
const votingDelay = new BN(4);
const votingPeriod = new BN(16);
const value = web3.utils.toWei('1');
beforeEach(async function () { beforeEach(async function () {
this.owner = owner; this.owner = owner;
this.token = await Token.new(tokenName, tokenSymbol); this.token = await Token.new(tokenName, tokenSymbol);
this.mock = await Governor.new(name, this.token.address); this.mock = await Governor.new(name, this.token.address);
this.receiver = await CallReceiver.new(); this.receiver = await CallReceiver.new();
this.helper = new GovernorHelper(this.mock);
await web3.eth.sendTransaction({ from: owner, to: this.mock.address, value });
await this.token.mint(owner, tokenSupply); await this.token.mint(owner, tokenSupply);
await this.token.delegate(voter1, { from: voter1 }); await this.helper.delegate({ token: this.token, to: voter1, value: web3.utils.toWei('10') }, { from: owner });
await this.token.delegate(voter2, { from: voter2 }); await this.helper.delegate({ token: this.token, to: voter2, value: web3.utils.toWei('7') }, { from: owner });
await this.token.delegate(voter3, { from: voter3 }); await this.helper.delegate({ token: this.token, to: voter3, value: web3.utils.toWei('5') }, { from: owner });
await this.token.delegate(voter4, { from: voter4 }); 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 () { it('deployment check', async function () {
expect(await this.mock.name()).to.be.equal(name); expect(await this.mock.name()).to.be.equal(name);
expect(await this.mock.token()).to.be.equal(this.token.address); expect(await this.mock.token()).to.be.equal(this.token.address);
expect(await this.mock.votingDelay()).to.be.bignumber.equal('4'); expect(await this.mock.votingDelay()).to.be.bignumber.equal(votingDelay);
expect(await this.mock.votingPeriod()).to.be.bignumber.equal('16'); 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.quorum(0)).to.be.bignumber.equal('0');
}); });
describe('voting with comp token', function () { it('voting with comp token', async function () {
beforeEach(async function () { await this.helper.propose();
this.settings = { await this.helper.waitForSnapshot();
proposal: [ await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
[ this.receiver.address ], await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 });
[ web3.utils.toWei('0') ], await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter3 });
[ this.receiver.contract.methods.mockFunction().encodeABI() ], await this.helper.vote({ support: Enums.VoteType.Abstain }, { from: voter4 });
'<proposal description>', await this.helper.waitForDeadline();
], await this.helper.execute();
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('1'), support: Enums.VoteType.For },
{ voter: voter2, weight: web3.utils.toWei('10'), support: Enums.VoteType.For },
{ voter: voter3, weight: web3.utils.toWei('5'), support: Enums.VoteType.Against },
{ voter: voter4, weight: web3.utils.toWei('2'), support: Enums.VoteType.Abstain },
],
};
});
afterEach(async function () {
expect(await this.mock.hasVoted(this.id, owner)).to.be.equal(false);
expect(await this.mock.hasVoted(this.id, voter1)).to.be.equal(true);
expect(await this.mock.hasVoted(this.id, voter2)).to.be.equal(true);
expect(await this.mock.hasVoted(this.id, voter3)).to.be.equal(true);
expect(await this.mock.hasVoted(this.id, voter4)).to.be.equal(true);
this.receipts.castVote.filter(Boolean).forEach(vote => { expect(await this.mock.hasVoted(this.proposal.id, owner)).to.be.equal(false);
const { voter } = vote.logs.find(Boolean).args; expect(await this.mock.hasVoted(this.proposal.id, voter1)).to.be.equal(true);
expectEvent( expect(await this.mock.hasVoted(this.proposal.id, voter2)).to.be.equal(true);
vote, expect(await this.mock.hasVoted(this.proposal.id, voter3)).to.be.equal(true);
'VoteCast', expect(await this.mock.hasVoted(this.proposal.id, voter4)).to.be.equal(true);
this.settings.voters.find(({ address }) => address === voter),
); await this.mock.proposalVotes(this.proposal.id).then(results => {
}); expect(results.forVotes).to.be.bignumber.equal(web3.utils.toWei('17'));
await this.mock.proposalVotes(this.id).then(result => { expect(results.againstVotes).to.be.bignumber.equal(web3.utils.toWei('5'));
for (const [key, value] of Object.entries(Enums.VoteType)) { expect(results.abstainVotes).to.be.bignumber.equal(web3.utils.toWei('2'));
expect(result[`${key.toLowerCase()}Votes`]).to.be.bignumber.equal(
Object.values(this.settings.voters).filter(({ support }) => support === value).reduce(
(acc, { weight }) => acc.add(new BN(weight)),
new BN('0'),
),
);
}
});
}); });
runGovernorWorkflow();
}); });
}); });
const { expectEvent } = require('@openzeppelin/test-helpers'); const { BN, expectEvent } = require('@openzeppelin/test-helpers');
const { BN } = require('bn.js'); const { expect } = require('chai');
const Enums = require('../../helpers/enums'); const Enums = require('../../helpers/enums');
const { GovernorHelper } = require('../../helpers/governance');
const {
runGovernorWorkflow,
} = require('./../GovernorWorkflow.behavior');
const Token = artifacts.require('ERC721VotesMock'); const Token = artifacts.require('ERC721VotesMock');
const Governor = artifacts.require('GovernorVoteMocks'); const Governor = artifacts.require('GovernorVoteMocks');
...@@ -14,105 +11,94 @@ contract('GovernorERC721Mock', function (accounts) { ...@@ -14,105 +11,94 @@ contract('GovernorERC721Mock', function (accounts) {
const [ owner, voter1, voter2, voter3, voter4 ] = accounts; const [ owner, voter1, voter2, voter3, voter4 ] = accounts;
const name = 'OZ-Governor'; const name = 'OZ-Governor';
// const version = '1';
const tokenName = 'MockNFToken'; const tokenName = 'MockNFToken';
const tokenSymbol = 'MTKN'; const tokenSymbol = 'MTKN';
const NFT0 = web3.utils.toWei('100'); const NFT0 = new BN(0);
const NFT1 = web3.utils.toWei('10'); const NFT1 = new BN(1);
const NFT2 = web3.utils.toWei('20'); const NFT2 = new BN(2);
const NFT3 = web3.utils.toWei('30'); const NFT3 = new BN(3);
const NFT4 = web3.utils.toWei('40'); const NFT4 = new BN(4);
const votingDelay = new BN(4);
// Must be the same as in contract const votingPeriod = new BN(16);
const ProposalState = { const value = web3.utils.toWei('1');
Pending: new BN('0'),
Active: new BN('1'),
Canceled: new BN('2'),
Defeated: new BN('3'),
Succeeded: new BN('4'),
Queued: new BN('5'),
Expired: new BN('6'),
Executed: new BN('7'),
};
beforeEach(async function () { beforeEach(async function () {
this.owner = owner; this.owner = owner;
this.token = await Token.new(tokenName, tokenSymbol); this.token = await Token.new(tokenName, tokenSymbol);
this.mock = await Governor.new(name, this.token.address); this.mock = await Governor.new(name, this.token.address);
this.receiver = await CallReceiver.new(); this.receiver = await CallReceiver.new();
await this.token.mint(owner, NFT0);
await this.token.mint(owner, NFT1); this.helper = new GovernorHelper(this.mock);
await this.token.mint(owner, NFT2);
await this.token.mint(owner, NFT3); await web3.eth.sendTransaction({ from: owner, to: this.mock.address, value });
await this.token.mint(owner, NFT4);
await Promise.all([ NFT0, NFT1, NFT2, NFT3, NFT4 ].map(tokenId => this.token.mint(owner, tokenId)));
await this.token.delegate(voter1, { from: voter1 }); await this.helper.delegate({ token: this.token, to: voter1, tokenId: NFT0 }, { from: owner });
await this.token.delegate(voter2, { from: voter2 }); await this.helper.delegate({ token: this.token, to: voter2, tokenId: NFT1 }, { from: owner });
await this.token.delegate(voter3, { from: voter3 }); await this.helper.delegate({ token: this.token, to: voter2, tokenId: NFT2 }, { from: owner });
await this.token.delegate(voter4, { from: voter4 }); 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 () { it('deployment check', async function () {
expect(await this.mock.name()).to.be.equal(name); expect(await this.mock.name()).to.be.equal(name);
expect(await this.mock.token()).to.be.equal(this.token.address); expect(await this.mock.token()).to.be.equal(this.token.address);
expect(await this.mock.votingDelay()).to.be.bignumber.equal('4'); expect(await this.mock.votingDelay()).to.be.bignumber.equal(votingDelay);
expect(await this.mock.votingPeriod()).to.be.bignumber.equal('16'); 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.quorum(0)).to.be.bignumber.equal('0');
}); });
describe('voting with ERC721 token', function () { it('voting with ERC721 token', async function () {
beforeEach(async function () { await this.helper.propose();
this.settings = { await this.helper.waitForSnapshot();
proposal: [
[ this.receiver.address ],
[ web3.utils.toWei('0') ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
tokenHolder: owner,
voters: [
{ voter: voter1, nfts: [NFT0], support: Enums.VoteType.For },
{ voter: voter2, nfts: [NFT1, NFT2], support: Enums.VoteType.For },
{ voter: voter3, nfts: [NFT3], support: Enums.VoteType.Against },
{ voter: voter4, nfts: [NFT4], support: Enums.VoteType.Abstain },
],
};
});
afterEach(async function () {
expect(await this.mock.hasVoted(this.id, owner)).to.be.equal(false);
for (const vote of this.receipts.castVote.filter(Boolean)) { expectEvent(
const { voter } = vote.logs.find(Boolean).args; await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 }),
'VoteCast',
{ voter: voter1, support: Enums.VoteType.For, weight: '1' },
);
expect(await this.mock.hasVoted(this.id, voter)).to.be.equal(true); expectEvent(
await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 }),
'VoteCast',
{ voter: voter2, support: Enums.VoteType.For, weight: '2' },
);
expectEvent( expectEvent(
vote, await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter3 }),
'VoteCast', 'VoteCast',
this.settings.voters.find(({ address }) => address === voter), { voter: voter3, support: Enums.VoteType.Against, weight: '1' },
); );
if (voter === voter2) { expectEvent(
expect(await this.token.getVotes(voter, vote.blockNumber)).to.be.bignumber.equal('2'); await this.helper.vote({ support: Enums.VoteType.Abstain }, { from: voter4 }),
} else { 'VoteCast',
expect(await this.token.getVotes(voter, vote.blockNumber)).to.be.bignumber.equal('1'); { voter: voter4, support: Enums.VoteType.Abstain, weight: '1' },
}
}
await this.mock.proposalVotes(this.id).then(result => {
for (const [key, value] of Object.entries(Enums.VoteType)) {
expect(result[`${key.toLowerCase()}Votes`]).to.be.bignumber.equal(
Object.values(this.settings.voters).filter(({ support }) => support === value).reduce(
(acc, { nfts }) => acc.add(new BN(nfts.length)),
new BN('0'),
),
); );
}
});
expect(await this.mock.state(this.id)).to.be.bignumber.equal(ProposalState.Executed); await this.helper.waitForDeadline();
}); await this.helper.execute();
runGovernorWorkflow(); 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');
});
}); });
}); });
const { BN, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers'); const { BN, expectEvent, expectRevert } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const Enums = require('../../helpers/enums'); const Enums = require('../../helpers/enums');
const { GovernorHelper } = require('../../helpers/governance');
const {
runGovernorWorkflow,
} = require('../GovernorWorkflow.behavior');
const Token = artifacts.require('ERC20VotesCompMock'); const Token = artifacts.require('ERC20VotesCompMock');
const Governor = artifacts.require('GovernorPreventLateQuorumMock'); const Governor = artifacts.require('GovernorPreventLateQuorumMock');
...@@ -21,6 +19,7 @@ contract('GovernorPreventLateQuorum', function (accounts) { ...@@ -21,6 +19,7 @@ contract('GovernorPreventLateQuorum', function (accounts) {
const votingPeriod = new BN(16); const votingPeriod = new BN(16);
const lateQuorumVoteExtension = new BN(8); const lateQuorumVoteExtension = new BN(8);
const quorum = web3.utils.toWei('1'); const quorum = web3.utils.toWei('1');
const value = web3.utils.toWei('1');
beforeEach(async function () { beforeEach(async function () {
this.owner = owner; this.owner = owner;
...@@ -34,11 +33,25 @@ contract('GovernorPreventLateQuorum', function (accounts) { ...@@ -34,11 +33,25 @@ contract('GovernorPreventLateQuorum', function (accounts) {
lateQuorumVoteExtension, lateQuorumVoteExtension,
); );
this.receiver = await CallReceiver.new(); this.receiver = await CallReceiver.new();
this.helper = new GovernorHelper(this.mock);
await web3.eth.sendTransaction({ from: owner, to: this.mock.address, value });
await this.token.mint(owner, tokenSupply); await this.token.mint(owner, tokenSupply);
await this.token.delegate(voter1, { from: voter1 }); await this.helper.delegate({ token: this.token, to: voter1, value: web3.utils.toWei('10') }, { from: owner });
await this.token.delegate(voter2, { from: voter2 }); await this.helper.delegate({ token: this.token, to: voter2, value: web3.utils.toWei('7') }, { from: owner });
await this.token.delegate(voter3, { from: voter3 }); await this.helper.delegate({ token: this.token, to: voter3, value: web3.utils.toWei('5') }, { from: owner });
await this.token.delegate(voter4, { from: voter4 }); 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 () { it('deployment check', async function () {
...@@ -50,198 +63,115 @@ contract('GovernorPreventLateQuorum', function (accounts) { ...@@ -50,198 +63,115 @@ contract('GovernorPreventLateQuorum', function (accounts) {
expect(await this.mock.lateQuorumVoteExtension()).to.be.bignumber.equal(lateQuorumVoteExtension); expect(await this.mock.lateQuorumVoteExtension()).to.be.bignumber.equal(lateQuorumVoteExtension);
}); });
describe('nominal is unaffected', function () { it('nominal workflow unaffected', async function () {
beforeEach(async function () { const txPropose = await this.helper.propose({ from: proposer });
this.settings = { await this.helper.waitForSnapshot();
proposal: [ await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
[ this.receiver.address ], await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 });
[ 0 ], await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter3 });
[ this.receiver.contract.methods.mockFunction().encodeABI() ], await this.helper.vote({ support: Enums.VoteType.Abstain }, { from: voter4 });
'<proposal description>', await this.helper.waitForDeadline();
], await this.helper.execute();
proposer,
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('1'), support: Enums.VoteType.For, reason: 'This is nice' },
{ voter: voter2, weight: web3.utils.toWei('7'), support: Enums.VoteType.For },
{ voter: voter3, weight: web3.utils.toWei('5'), support: Enums.VoteType.Against },
{ voter: voter4, weight: web3.utils.toWei('2'), support: Enums.VoteType.Abstain },
],
};
});
afterEach(async function () { expect(await this.mock.hasVoted(this.proposal.id, owner)).to.be.equal(false);
expect(await this.mock.hasVoted(this.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.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.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.id).then(result => {
for (const [key, value] of Object.entries(Enums.VoteType)) { await this.mock.proposalVotes(this.proposal.id).then(results => {
expect(result[`${key.toLowerCase()}Votes`]).to.be.bignumber.equal( expect(results.forVotes).to.be.bignumber.equal(web3.utils.toWei('17'));
Object.values(this.settings.voters).filter(({ support }) => support === value).reduce( expect(results.againstVotes).to.be.bignumber.equal(web3.utils.toWei('5'));
(acc, { weight }) => acc.add(new BN(weight)), expect(results.abstainVotes).to.be.bignumber.equal(web3.utils.toWei('2'));
new BN('0'),
),
);
}
}); });
const startBlock = new BN(this.receipts.propose.blockNumber).add(votingDelay); const startBlock = new BN(txPropose.receipt.blockNumber).add(votingDelay);
const endBlock = new BN(this.receipts.propose.blockNumber).add(votingDelay).add(votingPeriod); const endBlock = new BN(txPropose.receipt.blockNumber).add(votingDelay).add(votingPeriod);
expect(await this.mock.proposalSnapshot(this.id)).to.be.bignumber.equal(startBlock); expect(await this.mock.proposalSnapshot(this.proposal.id)).to.be.bignumber.equal(startBlock);
expect(await this.mock.proposalDeadline(this.id)).to.be.bignumber.equal(endBlock); expect(await this.mock.proposalDeadline(this.proposal.id)).to.be.bignumber.equal(endBlock);
expectEvent( expectEvent(
this.receipts.propose, txPropose,
'ProposalCreated', 'ProposalCreated',
{ {
proposalId: this.id, proposalId: this.proposal.id,
proposer, proposer,
targets: this.settings.proposal[0], targets: this.proposal.targets,
// values: this.settings.proposal[1].map(value => new BN(value)), // values: this.proposal.values.map(value => new BN(value)),
signatures: this.settings.proposal[2].map(() => ''), signatures: this.proposal.signatures,
calldatas: this.settings.proposal[2], calldatas: this.proposal.data,
startBlock, startBlock,
endBlock, endBlock,
description: this.settings.proposal[3], description: this.proposal.description,
}, },
); );
this.receipts.castVote.filter(Boolean).forEach(vote => {
const { voter } = vote.logs.find(Boolean).args;
expectEvent(
vote,
'VoteCast',
this.settings.voters.find(({ address }) => address === voter),
);
expectEvent.notEmitted(
vote,
'ProposalExtended',
);
});
expectEvent(
this.receipts.execute,
'ProposalExecuted',
{ proposalId: this.id },
);
await expectEvent.inTransaction(
this.receipts.execute.transactionHash,
this.receiver,
'MockFunctionCalled',
);
});
runGovernorWorkflow();
}); });
describe('Delay is extended to prevent last minute take-over', function () { it('Delay is extended to prevent last minute take-over', async function () {
beforeEach(async function () { const txPropose = await this.helper.propose({ from: proposer });
this.settings = {
proposal: [ // compute original schedule
[ this.receiver.address ], const startBlock = new BN(txPropose.receipt.blockNumber).add(votingDelay);
[ 0 ], const endBlock = new BN(txPropose.receipt.blockNumber).add(votingDelay).add(votingPeriod);
[ this.receiver.contract.methods.mockFunction().encodeABI() ], expect(await this.mock.proposalSnapshot(this.proposal.id)).to.be.bignumber.equal(startBlock);
'<proposal description>', expect(await this.mock.proposalDeadline(this.proposal.id)).to.be.bignumber.equal(endBlock);
],
proposer,
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('0.2'), support: Enums.VoteType.Against },
{ voter: voter2, weight: web3.utils.toWei('1.0') }, // do not actually vote, only getting tokens
{ voter: voter3, weight: web3.utils.toWei('0.9') }, // do not actually vote, only getting tokens
],
steps: {
wait: { enable: false },
execute: { enable: false },
},
};
});
afterEach(async function () { // wait for the last minute to vote
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Active); await this.helper.waitForDeadline(-1);
const txVote = await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 });
const startBlock = new BN(this.receipts.propose.blockNumber).add(votingDelay); // cannot execute yet
const endBlock = new BN(this.receipts.propose.blockNumber).add(votingDelay).add(votingPeriod); expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Active);
expect(await this.mock.proposalSnapshot(this.id)).to.be.bignumber.equal(startBlock);
expect(await this.mock.proposalDeadline(this.id)).to.be.bignumber.equal(endBlock);
// wait until the vote is almost over // compute new extended schedule
await time.advanceBlockTo(endBlock.subn(1)); const extendedDeadline = new BN(txVote.receipt.blockNumber).add(lateQuorumVoteExtension);
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Active); 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);
// try to overtake the vote at the last minute // still possible to vote
const tx = await this.mock.castVote(this.id, Enums.VoteType.For, { from: voter2 }); await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter1 });
// vote duration is extended await this.helper.waitForDeadline();
const extendedBlock = new BN(tx.receipt.blockNumber).add(lateQuorumVoteExtension); expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Active);
expect(await this.mock.proposalDeadline(this.id)).to.be.bignumber.equal(extendedBlock); await this.helper.waitForDeadline(+1);
expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Defeated);
// check extension event
expectEvent( expectEvent(
tx, txVote,
'ProposalExtended', 'ProposalExtended',
{ proposalId: this.id, extendedDeadline: extendedBlock }, { proposalId: this.proposal.id, extendedDeadline },
); );
// vote is still active after expected end
await time.advanceBlockTo(endBlock.addn(1));
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Active);
// Still possible to vote
await this.mock.castVote(this.id, Enums.VoteType.Against, { from: voter3 });
// proposal fails
await time.advanceBlockTo(extendedBlock.addn(1));
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Defeated);
});
runGovernorWorkflow();
});
describe('setLateQuorumVoteExtension', function () {
beforeEach(async function () {
this.newVoteExtension = new BN(0); // disable voting delay extension
}); });
it('protected', async function () { describe('onlyGovernance updates', function () {
it('setLateQuorumVoteExtension is protected', async function () {
await expectRevert( await expectRevert(
this.mock.setLateQuorumVoteExtension(this.newVoteExtension), this.mock.setLateQuorumVoteExtension(0),
'Governor: onlyGovernance', 'Governor: onlyGovernance',
); );
}); });
describe('using workflow', function () { it('can setLateQuorumVoteExtension through governance', async function () {
beforeEach(async function () { this.helper.setProposal([
this.settings = { {
proposal: [ target: this.mock.address,
[ this.mock.address ], data: this.mock.contract.methods.setLateQuorumVoteExtension('0').encodeABI(),
[ web3.utils.toWei('0') ], },
[ this.mock.contract.methods.setLateQuorumVoteExtension(this.newVoteExtension).encodeABI() ], ], '<proposal description>');
'<proposal description>',
], await this.helper.propose();
proposer, await this.helper.waitForSnapshot();
tokenHolder: owner, await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
voters: [ await this.helper.waitForDeadline();
{ voter: voter1, weight: web3.utils.toWei('1.0'), support: Enums.VoteType.For },
],
};
});
afterEach(async function () {
expectEvent(
this.receipts.propose,
'ProposalCreated',
{ proposalId: this.id },
);
expectEvent(
this.receipts.execute,
'ProposalExecuted',
{ proposalId: this.id },
);
expectEvent( expectEvent(
this.receipts.execute, await this.helper.execute(),
'LateQuorumVoteExtensionSet', 'LateQuorumVoteExtensionSet',
{ oldVoteExtension: lateQuorumVoteExtension, newVoteExtension: this.newVoteExtension }, { oldVoteExtension: lateQuorumVoteExtension, newVoteExtension: '0' },
); );
expect(await this.mock.lateQuorumVoteExtension()).to.be.bignumber.equal(this.newVoteExtension);
}); expect(await this.mock.lateQuorumVoteExtension()).to.be.bignumber.equal('0');
runGovernorWorkflow();
}); });
}); });
}); });
const { constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers'); const { BN, constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers');
const { expect } = require('chai'); const { expect } = require('chai');
const Enums = require('../../helpers/enums');
const RLP = require('rlp'); const RLP = require('rlp');
const Enums = require('../../helpers/enums');
const { const { GovernorHelper } = require('../../helpers/governance');
runGovernorWorkflow,
} = require('../GovernorWorkflow.behavior');
const { const {
shouldSupportInterfaces, shouldSupportInterfaces,
...@@ -21,13 +18,16 @@ function makeContractAddress (creator, nonce) { ...@@ -21,13 +18,16 @@ function makeContractAddress (creator, nonce) {
} }
contract('GovernorTimelockCompound', function (accounts) { contract('GovernorTimelockCompound', function (accounts) {
const [ admin, voter, other ] = accounts; const [ owner, voter1, voter2, voter3, voter4, other ] = accounts;
const name = 'OZ-Governor'; const name = 'OZ-Governor';
// const version = '1'; // const version = '1';
const tokenName = 'MockToken'; const tokenName = 'MockToken';
const tokenSymbol = 'MTKN'; const tokenSymbol = 'MTKN';
const tokenSupply = web3.utils.toWei('100'); const tokenSupply = web3.utils.toWei('100');
const votingDelay = new BN(4);
const votingPeriod = new BN(16);
const value = web3.utils.toWei('1');
beforeEach(async function () { beforeEach(async function () {
const [ deployer ] = await web3.eth.getAccounts(); const [ deployer ] = await web3.eth.getAccounts();
...@@ -39,10 +39,34 @@ contract('GovernorTimelockCompound', function (accounts) { ...@@ -39,10 +39,34 @@ contract('GovernorTimelockCompound', function (accounts) {
const predictGovernor = makeContractAddress(deployer, nonce + 1); const predictGovernor = makeContractAddress(deployer, nonce + 1);
this.timelock = await Timelock.new(predictGovernor, 2 * 86400); this.timelock = await Timelock.new(predictGovernor, 2 * 86400);
this.mock = await Governor.new(name, this.token.address, 4, 16, this.timelock.address, 0); this.mock = await Governor.new(
name,
this.token.address,
votingDelay,
votingPeriod,
this.timelock.address,
0,
);
this.receiver = await CallReceiver.new(); this.receiver = await CallReceiver.new();
await this.token.mint(voter, tokenSupply);
await this.token.delegate(voter, { from: voter }); this.helper = new GovernorHelper(this.mock);
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([ shouldSupportInterfaces([
...@@ -53,330 +77,220 @@ contract('GovernorTimelockCompound', function (accounts) { ...@@ -53,330 +77,220 @@ contract('GovernorTimelockCompound', function (accounts) {
]); ]);
it('doesn\'t accept ether transfers', async function () { it('doesn\'t accept ether transfers', async function () {
await expectRevert.unspecified(web3.eth.sendTransaction({ from: voter, to: this.mock.address, value: 1 })); await expectRevert.unspecified(web3.eth.sendTransaction({ from: owner, to: this.mock.address, value: 1 }));
}); });
it('post deployment check', async function () { it('post deployment check', async function () {
expect(await this.mock.name()).to.be.equal(name); expect(await this.mock.name()).to.be.equal(name);
expect(await this.mock.token()).to.be.equal(this.token.address); expect(await this.mock.token()).to.be.equal(this.token.address);
expect(await this.mock.votingDelay()).to.be.bignumber.equal('4'); expect(await this.mock.votingDelay()).to.be.bignumber.equal(votingDelay);
expect(await this.mock.votingPeriod()).to.be.bignumber.equal('16'); 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.quorum(0)).to.be.bignumber.equal('0');
expect(await this.mock.timelock()).to.be.equal(this.timelock.address); expect(await this.mock.timelock()).to.be.equal(this.timelock.address);
expect(await this.timelock.admin()).to.be.equal(this.mock.address); expect(await this.timelock.admin()).to.be.equal(this.mock.address);
}); });
describe('nominal', function () { it('nominal', async function () {
beforeEach(async function () { await this.helper.propose();
this.settings = { await this.helper.waitForSnapshot();
proposal: [ await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
[ this.receiver.address ], await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 });
[ web3.utils.toWei('0') ], await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter3 });
[ this.receiver.contract.methods.mockFunction().encodeABI() ], await this.helper.vote({ support: Enums.VoteType.Abstain }, { from: voter4 });
'<proposal description>', await this.helper.waitForDeadline();
], const txQueue = await this.helper.queue();
voters: [ const eta = await this.mock.proposalEta(this.proposal.id);
{ voter: voter, support: Enums.VoteType.For }, await this.helper.waitForEta();
], const txExecute = await this.helper.execute();
steps: {
queue: { delay: 7 * 86400 }, 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>');
afterEach(async function () {
expectEvent( await this.helper.propose();
this.receipts.propose, await this.helper.waitForSnapshot();
'ProposalCreated', await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
{ proposalId: this.id }, await this.helper.waitForDeadline();
); await expectRevert(
expectEvent( this.helper.queue(),
this.receipts.queue, 'GovernorTimelockCompound: identical proposal action already queued',
'ProposalQueued',
{ proposalId: this.id },
);
await expectEvent.inTransaction(
this.receipts.queue.transactionHash,
this.timelock,
'QueueTransaction',
{ eta: this.eta },
);
expectEvent(
this.receipts.execute,
'ProposalExecuted',
{ proposalId: this.id },
);
await expectEvent.inTransaction(
this.receipts.execute.transactionHash,
this.timelock,
'ExecuteTransaction',
{ eta: this.eta },
); );
await expectEvent.inTransaction( await expectRevert(
this.receipts.execute.transactionHash, this.helper.execute(),
this.receiver, 'GovernorTimelockCompound: proposal not yet queued',
'MockFunctionCalled',
); );
}); });
runGovernorWorkflow();
}); });
describe('not queued', function () { describe('on execute', function () {
beforeEach(async function () { it('if not queued', async function () {
this.settings = { await this.helper.propose();
proposal: [ await this.helper.waitForSnapshot();
[ this.receiver.address ], await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
[ web3.utils.toWei('0') ], await this.helper.waitForDeadline(+1);
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
voters: [
{ voter: voter, support: Enums.VoteType.For },
],
steps: {
queue: { enable: false },
execute: { error: 'GovernorTimelockCompound: proposal not yet queued' },
},
};
});
afterEach(async function () {
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Succeeded);
});
runGovernorWorkflow();
});
describe('to early', function () { expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Succeeded);
beforeEach(async function () {
this.settings = {
proposal: [
[ this.receiver.address ],
[ web3.utils.toWei('0') ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
voters: [
{ voter: voter, support: Enums.VoteType.For },
],
steps: {
execute: { error: 'Timelock::executeTransaction: Transaction hasn\'t surpassed time lock' },
},
};
});
afterEach(async function () {
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Queued);
});
runGovernorWorkflow();
});
describe('to late', function () { await expectRevert(
beforeEach(async function () { this.helper.execute(),
this.settings = { 'GovernorTimelockCompound: proposal not yet queued',
proposal: [ );
[ this.receiver.address ],
[ web3.utils.toWei('0') ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
voters: [
{ voter: voter, support: Enums.VoteType.For },
],
steps: {
queue: { delay: 30 * 86400 },
execute: { error: 'Governor: proposal not successful' },
},
};
});
afterEach(async function () {
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Expired);
});
runGovernorWorkflow();
}); });
describe('deplicated underlying call', function () { it('if too early', async function () {
beforeEach(async function () { await this.helper.propose();
this.settings = { await this.helper.waitForSnapshot();
proposal: [ await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
Array(2).fill(this.token.address), await this.helper.waitForDeadline();
Array(2).fill(web3.utils.toWei('0')), await this.helper.queue();
Array(2).fill(this.token.contract.methods.approve(this.receiver.address, constants.MAX_UINT256).encodeABI()),
'<proposal description>',
],
voters: [
{ voter: voter, support: Enums.VoteType.For },
],
steps: {
queue: {
error: 'GovernorTimelockCompound: identical proposal action already queued',
},
execute: {
error: 'GovernorTimelockCompound: proposal not yet queued',
},
},
};
});
runGovernorWorkflow();
});
describe('re-queue / re-execute', function () { expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Queued);
beforeEach(async function () {
this.settings = { await expectRevert(
proposal: [ this.helper.execute(),
[ this.receiver.address ], 'Timelock::executeTransaction: Transaction hasn\'t surpassed time lock',
[ web3.utils.toWei('0') ], );
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
voters: [
{ voter: voter, support: Enums.VoteType.For },
],
steps: {
queue: { delay: 7 * 86400 },
},
};
}); });
afterEach(async function () {
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Executed); 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( await expectRevert(
this.mock.queue(...this.settings.proposal.slice(0, -1), this.descriptionHash), this.helper.execute(),
'Governor: proposal not successful', '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( await expectRevert(
this.mock.execute(...this.settings.proposal.slice(0, -1), this.descriptionHash), this.helper.execute(),
'Governor: proposal not successful', 'Governor: proposal not successful',
); );
}); });
runGovernorWorkflow();
}); });
describe('cancel before queue prevents scheduling', function () {
beforeEach(async function () {
this.settings = {
proposal: [
[ this.receiver.address ],
[ web3.utils.toWei('0') ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
voters: [
{ voter: voter, support: Enums.VoteType.For },
],
steps: {
queue: { enable: false },
execute: { enable: false },
},
};
}); });
afterEach(async function () {
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Succeeded); 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( expectEvent(
await this.mock.cancel(...this.settings.proposal.slice(0, -1), this.descriptionHash), await this.helper.cancel(),
'ProposalCanceled', 'ProposalCanceled',
{ proposalId: this.id }, { proposalId: this.proposal.id },
); );
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled); expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled);
await expectRevert(this.helper.queue(), 'Governor: proposal not successful');
await expectRevert(
this.mock.queue(...this.settings.proposal.slice(0, -1), this.descriptionHash),
'Governor: proposal not successful',
);
});
runGovernorWorkflow();
}); });
describe('cancel after queue prevents executing', function () { it('cancel after queue prevents executing', async function () {
beforeEach(async function () { await this.helper.propose();
this.settings = { await this.helper.waitForSnapshot();
proposal: [ await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
[ this.receiver.address ], await this.helper.waitForDeadline();
[ web3.utils.toWei('0') ], await this.helper.queue();
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
voters: [
{ voter: voter, support: Enums.VoteType.For },
],
steps: {
queue: { delay: 7 * 86400 },
execute: { enable: false },
},
};
});
afterEach(async function () {
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Queued);
const receipt = await this.mock.cancel(...this.settings.proposal.slice(0, -1), this.descriptionHash);
expectEvent( expectEvent(
receipt, await this.helper.cancel(),
'ProposalCanceled', 'ProposalCanceled',
{ proposalId: this.id }, { proposalId: this.proposal.id },
); );
await expectEvent.inTransaction(
receipt.receipt.transactionHash,
this.timelock,
'CancelTransaction',
);
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled);
await expectRevert( expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled);
this.mock.execute(...this.settings.proposal.slice(0, -1), this.descriptionHash), await expectRevert(this.helper.execute(), 'Governor: proposal not successful');
'Governor: proposal not successful',
);
}); });
runGovernorWorkflow();
}); });
describe('onlyGovernance', function () {
describe('relay', function () { describe('relay', function () {
beforeEach(async function () { beforeEach(async function () {
await this.token.mint(this.mock.address, 1); await this.token.mint(this.mock.address, 1);
this.call = [
this.token.address,
0,
this.token.contract.methods.transfer(other, 1).encodeABI(),
];
}); });
it('protected', async function () { it('is protected', async function () {
await expectRevert( await expectRevert(
this.mock.relay(...this.call), this.mock.relay(
this.token.address,
0,
this.token.contract.methods.transfer(other, 1).encodeABI(),
),
'Governor: onlyGovernance', 'Governor: onlyGovernance',
); );
}); });
describe('using workflow', function () { it('can be executed through governance', async function () {
beforeEach(async function () { this.helper.setProposal([
this.settings = { {
proposal: [ target: this.mock.address,
[ data: this.mock.contract.methods.relay(
this.mock.address, this.token.address,
], 0,
[ this.token.contract.methods.transfer(other, 1).encodeABI(),
web3.utils.toWei('0'), ).encodeABI(),
],
[
this.mock.contract.methods.relay(...this.call).encodeABI(),
],
'<proposal description>',
],
voters: [
{ voter: voter, support: Enums.VoteType.For },
],
steps: {
queue: { delay: 7 * 86400 },
}, },
}; ], '<proposal description>');
expect(await this.token.balanceOf(this.mock.address), 1); expect(await this.token.balanceOf(this.mock.address), 1);
expect(await this.token.balanceOf(other), 0); expect(await this.token.balanceOf(other), 0);
});
afterEach(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();
const txExecute = await this.helper.execute();
expect(await this.token.balanceOf(this.mock.address), 0); expect(await this.token.balanceOf(this.mock.address), 0);
expect(await this.token.balanceOf(other), 1); expect(await this.token.balanceOf(other), 1);
});
runGovernorWorkflow(); expectEvent.inTransaction(
txExecute.tx,
this.token,
'Transfer',
{ from: this.mock.address, to: other, value: '1' },
);
}); });
}); });
...@@ -385,104 +299,70 @@ contract('GovernorTimelockCompound', function (accounts) { ...@@ -385,104 +299,70 @@ contract('GovernorTimelockCompound', function (accounts) {
this.newTimelock = await Timelock.new(this.mock.address, 7 * 86400); this.newTimelock = await Timelock.new(this.mock.address, 7 * 86400);
}); });
it('protected', async function () { it('is protected', async function () {
await expectRevert( await expectRevert(
this.mock.updateTimelock(this.newTimelock.address), this.mock.updateTimelock(this.newTimelock.address),
'Governor: onlyGovernance', 'Governor: onlyGovernance',
); );
}); });
describe('using workflow', function () { it('can be executed through governance to', async function () {
beforeEach(async function () { this.helper.setProposal([
this.settings = { {
proposal: [ target: this.timelock.address,
[ data: this.timelock.contract.methods.setPendingAdmin(owner).encodeABI(),
this.timelock.address,
this.mock.address,
],
[
web3.utils.toWei('0'),
web3.utils.toWei('0'),
],
[
this.timelock.contract.methods.setPendingAdmin(admin).encodeABI(),
this.mock.contract.methods.updateTimelock(this.newTimelock.address).encodeABI(),
],
'<proposal description>',
],
voters: [
{ voter: voter, support: Enums.VoteType.For },
],
steps: {
queue: { delay: 7 * 86400 },
}, },
}; {
}); target: this.mock.address,
afterEach(async function () { data: this.mock.contract.methods.updateTimelock(this.newTimelock.address).encodeABI(),
expectEvent( },
this.receipts.propose, ], '<proposal description>');
'ProposalCreated',
{ proposalId: this.id }, await this.helper.propose();
); await this.helper.waitForSnapshot();
expectEvent( await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
this.receipts.execute, await this.helper.waitForDeadline();
'ProposalExecuted', await this.helper.queue();
{ proposalId: this.id }, await this.helper.waitForEta();
); const txExecute = await this.helper.execute();
expectEvent( expectEvent(
this.receipts.execute, txExecute,
'TimelockChange', 'TimelockChange',
{ oldTimelock: this.timelock.address, newTimelock: this.newTimelock.address }, { oldTimelock: this.timelock.address, newTimelock: this.newTimelock.address },
); );
expect(await this.mock.timelock()).to.be.bignumber.equal(this.newTimelock.address); expect(await this.mock.timelock()).to.be.bignumber.equal(this.newTimelock.address);
}); });
runGovernorWorkflow();
});
}); });
describe('transfer timelock to new governor', function () { it('can transfer timelock to new governor', async function () {
beforeEach(async function () { const newGovernor = await Governor.new(name, this.token.address, 8, 32, this.timelock.address, 0);
this.newGovernor = await Governor.new(name, this.token.address, 8, 32, this.timelock.address, 0);
});
describe('using workflow', function () { this.helper.setProposal([
beforeEach(async function () { {
this.settings = { target: this.timelock.address,
proposal: [ data: this.timelock.contract.methods.setPendingAdmin(newGovernor.address).encodeABI(),
[ this.timelock.address ],
[ web3.utils.toWei('0') ],
[ this.timelock.contract.methods.setPendingAdmin(this.newGovernor.address).encodeABI() ],
'<proposal description>',
],
voters: [
{ voter: voter, support: Enums.VoteType.For },
],
steps: {
queue: { delay: 7 * 86400 },
}, },
}; ], '<proposal description>');
});
afterEach(async function () { await this.helper.propose();
expectEvent( await this.helper.waitForSnapshot();
this.receipts.propose, await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
'ProposalCreated', await this.helper.waitForDeadline();
{ proposalId: this.id }, await this.helper.queue();
); await this.helper.waitForEta();
expectEvent( const txExecute = await this.helper.execute();
this.receipts.execute,
'ProposalExecuted',
{ proposalId: this.id },
);
await expectEvent.inTransaction( await expectEvent.inTransaction(
this.receipts.execute.transactionHash, txExecute.tx,
this.timelock, this.timelock,
'NewPendingAdmin', 'NewPendingAdmin',
{ newPendingAdmin: this.newGovernor.address }, { newPendingAdmin: newGovernor.address },
); );
await this.newGovernor.__acceptAdmin();
expect(await this.timelock.admin()).to.be.bignumber.equal(this.newGovernor.address); await newGovernor.__acceptAdmin();
}); expect(await this.timelock.admin()).to.be.bignumber.equal(newGovernor.address);
runGovernorWorkflow();
}); });
}); });
}); });
const { constants, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers'); const { BN, constants, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers');
const { expect } = require('chai'); const { expect } = require('chai');
const Enums = require('../../helpers/enums'); const Enums = require('../../helpers/enums');
const { GovernorHelper } = require('../../helpers/governance');
const {
runGovernorWorkflow,
} = require('../GovernorWorkflow.behavior');
const { const {
shouldSupportInterfaces, shouldSupportInterfaces,
...@@ -16,7 +13,7 @@ const Governor = artifacts.require('GovernorTimelockControlMock'); ...@@ -16,7 +13,7 @@ const Governor = artifacts.require('GovernorTimelockControlMock');
const CallReceiver = artifacts.require('CallReceiverMock'); const CallReceiver = artifacts.require('CallReceiverMock');
contract('GovernorTimelockControl', function (accounts) { contract('GovernorTimelockControl', function (accounts) {
const [ admin, voter, other ] = accounts; const [ owner, voter1, voter2, voter3, voter4, other ] = accounts;
const TIMELOCK_ADMIN_ROLE = web3.utils.soliditySha3('TIMELOCK_ADMIN_ROLE'); const TIMELOCK_ADMIN_ROLE = web3.utils.soliditySha3('TIMELOCK_ADMIN_ROLE');
const PROPOSER_ROLE = web3.utils.soliditySha3('PROPOSER_ROLE'); const PROPOSER_ROLE = web3.utils.soliditySha3('PROPOSER_ROLE');
...@@ -28,30 +25,61 @@ contract('GovernorTimelockControl', function (accounts) { ...@@ -28,30 +25,61 @@ contract('GovernorTimelockControl', function (accounts) {
const tokenName = 'MockToken'; const tokenName = 'MockToken';
const tokenSymbol = 'MTKN'; const tokenSymbol = 'MTKN';
const tokenSupply = web3.utils.toWei('100'); const tokenSupply = web3.utils.toWei('100');
const votingDelay = new BN(4);
const votingPeriod = new BN(16);
const value = web3.utils.toWei('1');
beforeEach(async function () { beforeEach(async function () {
const [ deployer ] = await web3.eth.getAccounts(); const [ deployer ] = await web3.eth.getAccounts();
this.token = await Token.new(tokenName, tokenSymbol); this.token = await Token.new(tokenName, tokenSymbol);
this.timelock = await Timelock.new(3600, [], []); this.timelock = await Timelock.new(3600, [], []);
this.mock = await Governor.new(name, this.token.address, 4, 16, this.timelock.address, 0); this.mock = await Governor.new(
name,
this.token.address,
votingDelay,
votingPeriod,
this.timelock.address,
0,
);
this.receiver = await CallReceiver.new(); this.receiver = await CallReceiver.new();
this.helper = new GovernorHelper(this.mock);
this.TIMELOCK_ADMIN_ROLE = await this.timelock.TIMELOCK_ADMIN_ROLE(); this.TIMELOCK_ADMIN_ROLE = await this.timelock.TIMELOCK_ADMIN_ROLE();
this.PROPOSER_ROLE = await this.timelock.PROPOSER_ROLE(); this.PROPOSER_ROLE = await this.timelock.PROPOSER_ROLE();
this.EXECUTOR_ROLE = await this.timelock.EXECUTOR_ROLE(); this.EXECUTOR_ROLE = await this.timelock.EXECUTOR_ROLE();
this.CANCELLER_ROLE = await this.timelock.CANCELLER_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 // 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, this.mock.address);
await this.timelock.grantRole(PROPOSER_ROLE, admin); await this.timelock.grantRole(PROPOSER_ROLE, owner);
await this.timelock.grantRole(CANCELLER_ROLE, this.mock.address); await this.timelock.grantRole(CANCELLER_ROLE, this.mock.address);
await this.timelock.grantRole(CANCELLER_ROLE, admin); await this.timelock.grantRole(CANCELLER_ROLE, owner);
await this.timelock.grantRole(EXECUTOR_ROLE, constants.ZERO_ADDRESS); await this.timelock.grantRole(EXECUTOR_ROLE, constants.ZERO_ADDRESS);
await this.timelock.revokeRole(TIMELOCK_ADMIN_ROLE, deployer); await this.timelock.revokeRole(TIMELOCK_ADMIN_ROLE, deployer);
await this.token.mint(voter, tokenSupply); await this.token.mint(owner, tokenSupply);
await this.token.delegate(voter, { from: voter }); 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([ shouldSupportInterfaces([
...@@ -62,294 +90,206 @@ contract('GovernorTimelockControl', function (accounts) { ...@@ -62,294 +90,206 @@ contract('GovernorTimelockControl', function (accounts) {
]); ]);
it('doesn\'t accept ether transfers', async function () { it('doesn\'t accept ether transfers', async function () {
await expectRevert.unspecified(web3.eth.sendTransaction({ from: voter, to: this.mock.address, value: 1 })); await expectRevert.unspecified(web3.eth.sendTransaction({ from: owner, to: this.mock.address, value: 1 }));
}); });
it('post deployment check', async function () { it('post deployment check', async function () {
expect(await this.mock.name()).to.be.equal(name); expect(await this.mock.name()).to.be.equal(name);
expect(await this.mock.token()).to.be.equal(this.token.address); expect(await this.mock.token()).to.be.equal(this.token.address);
expect(await this.mock.votingDelay()).to.be.bignumber.equal('4'); expect(await this.mock.votingDelay()).to.be.bignumber.equal(votingDelay);
expect(await this.mock.votingPeriod()).to.be.bignumber.equal('16'); 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.quorum(0)).to.be.bignumber.equal('0');
expect(await this.mock.timelock()).to.be.equal(this.timelock.address); expect(await this.mock.timelock()).to.be.equal(this.timelock.address);
}); });
describe('nominal', function () { it('nominal', async function () {
beforeEach(async function () { await this.helper.propose();
this.settings = { await this.helper.waitForSnapshot();
proposal: [ await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
[ this.receiver.address ], await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 });
[ web3.utils.toWei('0') ], await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter3 });
[ this.receiver.contract.methods.mockFunction().encodeABI() ], await this.helper.vote({ support: Enums.VoteType.Abstain }, { from: voter4 });
'<proposal description>', await this.helper.waitForDeadline();
], const txQueue = await this.helper.queue();
voters: [ await this.helper.waitForEta();
{ voter: voter, support: Enums.VoteType.For }, const txExecute = await this.helper.execute();
],
steps: { expectEvent(txQueue, 'ProposalQueued', { proposalId: this.proposal.id });
queue: { delay: 3600 }, 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');
}); });
afterEach(async function () {
const timelockid = await this.timelock.hashOperationBatch(
...this.settings.proposal.slice(0, 3),
'0x0',
this.descriptionHash,
);
expectEvent( describe('should revert', function () {
this.receipts.propose, describe('on queue', function () {
'ProposalCreated', it('if already queued', async function () {
{ proposalId: this.id }, await this.helper.propose();
); await this.helper.waitForSnapshot();
expectEvent( await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
this.receipts.queue, await this.helper.waitForDeadline();
'ProposalQueued', await this.helper.queue();
{ proposalId: this.id }, await expectRevert(this.helper.queue(), 'Governor: proposal not successful');
);
await expectEvent.inTransaction(
this.receipts.queue.transactionHash,
this.timelock,
'CallScheduled',
{ id: timelockid },
);
expectEvent(
this.receipts.execute,
'ProposalExecuted',
{ proposalId: this.id },
);
await expectEvent.inTransaction(
this.receipts.execute.transactionHash,
this.timelock,
'CallExecuted',
{ id: timelockid },
);
await expectEvent.inTransaction(
this.receipts.execute.transactionHash,
this.receiver,
'MockFunctionCalled',
);
}); });
runGovernorWorkflow();
}); });
describe('executed by other proposer', function () { describe('on execute', function () {
beforeEach(async function () { it('if not queued', async function () {
this.settings = { await this.helper.propose();
proposal: [ await this.helper.waitForSnapshot();
[ this.receiver.address ], await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
[ web3.utils.toWei('0') ], await this.helper.waitForDeadline(+1);
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
voters: [
{ voter: voter, support: Enums.VoteType.For },
],
steps: {
queue: { delay: 3600 },
execute: { enable: false },
},
};
});
afterEach(async function () {
await this.timelock.executeBatch(
...this.settings.proposal.slice(0, 3),
'0x0',
this.descriptionHash,
);
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Executed); expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Succeeded);
await expectRevert( await expectRevert(this.helper.execute(), 'TimelockController: operation is not ready');
this.mock.execute(...this.settings.proposal.slice(0, -1), this.descriptionHash),
'Governor: proposal not successful',
);
});
runGovernorWorkflow();
}); });
describe('not queued', function () { it('if too early', async function () {
beforeEach(async function () { await this.helper.propose();
this.settings = { await this.helper.waitForSnapshot();
proposal: [ await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
[ this.receiver.address ], await this.helper.waitForDeadline();
[ web3.utils.toWei('0') ], await this.helper.queue();
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
voters: [
{ voter: voter, support: Enums.VoteType.For },
],
steps: {
queue: { enable: false },
execute: { error: 'TimelockController: operation is not ready' },
},
};
});
afterEach(async function () {
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Succeeded);
});
runGovernorWorkflow();
});
describe('to early', function () { expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Queued);
beforeEach(async function () {
this.settings = { await expectRevert(this.helper.execute(), 'TimelockController: operation is not ready');
proposal: [
[ this.receiver.address ],
[ web3.utils.toWei('0') ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
voters: [
{ voter: voter, support: Enums.VoteType.For },
],
steps: {
execute: { error: 'TimelockController: operation is not ready' },
},
};
});
afterEach(async function () {
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Queued);
});
runGovernorWorkflow();
}); });
describe('re-queue / re-execute', function () { it('if already executed', async function () {
beforeEach(async function () { await this.helper.propose();
this.settings = { await this.helper.waitForSnapshot();
proposal: [ await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
[ this.receiver.address ], await this.helper.waitForDeadline();
[ web3.utils.toWei('0') ], await this.helper.queue();
[ this.receiver.contract.methods.mockFunction().encodeABI() ], await this.helper.waitForEta();
'<proposal description>', await this.helper.execute();
], await expectRevert(this.helper.execute(), 'Governor: proposal not successful');
voters: [
{ voter: voter, support: Enums.VoteType.For },
],
steps: {
queue: { delay: 3600 },
},
};
}); });
afterEach(async function () {
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Executed);
await expectRevert( it('if already executed by another proposer', async function () {
this.mock.queue(...this.settings.proposal.slice(0, -1), this.descriptionHash), await this.helper.propose();
'Governor: proposal not successful', await this.helper.waitForSnapshot();
); await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
await expectRevert( await this.helper.waitForDeadline();
this.mock.execute(...this.settings.proposal.slice(0, -1), this.descriptionHash), await this.helper.queue();
'Governor: proposal not successful', 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');
}); });
runGovernorWorkflow();
}); });
describe('cancel before queue prevents scheduling', function () {
beforeEach(async function () {
this.settings = {
proposal: [
[ this.receiver.address ],
[ web3.utils.toWei('0') ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
voters: [
{ voter: voter, support: Enums.VoteType.For },
],
steps: {
queue: { enable: false },
execute: { enable: false },
},
};
}); });
afterEach(async function () {
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Succeeded); 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( expectEvent(
await this.mock.cancel(...this.settings.proposal.slice(0, -1), this.descriptionHash), await this.helper.cancel(),
'ProposalCanceled', 'ProposalCanceled',
{ proposalId: this.id }, { proposalId: this.proposal.id },
); );
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled); expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled);
await expectRevert(this.helper.queue(), 'Governor: proposal not successful');
});
await expectRevert( it('cancel after queue prevents executing', async function () {
this.mock.queue(...this.settings.proposal.slice(0, -1), this.descriptionHash), await this.helper.propose();
'Governor: proposal not successful', 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(),
'ProposalCanceled',
{ proposalId: this.proposal.id },
); );
});
runGovernorWorkflow();
});
describe('cancel after queue prevents execution', function () { expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled);
beforeEach(async function () { await expectRevert(this.helper.execute(), 'Governor: proposal not successful');
this.settings = {
proposal: [
[ this.receiver.address ],
[ web3.utils.toWei('0') ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
voters: [
{ voter: voter, support: Enums.VoteType.For },
],
steps: {
queue: { delay: 3600 },
execute: { enable: false },
},
};
}); });
afterEach(async function () {
const timelockid = await this.timelock.hashOperationBatch(
...this.settings.proposal.slice(0, 3),
'0x0',
this.descriptionHash,
);
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Queued); 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);
const receipt = await this.mock.cancel(...this.settings.proposal.slice(0, -1), this.descriptionHash);
expectEvent( expectEvent(
receipt, await this.timelock.cancel(this.proposal.timelockid, { from: owner }),
'ProposalCanceled',
{ proposalId: this.id },
);
await expectEvent.inTransaction(
receipt.receipt.transactionHash,
this.timelock,
'Cancelled', 'Cancelled',
{ id: timelockid }, { id: this.proposal.timelockid },
); );
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled); expect(await this.mock.state(this.proposal.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled);
await expectRevert(
this.mock.execute(...this.settings.proposal.slice(0, -1), this.descriptionHash),
'Governor: proposal not successful',
);
}); });
runGovernorWorkflow();
}); });
describe('onlyGovernance', function () {
describe('relay', function () { describe('relay', function () {
beforeEach(async function () { beforeEach(async function () {
await this.token.mint(this.mock.address, 1); await this.token.mint(this.mock.address, 1);
this.call = [ });
it('is protected', async function () {
await expectRevert(
this.mock.relay(
this.token.address, this.token.address,
0, 0,
this.token.contract.methods.transfer(other, 1).encodeABI(), this.token.contract.methods.transfer(other, 1).encodeABI(),
]; ),
'Governor: onlyGovernance',
);
}); });
it('protected', async function () { it('can be executed through governance', async function () {
await expectRevert( this.helper.setProposal([
this.mock.relay(...this.call), {
'Governor: onlyGovernance', 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);
expectEvent.inTransaction(
txExecute.tx,
this.token,
'Transfer',
{ from: this.mock.address, to: other, value: '1' },
); );
}); });
...@@ -357,11 +297,11 @@ contract('GovernorTimelockControl', function (accounts) { ...@@ -357,11 +297,11 @@ contract('GovernorTimelockControl', function (accounts) {
await this.timelock.schedule( await this.timelock.schedule(
this.mock.address, this.mock.address,
web3.utils.toWei('0'), web3.utils.toWei('0'),
this.mock.contract.methods.relay(...this.call).encodeABI(), this.mock.contract.methods.relay(constants.ZERO_ADDRESS, 0, '0x').encodeABI(),
constants.ZERO_BYTES32, constants.ZERO_BYTES32,
constants.ZERO_BYTES32, constants.ZERO_BYTES32,
3600, 3600,
{ from: admin }, { from: owner },
); );
await time.increase(3600); await time.increase(3600);
...@@ -370,86 +310,14 @@ contract('GovernorTimelockControl', function (accounts) { ...@@ -370,86 +310,14 @@ contract('GovernorTimelockControl', function (accounts) {
this.timelock.execute( this.timelock.execute(
this.mock.address, this.mock.address,
web3.utils.toWei('0'), web3.utils.toWei('0'),
this.mock.contract.methods.relay(...this.call).encodeABI(), this.mock.contract.methods.relay(constants.ZERO_ADDRESS, 0, '0x').encodeABI(),
constants.ZERO_BYTES32, constants.ZERO_BYTES32,
constants.ZERO_BYTES32, constants.ZERO_BYTES32,
{ from: admin }, { from: owner },
), ),
'TimelockController: underlying transaction reverted', 'TimelockController: underlying transaction reverted',
); );
}); });
describe('using workflow', function () {
beforeEach(async function () {
this.settings = {
proposal: [
[
this.mock.address,
],
[
web3.utils.toWei('0'),
],
[
this.mock.contract.methods.relay(...this.call).encodeABI(),
],
'<proposal description>',
],
voters: [
{ voter: voter, support: Enums.VoteType.For },
],
steps: {
queue: { delay: 7 * 86400 },
},
};
expect(await this.token.balanceOf(this.mock.address), 1);
expect(await this.token.balanceOf(other), 0);
});
afterEach(async function () {
expect(await this.token.balanceOf(this.mock.address), 0);
expect(await this.token.balanceOf(other), 1);
});
runGovernorWorkflow();
});
});
describe('cancel on timelock is forwarded in state', function () {
beforeEach(async function () {
this.settings = {
proposal: [
[ this.receiver.address ],
[ web3.utils.toWei('0') ],
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
voters: [
{ voter: voter, support: Enums.VoteType.For },
],
steps: {
queue: { delay: 3600 },
execute: { enable: false },
},
};
});
afterEach(async function () {
const timelockid = await this.timelock.hashOperationBatch(
...this.settings.proposal.slice(0, 3),
'0x0',
this.descriptionHash,
);
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Queued);
const receipt = await this.timelock.cancel(timelockid, { from: admin });
expectEvent(
receipt,
'Cancelled',
{ id: timelockid },
);
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Canceled);
});
runGovernorWorkflow();
}); });
describe('updateTimelock', function () { describe('updateTimelock', function () {
...@@ -457,78 +325,58 @@ contract('GovernorTimelockControl', function (accounts) { ...@@ -457,78 +325,58 @@ contract('GovernorTimelockControl', function (accounts) {
this.newTimelock = await Timelock.new(3600, [], []); this.newTimelock = await Timelock.new(3600, [], []);
}); });
it('protected', async function () { it('is protected', async function () {
await expectRevert( await expectRevert(
this.mock.updateTimelock(this.newTimelock.address), this.mock.updateTimelock(this.newTimelock.address),
'Governor: onlyGovernance', 'Governor: onlyGovernance',
); );
}); });
describe('using workflow', function () { it('can be executed through governance to', async function () {
beforeEach(async function () { this.helper.setProposal([
this.settings = { {
proposal: [ target: this.mock.address,
[ this.mock.address ], data: this.mock.contract.methods.updateTimelock(this.newTimelock.address).encodeABI(),
[ web3.utils.toWei('0') ],
[ this.mock.contract.methods.updateTimelock(this.newTimelock.address).encodeABI() ],
'<proposal description>',
],
voters: [
{ voter: voter, support: Enums.VoteType.For },
],
steps: {
queue: { delay: 3600 },
}, },
}; ], '<proposal description>');
});
afterEach(async function () { await this.helper.propose();
expectEvent( await this.helper.waitForSnapshot();
this.receipts.propose, await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
'ProposalCreated', await this.helper.waitForDeadline();
{ proposalId: this.id }, await this.helper.queue();
); await this.helper.waitForEta();
expectEvent( const txExecute = await this.helper.execute();
this.receipts.execute,
'ProposalExecuted',
{ proposalId: this.id },
);
expectEvent( expectEvent(
this.receipts.execute, txExecute,
'TimelockChange', 'TimelockChange',
{ oldTimelock: this.timelock.address, newTimelock: this.newTimelock.address }, { oldTimelock: this.timelock.address, newTimelock: this.newTimelock.address },
); );
expect(await this.mock.timelock()).to.be.bignumber.equal(this.newTimelock.address); expect(await this.mock.timelock()).to.be.bignumber.equal(this.newTimelock.address);
}); });
runGovernorWorkflow();
}); });
}); });
describe('clear queue of pending governor calls', function () { it('clear queue of pending governor calls', async function () {
beforeEach(async function () { this.helper.setProposal([
this.settings = { {
proposal: [ target: this.mock.address,
[ this.mock.address ], data: this.mock.contract.methods.nonGovernanceFunction().encodeABI(),
[ web3.utils.toWei('0') ],
[ this.mock.contract.methods.nonGovernanceFunction().encodeABI() ],
'<proposal description>',
],
voters: [
{ voter: voter, support: Enums.VoteType.For },
],
steps: {
queue: { delay: 3600 },
}, },
}; ], '<proposal description>');
});
await this.helper.propose();
afterEach(async function () { await this.helper.waitForSnapshot();
expectEvent( await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
this.receipts.execute, await this.helper.waitForDeadline();
'ProposalExecuted', await this.helper.queue();
{ proposalId: this.id }, await this.helper.waitForEta();
); await this.helper.execute();
});
// This path clears _governanceCall as part of the afterExecute call,
runGovernorWorkflow(); // but we have not way to check that the cleanup actually happened other
// then coverage reports.
}); });
}); });
const { BN, expectEvent, time } = require('@openzeppelin/test-helpers'); const { BN, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const Enums = require('../../helpers/enums'); const Enums = require('../../helpers/enums');
const { GovernorHelper } = require('../../helpers/governance');
const {
runGovernorWorkflow,
} = require('./../GovernorWorkflow.behavior');
const Token = artifacts.require('ERC20VotesMock'); const Token = artifacts.require('ERC20VotesMock');
const Governor = artifacts.require('GovernorMock'); const Governor = artifacts.require('GovernorMock');
...@@ -19,24 +17,41 @@ contract('GovernorVotesQuorumFraction', function (accounts) { ...@@ -19,24 +17,41 @@ contract('GovernorVotesQuorumFraction', function (accounts) {
const tokenSupply = new BN(web3.utils.toWei('100')); const tokenSupply = new BN(web3.utils.toWei('100'));
const ratio = new BN(8); // percents const ratio = new BN(8); // percents
const newRatio = new BN(6); // percents const newRatio = new BN(6); // percents
const votingDelay = new BN(4);
const votingPeriod = new BN(16);
const value = web3.utils.toWei('1');
beforeEach(async function () { beforeEach(async function () {
this.owner = owner; this.owner = owner;
this.token = await Token.new(tokenName, tokenSymbol); this.token = await Token.new(tokenName, tokenSymbol);
this.mock = await Governor.new(name, this.token.address, 4, 16, ratio); this.mock = await Governor.new(name, this.token.address, votingDelay, votingPeriod, ratio);
this.receiver = await CallReceiver.new(); this.receiver = await CallReceiver.new();
this.helper = new GovernorHelper(this.mock);
await web3.eth.sendTransaction({ from: owner, to: this.mock.address, value });
await this.token.mint(owner, tokenSupply); await this.token.mint(owner, tokenSupply);
await this.token.delegate(voter1, { from: voter1 }); await this.helper.delegate({ token: this.token, to: voter1, value: web3.utils.toWei('10') }, { from: owner });
await this.token.delegate(voter2, { from: voter2 }); await this.helper.delegate({ token: this.token, to: voter2, value: web3.utils.toWei('7') }, { from: owner });
await this.token.delegate(voter3, { from: voter3 }); await this.helper.delegate({ token: this.token, to: voter3, value: web3.utils.toWei('5') }, { from: owner });
await this.token.delegate(voter4, { from: voter4 }); 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 () { it('deployment check', async function () {
expect(await this.mock.name()).to.be.equal(name); expect(await this.mock.name()).to.be.equal(name);
expect(await this.mock.token()).to.be.equal(this.token.address); expect(await this.mock.token()).to.be.equal(this.token.address);
expect(await this.mock.votingDelay()).to.be.bignumber.equal('4'); expect(await this.mock.votingDelay()).to.be.bignumber.equal(votingDelay);
expect(await this.mock.votingPeriod()).to.be.bignumber.equal('16'); 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.quorum(0)).to.be.bignumber.equal('0');
expect(await this.mock.quorumNumerator()).to.be.bignumber.equal(ratio); expect(await this.mock.quorumNumerator()).to.be.bignumber.equal(ratio);
expect(await this.mock.quorumDenominator()).to.be.bignumber.equal('100'); expect(await this.mock.quorumDenominator()).to.be.bignumber.equal('100');
...@@ -44,51 +59,47 @@ contract('GovernorVotesQuorumFraction', function (accounts) { ...@@ -44,51 +59,47 @@ contract('GovernorVotesQuorumFraction', function (accounts) {
.to.be.bignumber.equal(tokenSupply.mul(ratio).divn(100)); .to.be.bignumber.equal(tokenSupply.mul(ratio).divn(100));
}); });
describe('quroum not reached', function () { it('quroum reached', async function () {
beforeEach(async function () { await this.helper.propose();
this.settings = { await this.helper.waitForSnapshot();
proposal: [ await this.helper.vote({ support: Enums.VoteType.For }, { from: voter1 });
[ this.receiver.address ], await this.helper.waitForDeadline();
[ web3.utils.toWei('0') ], await this.helper.execute();
[ this.receiver.contract.methods.mockFunction().encodeABI() ],
'<proposal description>',
],
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('1'), support: Enums.VoteType.For },
],
steps: {
execute: { error: 'Governor: proposal not successful' },
},
};
}); });
runGovernorWorkflow();
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('update quorum ratio through proposal', function () { describe('onlyGovernance updates', function () {
beforeEach(async function () { it('updateQuorumNumerator is protected', async function () {
this.settings = { await expectRevert(
proposal: [ this.mock.updateQuorumNumerator(newRatio),
[ this.mock.address ], 'Governor: onlyGovernance',
[ web3.utils.toWei('0') ], );
[ this.mock.contract.methods.updateQuorumNumerator(newRatio).encodeABI() ],
'<proposal description>',
],
tokenHolder: owner,
voters: [
{ voter: voter1, weight: tokenSupply, support: Enums.VoteType.For },
],
};
}); });
afterEach(async function () {
await expectEvent.inTransaction( it('can updateQuorumNumerator through governance', async function () {
this.receipts.execute.transactionHash, this.helper.setProposal([
this.mock,
'QuorumNumeratorUpdated',
{ {
oldQuorumNumerator: ratio, target: this.mock.address,
newQuorumNumerator: newRatio, 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.quorumNumerator()).to.be.bignumber.equal(newRatio);
...@@ -96,27 +107,24 @@ contract('GovernorVotesQuorumFraction', function (accounts) { ...@@ -96,27 +107,24 @@ contract('GovernorVotesQuorumFraction', function (accounts) {
expect(await time.latestBlock().then(blockNumber => this.mock.quorum(blockNumber.subn(1)))) expect(await time.latestBlock().then(blockNumber => this.mock.quorum(blockNumber.subn(1))))
.to.be.bignumber.equal(tokenSupply.mul(newRatio).divn(100)); .to.be.bignumber.equal(tokenSupply.mul(newRatio).divn(100));
}); });
runGovernorWorkflow();
});
describe('update quorum over the maximum', function () { it('cannot updateQuorumNumerator over the maximum', async function () {
beforeEach(async function () { this.helper.setProposal([
this.settings = { {
proposal: [ target: this.mock.address,
[ this.mock.address ], data: this.mock.contract.methods.updateQuorumNumerator('101').encodeABI(),
[ web3.utils.toWei('0') ],
[ this.mock.contract.methods.updateQuorumNumerator(new BN(101)).encodeABI() ],
'<proposal description>',
],
tokenHolder: owner,
voters: [
{ voter: voter1, weight: tokenSupply, support: Enums.VoteType.For },
],
steps: {
execute: { error: 'GovernorVotesQuorumFraction: quorumNumerator over quorumDenominator' },
}, },
}; ], '<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',
);
}); });
runGovernorWorkflow();
}); });
}); });
const { BN, constants, expectEvent } = require('@openzeppelin/test-helpers'); const { BN, expectEvent } = require('@openzeppelin/test-helpers');
const { web3 } = require('@openzeppelin/test-helpers/src/setup'); const { expect } = require('chai');
const Enums = require('../../helpers/enums');
const ethSigUtil = require('eth-sig-util'); const ethSigUtil = require('eth-sig-util');
const Wallet = require('ethereumjs-wallet').default; const Wallet = require('ethereumjs-wallet').default;
const { EIP712Domain } = require('../../helpers/eip712');
const { fromRpcSig } = require('ethereumjs-util'); const { fromRpcSig } = require('ethereumjs-util');
const Enums = require('../../helpers/enums');
const { runGovernorWorkflow } = require('../GovernorWorkflow.behavior'); const { EIP712Domain } = require('../../helpers/eip712');
const { expect } = require('chai'); const { GovernorHelper } = require('../../helpers/governance');
const Token = artifacts.require('ERC20VotesCompMock'); const Token = artifacts.require('ERC20VotesCompMock');
const Governor = artifacts.require('GovernorWithParamsMock'); const Governor = artifacts.require('GovernorWithParamsMock');
const CallReceiver = artifacts.require('CallReceiverMock'); const CallReceiver = artifacts.require('CallReceiverMock');
const rawParams = {
uintParam: new BN('42'),
strParam: 'These are my params',
};
const encodedParams = web3.eth.abi.encodeParameters(
[ 'uint256', 'string' ],
Object.values(rawParams),
);
contract('GovernorWithParams', function (accounts) { contract('GovernorWithParams', function (accounts) {
const [owner, proposer, voter1, voter2, voter3, voter4] = accounts; const [ owner, proposer, voter1, voter2, voter3, voter4 ] = accounts;
const name = 'OZ-Governor'; const name = 'OZ-Governor';
const version = '1'; const version = '1';
...@@ -23,17 +31,32 @@ contract('GovernorWithParams', function (accounts) { ...@@ -23,17 +31,32 @@ contract('GovernorWithParams', function (accounts) {
const tokenSupply = web3.utils.toWei('100'); const tokenSupply = web3.utils.toWei('100');
const votingDelay = new BN(4); const votingDelay = new BN(4);
const votingPeriod = new BN(16); const votingPeriod = new BN(16);
const value = web3.utils.toWei('1');
beforeEach(async function () { beforeEach(async function () {
this.owner = owner; this.chainId = await web3.eth.getChainId();
this.token = await Token.new(tokenName, tokenSymbol); this.token = await Token.new(tokenName, tokenSymbol);
this.mock = await Governor.new(name, this.token.address); this.mock = await Governor.new(name, this.token.address);
this.receiver = await CallReceiver.new(); this.receiver = await CallReceiver.new();
this.helper = new GovernorHelper(this.mock);
await web3.eth.sendTransaction({ from: owner, to: this.mock.address, value });
await this.token.mint(owner, tokenSupply); await this.token.mint(owner, tokenSupply);
await this.token.delegate(voter1, { from: voter1 }); await this.helper.delegate({ token: this.token, to: voter1, value: web3.utils.toWei('10') }, { from: owner });
await this.token.delegate(voter2, { from: voter2 }); await this.helper.delegate({ token: this.token, to: voter2, value: web3.utils.toWei('7') }, { from: owner });
await this.token.delegate(voter3, { from: voter3 }); await this.helper.delegate({ token: this.token, to: voter3, value: web3.utils.toWei('5') }, { from: owner });
await this.token.delegate(voter4, { from: voter4 }); 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 () { it('deployment check', async function () {
...@@ -43,172 +66,57 @@ contract('GovernorWithParams', function (accounts) { ...@@ -43,172 +66,57 @@ contract('GovernorWithParams', function (accounts) {
expect(await this.mock.votingPeriod()).to.be.bignumber.equal(votingPeriod); expect(await this.mock.votingPeriod()).to.be.bignumber.equal(votingPeriod);
}); });
describe('nominal is unaffected', function () { it('nominal is unaffected', async function () {
beforeEach(async function () { await this.helper.propose({ from: proposer });
this.settings = { await this.helper.waitForSnapshot();
proposal: [ await this.helper.vote({ support: Enums.VoteType.For, reason: 'This is nice' }, { from: voter1 });
[this.receiver.address], await this.helper.vote({ support: Enums.VoteType.For }, { from: voter2 });
[0], await this.helper.vote({ support: Enums.VoteType.Against }, { from: voter3 });
[this.receiver.contract.methods.mockFunction().encodeABI()], await this.helper.vote({ support: Enums.VoteType.Abstain }, { from: voter4 });
'<proposal description>', await this.helper.waitForDeadline();
], await this.helper.execute();
proposer,
tokenHolder: owner, expect(await this.mock.hasVoted(this.proposal.id, owner)).to.be.equal(false);
voters: [ expect(await this.mock.hasVoted(this.proposal.id, voter1)).to.be.equal(true);
{ voter: voter1, weight: web3.utils.toWei('1'), support: Enums.VoteType.For, reason: 'This is nice' }, expect(await this.mock.hasVoted(this.proposal.id, voter2)).to.be.equal(true);
{ voter: voter2, weight: web3.utils.toWei('7'), support: Enums.VoteType.For }, expect(await web3.eth.getBalance(this.mock.address)).to.be.bignumber.equal('0');
{ voter: voter3, weight: web3.utils.toWei('5'), support: Enums.VoteType.Against }, expect(await web3.eth.getBalance(this.receiver.address)).to.be.bignumber.equal(value);
{ voter: voter4, weight: web3.utils.toWei('2'), support: Enums.VoteType.Abstain },
],
};
});
afterEach(async function () {
expect(await this.mock.hasVoted(this.id, owner)).to.be.equal(false);
expect(await this.mock.hasVoted(this.id, voter1)).to.be.equal(true);
expect(await this.mock.hasVoted(this.id, voter2)).to.be.equal(true);
await this.mock.proposalVotes(this.id).then((result) => {
for (const [key, value] of Object.entries(Enums.VoteType)) {
expect(result[`${key.toLowerCase()}Votes`]).to.be.bignumber.equal(
Object.values(this.settings.voters)
.filter(({ support }) => support === value)
.reduce((acc, { weight }) => acc.add(new BN(weight)), new BN('0')),
);
}
});
const startBlock = new BN(this.receipts.propose.blockNumber).add(votingDelay);
const endBlock = new BN(this.receipts.propose.blockNumber).add(votingDelay).add(votingPeriod);
expect(await this.mock.proposalSnapshot(this.id)).to.be.bignumber.equal(startBlock);
expect(await this.mock.proposalDeadline(this.id)).to.be.bignumber.equal(endBlock);
expectEvent(this.receipts.propose, 'ProposalCreated', {
proposalId: this.id,
proposer,
targets: this.settings.proposal[0],
// values: this.settings.proposal[1].map(value => new BN(value)),
signatures: this.settings.proposal[2].map(() => ''),
calldatas: this.settings.proposal[2],
startBlock,
endBlock,
description: this.settings.proposal[3],
});
this.receipts.castVote.filter(Boolean).forEach((vote) => {
const { voter } = vote.logs.filter(({ event }) => event === 'VoteCast').find(Boolean).args;
expectEvent(
vote,
'VoteCast',
this.settings.voters.find(({ address }) => address === voter),
);
});
expectEvent(this.receipts.execute, 'ProposalExecuted', { proposalId: this.id });
await expectEvent.inTransaction(this.receipts.execute.transactionHash, this.receiver, 'MockFunctionCalled');
});
runGovernorWorkflow();
});
describe('Voting with params is properly supported', function () {
const voter2Weight = web3.utils.toWei('1.0');
beforeEach(async function () {
this.settings = {
proposal: [
[this.receiver.address],
[0],
[this.receiver.contract.methods.mockFunction().encodeABI()],
'<proposal description>',
],
proposer,
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('0.2'), support: Enums.VoteType.Against },
{ voter: voter2, weight: voter2Weight }, // do not actually vote, only getting tokenss
],
steps: {
wait: { enable: false },
execute: { enable: false },
},
};
}); });
afterEach(async function () { it('Voting with params is properly supported', async function () {
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Active); await this.helper.propose({ from: proposer });
await this.helper.waitForSnapshot();
const uintParam = new BN(1);
const strParam = 'These are my params'; const weight = new BN(web3.utils.toWei('7')).sub(rawParams.uintParam);
const reducedWeight = new BN(voter2Weight).sub(uintParam);
const params = web3.eth.abi.encodeParameters(['uint256', 'string'], [uintParam, strParam]); const tx = await this.helper.vote({
const tx = await this.mock.castVoteWithReasonAndParams(this.id, Enums.VoteType.For, '', params, { from: voter2 }); support: Enums.VoteType.For,
reason: 'no particular reason',
expectEvent(tx, 'CountParams', { uintParam, strParam }); params: encodedParams,
expectEvent(tx, 'VoteCastWithParams', { voter: voter2, weight: reducedWeight, params }); }, { from: voter2 });
const votes = await this.mock.proposalVotes(this.id);
expect(votes.forVotes).to.be.bignumber.equal(reducedWeight); expectEvent(tx, 'CountParams', { ...rawParams });
expectEvent(tx, 'VoteCastWithParams', {
voter: voter2,
proposalId: this.proposal.id,
support: Enums.VoteType.For,
weight,
reason: 'no particular reason',
params: encodedParams,
}); });
runGovernorWorkflow();
});
describe('Voting with params by signature is properly supported', function () {
const voterBySig = Wallet.generate(); // generate voter by signature wallet
const sigVoterWeight = web3.utils.toWei('1.0');
beforeEach(async function () { const votes = await this.mock.proposalVotes(this.proposal.id);
this.chainId = await web3.eth.getChainId(); expect(votes.forVotes).to.be.bignumber.equal(weight);
this.voter = web3.utils.toChecksumAddress(voterBySig.getAddressString());
// use delegateBySig to enable vote delegation sig voting wallet
const { v, r, s } = fromRpcSig(
ethSigUtil.signTypedMessage(voterBySig.getPrivateKey(), {
data: {
types: {
EIP712Domain,
Delegation: [
{ name: 'delegatee', type: 'address' },
{ name: 'nonce', type: 'uint256' },
{ name: 'expiry', type: 'uint256' },
],
},
domain: { name: tokenName, version: '1', chainId: this.chainId, verifyingContract: this.token.address },
primaryType: 'Delegation',
message: { delegatee: this.voter, nonce: 0, expiry: constants.MAX_UINT256 },
},
}),
);
await this.token.delegateBySig(this.voter, 0, constants.MAX_UINT256, v, r, s);
this.settings = {
proposal: [
[this.receiver.address],
[0],
[this.receiver.contract.methods.mockFunction().encodeABI()],
'<proposal description>',
],
proposer,
tokenHolder: owner,
voters: [
{ voter: voter1, weight: web3.utils.toWei('0.2'), support: Enums.VoteType.Against },
{ voter: this.voter, weight: sigVoterWeight }, // do not actually vote, only getting tokens
],
steps: {
wait: { enable: false },
execute: { enable: false },
},
};
}); });
afterEach(async function () { it('Voting with params by signature is properly supported', async function () {
expect(await this.mock.state(this.id)).to.be.bignumber.equal(Enums.ProposalState.Active); const voterBySig = Wallet.generate();
const voterBySigAddress = web3.utils.toChecksumAddress(voterBySig.getAddressString());
const reason = 'This is my reason';
const uintParam = new BN(1);
const strParam = 'These are my params';
const reducedWeight = new BN(sigVoterWeight).sub(uintParam);
const params = web3.eth.abi.encodeParameters(['uint256', 'string'], [uintParam, strParam]);
// prepare signature for vote by signature const signature = async (message) => {
const { v, r, s } = fromRpcSig( return fromRpcSig(ethSigUtil.signTypedMessage(
ethSigUtil.signTypedMessage(voterBySig.getPrivateKey(), { voterBySig.getPrivateKey(),
{
data: { data: {
types: { types: {
EIP712Domain, EIP712Domain,
...@@ -221,18 +129,38 @@ contract('GovernorWithParams', function (accounts) { ...@@ -221,18 +129,38 @@ contract('GovernorWithParams', function (accounts) {
}, },
domain: { name, version, chainId: this.chainId, verifyingContract: this.mock.address }, domain: { name, version, chainId: this.chainId, verifyingContract: this.mock.address },
primaryType: 'ExtendedBallot', primaryType: 'ExtendedBallot',
message: { proposalId: this.id, support: Enums.VoteType.For, reason, params }, message,
}, },
}), },
); ));
};
await this.token.delegate(voterBySigAddress, { from: voter2 });
// Run proposal
await this.helper.propose();
await this.helper.waitForSnapshot();
const tx = await this.mock.castVoteWithReasonAndParamsBySig(this.id, Enums.VoteType.For, reason, params, v, r, s); const weight = new BN(web3.utils.toWei('7')).sub(rawParams.uintParam);
expectEvent(tx, 'CountParams', { uintParam, strParam }); const tx = await this.helper.vote({
expectEvent(tx, 'VoteCastWithParams', { voter: this.voter, weight: reducedWeight, params }); support: Enums.VoteType.For,
const votes = await this.mock.proposalVotes(this.id); reason: 'no particular reason',
expect(votes.forVotes).to.be.bignumber.equal(reducedWeight); params: encodedParams,
signature,
}); });
runGovernorWorkflow();
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);
}); });
}); });
const { time } = require('@openzeppelin/test-helpers');
function zip (...args) {
return Array(Math.max(...args.map(array => array.length)))
.fill()
.map((_, i) => args.map(array => array[i]));
}
function concatHex (...args) {
return web3.utils.bytesToHex([].concat(...args.map(h => web3.utils.hexToBytes(h || '0x'))));
}
function concatOpts (args, opts = null) {
return opts ? args.concat(opts) : args;
}
class GovernorHelper {
constructor (governor) {
this.governor = governor;
}
delegate (delegation = {}, opts = null) {
return Promise.all([
delegation.token.delegate(delegation.to, { from: delegation.to }),
delegation.value &&
delegation.token.transfer(...concatOpts([ delegation.to, delegation.value ]), opts),
delegation.tokenId &&
delegation.token.ownerOf(delegation.tokenId).then(owner =>
delegation.token.transferFrom(...concatOpts([ owner, delegation.to, delegation.tokenId ], opts)),
),
]);
}
propose (opts = null) {
const proposal = this.currentProposal;
return this.governor.methods[
proposal.useCompatibilityInterface
? 'propose(address[],uint256[],string[],bytes[],string)'
: 'propose(address[],uint256[],bytes[],string)'
](...concatOpts(proposal.fullProposal, opts));
}
queue (opts = null) {
const proposal = this.currentProposal;
return proposal.useCompatibilityInterface
? this.governor.methods['queue(uint256)'](...concatOpts(
[ proposal.id ],
opts,
))
: this.governor.methods['queue(address[],uint256[],bytes[],bytes32)'](...concatOpts(
proposal.shortProposal,
opts,
));
}
execute (opts = null) {
const proposal = this.currentProposal;
return proposal.useCompatibilityInterface
? this.governor.methods['execute(uint256)'](...concatOpts(
[ proposal.id ],
opts,
))
: this.governor.methods['execute(address[],uint256[],bytes[],bytes32)'](...concatOpts(
proposal.shortProposal,
opts,
));
}
cancel (opts = null) {
const proposal = this.currentProposal;
return proposal.useCompatibilityInterface
? this.governor.methods['cancel(uint256)'](...concatOpts(
[ proposal.id ],
opts,
))
: this.governor.methods['cancel(address[],uint256[],bytes[],bytes32)'](...concatOpts(
proposal.shortProposal,
opts,
));
}
vote (vote = {}, opts = null) {
const proposal = this.currentProposal;
return vote.signature
// if signature, and either params or reason →
? vote.params || vote.reason
? vote.signature({
proposalId: proposal.id,
support: vote.support,
reason: vote.reason || '',
params: vote.params || '',
}).then(({ v, r, s }) => this.governor.castVoteWithReasonAndParamsBySig(...concatOpts(
[ proposal.id, vote.support, vote.reason || '', vote.params || '', v, r, s ],
opts,
)))
: vote.signature({
proposalId: proposal.id,
support: vote.support,
}).then(({ v, r, s }) => this.governor.castVoteBySig(...concatOpts(
[ proposal.id, vote.support, v, r, s ],
opts,
)))
: vote.params
// otherwize if params
? this.governor.castVoteWithReasonAndParams(...concatOpts(
[ proposal.id, vote.support, vote.reason || '', vote.params ],
opts,
))
: vote.reason
// otherwize if reason
? this.governor.castVoteWithReason(...concatOpts(
[ proposal.id, vote.support, vote.reason ],
opts,
))
: this.governor.castVote(...concatOpts(
[ proposal.id, vote.support ],
opts,
));
}
waitForSnapshot (offset = 0) {
const proposal = this.currentProposal;
return this.governor.proposalSnapshot(proposal.id)
.then(blockNumber => time.advanceBlockTo(blockNumber.addn(offset)));
}
waitForDeadline (offset = 0) {
const proposal = this.currentProposal;
return this.governor.proposalDeadline(proposal.id)
.then(blockNumber => time.advanceBlockTo(blockNumber.addn(offset)));
}
waitForEta (offset = 0) {
const proposal = this.currentProposal;
return this.governor.proposalEta(proposal.id)
.then(timestamp => time.increaseTo(timestamp.addn(offset)));
}
/**
* Specify a proposal either as
* 1) an array of objects [{ target, value, data, signature? }]
* 2) an object of arrays { targets: [], values: [], data: [], signatures?: [] }
*/
setProposal (actions, description) {
let targets, values, signatures, data, useCompatibilityInterface;
if (Array.isArray(actions)) {
useCompatibilityInterface = actions.some(a => 'signature' in a);
targets = actions.map(a => a.target);
values = actions.map(a => a.value || '0');
signatures = actions.map(a => a.signature || '');
data = actions.map(a => a.data || '0x');
} else {
useCompatibilityInterface = Array.isArray(actions.signatures);
({ targets, values, signatures = [], data } = actions);
}
const fulldata = zip(signatures.map(s => s && web3.eth.abi.encodeFunctionSignature(s)), data)
.map(hexs => concatHex(...hexs));
const descriptionHash = web3.utils.keccak256(description);
// condensed version for queing end executing
const shortProposal = [
targets,
values,
fulldata,
descriptionHash,
];
// full version for proposing
const fullProposal = [
targets,
values,
...(useCompatibilityInterface ? [ signatures ] : []),
data,
description,
];
// proposal id
const id = web3.utils.toBN(web3.utils.keccak256(web3.eth.abi.encodeParameters(
[ 'address[]', 'uint256[]', 'bytes[]', 'bytes32' ],
shortProposal,
)));
this.currentProposal = {
id,
targets,
values,
signatures,
data,
fulldata,
description,
descriptionHash,
shortProposal,
fullProposal,
useCompatibilityInterface,
};
return this.currentProposal;
}
}
module.exports = {
GovernorHelper,
};
...@@ -112,35 +112,34 @@ for (const k of Object.getOwnPropertyNames(INTERFACES)) { ...@@ -112,35 +112,34 @@ for (const k of Object.getOwnPropertyNames(INTERFACES)) {
} }
function shouldSupportInterfaces (interfaces = []) { function shouldSupportInterfaces (interfaces = []) {
describe('Contract interface', function () { describe('ERC165', function () {
beforeEach(function () { beforeEach(function () {
this.contractUnderTest = this.mock || this.token || this.holder || this.accessControl; this.contractUnderTest = this.mock || this.token || this.holder || this.accessControl;
}); });
it('supportsInterface uses less than 30k gas', async function () {
for (const k of interfaces) { for (const k of interfaces) {
const interfaceId = INTERFACE_IDS[k]; const interfaceId = INTERFACE_IDS[k];
describe(k, function () {
describe('ERC165\'s supportsInterface(bytes4)', function () {
it('uses less than 30k gas', async function () {
expect(await this.contractUnderTest.supportsInterface.estimateGas(interfaceId)).to.be.lte(30000); expect(await this.contractUnderTest.supportsInterface.estimateGas(interfaceId)).to.be.lte(30000);
}
}); });
it('claims support', async function () { it('all interfaces are reported as supported', async function () {
for (const k of interfaces) {
const interfaceId = INTERFACE_IDS[k];
expect(await this.contractUnderTest.supportsInterface(interfaceId)).to.equal(true); expect(await this.contractUnderTest.supportsInterface(interfaceId)).to.equal(true);
}); }
}); });
it('all interface functions are in ABI', async function () {
for (const k of interfaces) {
for (const fnName of INTERFACES[k]) { for (const fnName of INTERFACES[k]) {
const fnSig = FN_SIGNATURES[fnName]; const fnSig = FN_SIGNATURES[fnName];
describe(fnName, function () {
it('has to be implemented', function () {
expect(this.contractUnderTest.abi.filter(fn => fn.signature === fnSig).length).to.equal(1); expect(this.contractUnderTest.abi.filter(fn => fn.signature === fnSig).length).to.equal(1);
});
});
} }
});
} }
}); });
});
} }
module.exports = { module.exports = {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment