On-chain DAO governance uses a Governor contract to run votes and a timelock contract to carry out the result. A proposal is a list of contract calls (targets, values and calldata). Token holders vote with voting power checkpointed at a snapshot, so tokens bought or borrowed after the proposal was created don't count. If the proposal reaches quorum and more votes are for than against, it is queued in the timelock, waits out a fixed delay, and then anyone can execute it. The timelock, not the Governor, holds the treasury and admin roles, and the delay gives users time to exit before a change takes effect.
The design most DAOs on Ethereum and other EVM chains use today descends from Compound's GovernorAlpha and GovernorBravo and is standardised in OpenZeppelin's Governor. This guide walks through the lifecycle, the contracts, and the mistakes that let attackers take over DAOs.
What are the moving parts?
| Contract | Role |
|---|---|
Votes token (ERC20Votes or ERC721Votes) | Tracks delegated voting power with historical checkpoints |
| Governor | Accepts proposals, counts votes, enforces quorum and thresholds |
| TimelockController | Holds funds and permissions, executes approved calls after a delay |
| Protocol contracts | Owned by the timelock: proxies, parameter setters, treasury |
The split matters. The Governor decides whether something happens; the timelock is the only address that can make it happen. If your protocol's owner() or DEFAULT_ADMIN_ROLE is still a deployer EOA, the DAO is decorative.
How does a proposal move through its lifecycle?
OpenZeppelin's IGovernor.ProposalState enum has eight states: Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed. The normal path looks like this:
- Propose. An account with at least
proposalThreshold()votes callspropose(targets, values, calldatas, description). The proposal ID ishashProposal(targets, values, calldatas, keccak256(description)), so the same calls with the same description always produce the same ID. - Pending. For
votingDelay()the proposal exists but nobody can vote. The snapshot is set to the creation time plus this delay. - Active. For
votingPeriod()holders callcastVote(proposalId, support)with0= Against,1= For,2= Abstain. Weight istoken.getPastVotes(voter, snapshot). - Succeeded or Defeated. With
GovernorCountingSimple, a proposal succeeds when For + Abstain meets quorum and For is strictly greater than Against. - Queued. Anyone calls
queue(...), which schedules the batch in the timelock. The clock forminDelaystarts. - Executed. After the delay, anyone calls
execute(...)and the timelock makes each call in order.
Because voting power is read at a past checkpoint, a flash loan taken during the vote gives zero votes. That is the specific defence missing from Beanstalk in April 2022: its governance counted current balances and allowed immediate execution, so an attacker borrowed enough tokens to pass a proposal and drain the protocol in one transaction. For the general pattern, see how flash loan attacks borrow capital for one transaction.
Why do I have to delegate my tokens before I can vote?
ERC20Votes only tracks voting power for delegates. Holding tokens is not enough: an account has zero votes until it calls delegate(self) or delegates to someone else. This keeps transfers cheap, because checkpoints are only written for accounts with delegated power, but it surprises almost every new DAO. Your frontend should prompt users to self-delegate, and your tests should do it explicitly.
A minimal votes token with OpenZeppelin Contracts v5:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";
import {ERC20Votes} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol";
import {Nonces} from "@openzeppelin/contracts/utils/Nonces.sol";
contract GovToken is ERC20, ERC20Permit, ERC20Votes {
constructor(address treasury) ERC20("Gov", "GOV") ERC20Permit("Gov") {
_mint(treasury, 10_000_000e18);
}
// Use timestamps instead of block numbers (ERC-6372).
function clock() public view override returns (uint48) {
return uint48(block.timestamp);
}
function CLOCK_MODE() public pure override returns (string memory) {
return "mode=timestamp";
}
function _update(address from, address to, uint256 value)
internal override(ERC20, ERC20Votes)
{
super._update(from, to, value);
}
function nonces(address owner)
public view override(ERC20Permit, Nonces) returns (uint256)
{
return super.nonces(owner);
}
}
The clock() override is worth making on L2s, where block numbers don't tick at a predictable rate (on Arbitrum, block.number even returns an approximate L1 block number). With timestamp mode, votingDelay and votingPeriod are measured in seconds. If you start from a standard OpenZeppelin ERC-20, adding ERC20Votes later changes storage, so decide before deployment.
How do I deploy a Governor with a timelock?
The Governor is assembled from extensions:
contract MyGovernor is
Governor,
GovernorSettings,
GovernorCountingSimple,
GovernorVotes,
GovernorVotesQuorumFraction,
GovernorTimelockControl
{
constructor(IVotes token, TimelockController timelock)
Governor("MyGovernor")
GovernorSettings(
1 days, // votingDelay (seconds, because the token uses timestamps)
7 days, // votingPeriod
100_000e18 // proposalThreshold
)
GovernorVotes(token)
GovernorVotesQuorumFraction(4) // 4% of total supply at the snapshot
GovernorTimelockControl(timelock)
{}
// Plus the override functions Solidity requires for diamond inheritance
// (votingDelay, votingPeriod, quorum, state, proposalNeedsQueuing,
// proposalThreshold, _queueOperations, _executeOperations, _cancel,
// _executor). The OpenZeppelin Contracts Wizard generates them.
}
Then wire the timelock:
address[] memory none = new address[](0);
address[] memory anyone = new address[](1); // address(0) = anyone may execute
TimelockController timelock = new TimelockController(2 days, none, anyone, address(this));
MyGovernor governor = new MyGovernor(token, timelock);
timelock.grantRole(timelock.PROPOSER_ROLE(), address(governor));
timelock.grantRole(timelock.CANCELLER_ROLE(), address(governor));
timelock.renounceRole(timelock.DEFAULT_ADMIN_ROLE(), address(this));
protocol.transferOwnership(address(timelock));
Three details decide whether this is secure. The Governor must be the only proposer: any other PROPOSER_ROLE holder can schedule calls without a vote. The deployer must renounce the admin role, otherwise it can grant itself proposer later. And funds and ownership must sit in the timelock: with GovernorTimelockControl the executor is the timelock, so ETH or tokens sent to the Governor address are not reachable by proposals.
Upgrades follow the same rule. If your protocol uses UUPS or Transparent proxies, the timelock should own the ProxyAdmin or hold the upgrade role, so an upgrade is itself a proposal with a public delay.
Creating, voting on and executing a proposal
With ethers v6, a proposal that pays a grant from the treasury looks like this:
import { ethers } from "ethers";
const description = "Grant 50,000 GOV to the audit fund";
const calldata = token.interface.encodeFunctionData("transfer", [auditFund, ethers.parseUnits("50000", 18)]);
const targets = [await token.getAddress()];
const values = [0n];
const calldatas = [calldata];
const descriptionHash = ethers.id(description);
await (await governor.propose(targets, values, calldatas, description)).wait();
const proposalId = await governor.hashProposal(targets, values, calldatas, descriptionHash);
// after votingDelay
await (await governor.castVoteWithReason(proposalId, 1, "Audit before v2 launch")).wait();
// after votingPeriod, if Succeeded
await (await governor.queue(targets, values, calldatas, descriptionHash)).wait();
// after the timelock's minDelay
await (await governor.execute(targets, values, calldatas, descriptionHash)).wait();
queue and execute take the description hash, not the text, and must receive byte-identical arrays. Store the exact description string with the proposal or you can't execute it. If any call in the batch reverts, the whole execution reverts and the proposal stays queued; read how to decode "execution reverted" to find which target failed. If you need more contract-call patterns, the guide to reading contracts and sending transactions with ethers.js v6 covers them.
OpenZeppelin also lets a proposer append #proposer=0xTheirAddress to the description, which makes the Governor reject the same description from anyone else. That stops someone front-running propose to grab a proposal ID.
How do DAOs get attacked anyway?
Checkpointed votes and a timelock stop the crude attacks. The ones that still work target the humans and the parameters:
- Malicious payloads. In May 2023 an attacker passed a Tornado Cash governance proposal that looked like an earlier, harmless one, then used
CREATE2andSELFDESTRUCTto swap the target contract's code after the vote and grant themselves voting power. EIP-6780 (Dencun) has since restrictedSELFDESTRUCT, but the lesson stands: voters must review the exact bytecode and calldata being executed, not the description. - Low turnout. A 4% quorum on a token where 3% is regularly voted is easy to capture with bought tokens during the voting delay. Watch for unusual delegation right before a snapshot.
- Short delays. A one-day voting period and a one-hour timelock give nobody time to react. Users need long enough after
Queuedto withdraw. - Off-chain voting gaps. Many DAOs vote off-chain with signed messages (for example on Snapshot) and rely on a multisig to execute. That is cheaper but trusts the signers; the multisig is then the real governance.
Many DAOs add a guardian or security council that can cancel queued proposals in an emergency, usually a Safe multisig holding the canceller role. It should be able to stop things, never to start them.
What should I test before launch?
Governance code is small, but the configuration is where DAOs fail. In Foundry, test the full path with vm.warp: delegate, propose, warp past the delay, vote, warp past the period, queue, warp past minDelay, execute. Then assert the negatives: a non-delegated holder has zero votes, tokens transferred after the snapshot don't change the result, the deployer has no remaining roles, and execute before minDelay reverts with TimelockUnexpectedOperationState. Fuzz and invariant tests can check that no sequence of calls lets a non-proposer schedule operations. Include role assignments and parameter choices in the scope of any smart contract audit.
Checklist
- Votes token uses
ERC20Voteswith checkpoints; holders are told to self-delegate. - Use
mode=timestampon chains where block numbers are irregular. - Voting delay, voting period, threshold and quorum are set for your real turnout, not defaults.
- The Governor is the timelock's only proposer; executor is
address(0)or a known set. - The deployer has renounced
DEFAULT_ADMIN_ROLEon the timelock. - The timelock owns the treasury, the protocol contracts and the proxy admin.
- The timelock delay is long enough for users to exit before changes land.
- Any guardian can cancel but cannot propose or execute.
- Store each proposal's exact description;
queueandexecuteneed its hash. - Test the full lifecycle and the failure cases on a fork before handing over control.
Get the weekly commit
New blockchain deep dives every week.