Sub topic 8
Delegation and Vote Checkpoints in Code
This chapter assumes you can read short Solidity snippets, know what an ERC-20 balance mapping is, and have seen the proposal and voting flow from the previous chapter. Here you will see how a governance token turns balances into voting power, and why the contract needs delegation and checkpoints to do it safely.
Why a plain balance is not enough
A basic ERC-20 stores one number per address: the current balance. A governance system needs more than that. Two problems appear immediately.
- Voting power must be fixed at a point in the past. Suppose a proposal opens for voting and your balance is read live. You could vote, send your tokens to a second wallet, and vote again. Anyone could also borrow tokens for one transaction (a flash loan), vote, and return them. The system needs to ask, "What was this address's balance at the moment the proposal was created?"
- Reading history is expensive. Looping over every past transfer to answer that question would cost too much gas, so the contract must record history in a form that can be searched quickly.
OpenZeppelin's ERC20Votes solves both problems with two ideas: delegation and checkpoints.
Delegation: balance is not voting power
In ERC20Votes, owning tokens does not give you votes. Your tokens count as votes only for the address you have delegated to. Delegation never moves tokens. It only moves the voting weight attached to them.
Three details matter:
- Delegation is opt-in. A new holder has no voting power until they call
delegate(). Tokens held by an address that never delegated are not counted toward quorum or any vote. This is a deliberate gas saving, because tracking votes for every transfer of undelegated tokens would cost more. It is also a common cause of low participation. - You can delegate to yourself. Calling
delegate(msg.sender)activates your own voting power. - Delegation is one-to-one at a time. Each address has exactly one delegate. Calling
delegate()again replaces the previous choice and moves the whole balance's weight to the new delegate.
Here is the governance token from the Topic Spine again:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
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() ERC20("Gov Token", "GOV") ERC20Permit("Gov Token") {
_mint(msg.sender, 1_000_000 * 10 ** decimals());
}
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 two overrides exist because several parent contracts define _update and nonces. Solidity requires you to name every parent that you are overriding and to resolve the conflict explicitly. The _update override is the important one. Every mint, burn, and transfer passes through _update, and ERC20Votes hooks into it to move voting weight and write checkpoints.
ERC20Permit is included because many governance tokens support gasless approvals. It is not required for voting. ERC20Votes also needs it only in the sense that the standard pairing includes delegateBySig, which lets a holder sign a delegation message off-chain so someone else can submit it.
Checkpoints: a history you can search
A checkpoint is a record of the form "from this point on, this account has this many votes". ERC20Votes keeps one list of checkpoints per delegate, and it adds a new entry whenever that delegate's voting power changes. A change happens when:
- a holder delegates to them or away from them,
- a holder who has delegated to them receives or sends tokens,
- tokens are minted or burned for such a holder.
Each checkpoint stores a point in time and the voting power from then on. In OpenZeppelin v5 the clock defaults to block numbers, and you can switch it to timestamps by overriding clock() and CLOCK_MODE(). Chains with unpredictable block times, such as some layer 2 networks, often use timestamps.
Two properties make this design work:
- Writes are cheap. If power changes more than once in the same block, the contract overwrites the latest checkpoint instead of adding a new one.
- Reads are fast. The list is ordered by time, so
getPastVotes(account, timepoint)uses a binary search. It takes about log₂(n) steps for n checkpoints, not n steps.
Reading votes from a contract
The token exposes several view functions. The governor contract and front ends use them.
| Function | Returns |
|---|---|
| `balanceOf(account)` | Tokens owned, regardless of delegation |
| `delegates(account)` | The address that `account` has delegated to (zero address if none) |
| `getVotes(account)` | Current voting power of `account` as a delegate |
| `getPastVotes(account, timepoint)` | Voting power at a past timepoint, which must be earlier than the current one |
| `getPastTotalSupply(timepoint)` | Total supply at a past timepoint, used for quorum |
| `numCheckpoints(account)` | Number of checkpoints stored for `account` |
A short Foundry test shows the whole flow, including the common mistake of forgetting to delegate:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {Test} from "forge-std/Test.sol";
import {GovToken} from "../src/GovToken.sol";
contract GovTokenTest is Test {
GovToken token;
address alice = address(0xA11CE);
address bob = address(0xB0B);
function setUp() public {
token = new GovToken();
token.transfer(alice, 1_000 ether);
}
function testBalanceIsNotVotingPower() public {
assertEq(token.balanceOf(alice), 1_000 ether);
assertEq(token.getVotes(alice), 0);
}
function testDelegationAndSnapshot() public {
vm.roll(10);
vm.prank(alice);
token.delegate(alice);
vm.roll(20);
assertEq(token.getVotes(alice), 1_000 ether);
assertEq(token.getPastVotes(alice, 15), 1_000 ether);
assertEq(token.getPastVotes(alice, 5), 0);
vm.prank(alice);
token.transfer(bob, 400 ether);
vm.roll(30);
assertEq(token.getVotes(alice), 600 ether);
assertEq(token.getPastVotes(alice, 15), 1_000 ether);
}
}The last assertion is the point of checkpoints. After Alice sends tokens away, her vote total at block 15 is still 1,000, because history does not change.
How a governor uses checkpoints
When someone creates a proposal, the governor records a snapshot timepoint. The proposal's voting delay is the gap between creation and the snapshot, and it gives holders time to delegate or buy tokens before the snapshot is taken. When a vote is cast, the governor calls getPastVotes(voter, snapshot). Quorum is checked against getPastTotalSupply(snapshot).
This closes the double-voting and flash-loan holes from the start of the chapter. Tokens acquired after the snapshot add nothing to that proposal. Tokens sent away after the snapshot do not remove anything.
Common errors and edge cases
- Forgetting to delegate. The most common mistake. A holder with a large balance and no delegation has zero votes. Many interfaces prompt for self-delegation on first use. Consider whether your deployment should delegate the initial mint to the deployer or a treasury address.
- Delegating after the snapshot. Delegation made after the proposal snapshot does not count for that proposal. Tell holders to delegate before proposals appear.
- Tokens held in exchanges or contracts. Tokens held by a centralized exchange or a contract that never calls
delegate()carry no votes. Tokens in a liquidity pool are in the same position, so a large share of supply can sit outside governance. - Supply cap.
ERC20Voteslimits total supply to the maximum of a 208-bit unsigned integer, because checkpoint values are packed into a compact struct. This is far above any realistic supply, but a token with extreme decimals or minting can reach it, and_updatereverts when it does. - Wrapped or rebasing tokens. Checkpoints record balances at transfer events. A token whose balances change without transfers, such as a rebasing token, does not fit this model without a wrapper such as
ERC20Wrapper. - Delegate concentration. Delegation lets many small holders pool their weight under a few addresses. This helps participation but concentrates influence, which links to the risks in the next chapter.
Delegation is not custody
A delegate cannot spend your tokens. They can only vote with the weight. You can redelegate at any time, including during a live proposal, though your change affects only proposals whose snapshot comes after it. Delegation is a trust decision about how someone will vote, not about who holds your funds.
Exercise
Alice holds 1,000 GOV and has never called delegate(). A proposal is created at block 100 with a snapshot at block 101. At block 120 Alice calls delegate(alice) and votes. How many votes does she cast on that proposal, and why?
Show answer
Zero. Voting power for the proposal is read with getPastVotes(alice, 101). At block 101 Alice had no delegation, so her checkpointed votes were 0. Delegating at block 120 creates a checkpoint at block 120, which does not change the value at block 101. She needed to delegate before the snapshot.
Exercise
Why does ERC20Votes use a binary search over checkpoints in getPastVotes instead of looping through all of them, and what property of the checkpoint list makes this possible?
Show answer
A loop would cost gas proportional to the number of checkpoints, which grows with every power change. Checkpoints are appended in increasing time order, so the list is sorted by timepoint. A sorted list allows binary search, which finds the right entry in about log2(n) steps.