Governance

This document is better viewed at https://docs.openzeppelin.com/contracts/api/governance

This directory includes primitives for on-chain governance.

Governor

This modular system of Governor contracts allows the deployment on-chain voting protocols similar to Compound’s Governor Alpha & Bravo and beyond, through the ability to easily customize multiple aspects of the protocol.

For a guided experience, set up your Governor contract using Contracts Wizard.

For a written walkthrough, check out our guide on How to set up on-chain governance.

  • Governor: The core contract that contains all the logic and primitives. It is abstract and requires choosing one of each of the modules below, or custom ones.

Votes modules determine the source of voting power, and sometimes quorum number.

Counting modules determine valid voting options.

Timelock extensions add a delay for governance decisions to be executed. The workflow is extended to require a queue step before execution. With these modules, proposals are executed by the external timelock contract, thus it is the timelock that has to hold the assets that are being governed.

Other extensions can customize the behavior or interface in multiple ways.

  • GovernorCompatibilityBravo: Extends the interface to be fully GovernorBravo-compatible. Note that events are compatible regardless of whether this extension is included or not.

  • GovernorSettings: Manages some of the settings (voting delay, voting period duration, and proposal threshold) in a way that can be updated through a governance proposal, without requiring an upgrade.

  • GovernorPreventLateQuorum: Ensures there is a minimum voting period after quorum is reached as a security protection against large voters.

In addition to modules and extensions, the core contract requires a few virtual functions to be implemented to your particular specifications:

  • votingDelay(): Delay (in EIP-6372 clock) since the proposal is submitted until voting power is fixed and voting starts. This can be used to enforce a delay after a proposal is published for users to buy tokens, or delegate their votes.

  • votingPeriod(): Delay (in EIP-6372 clock) since the proposal starts until voting ends.

  • quorum(uint256 timepoint): Quorum required for a proposal to be successful. This function includes a timepoint argument (see EIP-6372) so the quorum can adapt through time, for example, to follow a token’s totalSupply.

Functions of the Governor contract do not include access control. If you want to restrict access, you should add these checks by overloading the particular functions. Among these, Governor._cancel is internal by default, and you will have to expose it (with the right access control mechanism) yourself if this function is needed.

Core

IGovernor

import "@openzeppelin/contracts/governance/IGovernor.sol";

Interface of the Governor core.

Available since v4.3.

name() → string public

Name of the governor instance (used in building the ERC712 domain separator).

version() → string public

Version of the governor instance (used in building the ERC712 domain separator). Default: "1"

clock() → uint48 public

See IERC6372

CLOCK_MODE() → string public

See EIP-6372.

COUNTING_MODE() → string public

A description of the possible support values for castVote and the way these votes are counted, meant to be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of key-value pairs that each describe one aspect, for example support=bravo&quorum=for,abstain.

There are 2 standard keys: support and quorum.

  • support=bravo refers to the vote options 0 = Against, 1 = For, 2 = Abstain, as in GovernorBravo.

  • quorum=bravo means that only For votes are counted towards quorum.

  • quorum=for,abstain means that both For and Abstain votes are counted towards quorum.

If a counting module makes use of encoded params, it should include this under a params key with a unique name that describes the behavior. For example:

  • params=fractional might refer to a scheme where votes are divided fractionally between for/against/abstain.

  • params=erc721 might refer to a scheme where specific NFTs are delegated to vote.

The string can be decoded by the standard URLSearchParams JavaScript class.

hashProposal(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) → uint256 public

Hashing function used to (re)build the proposal id from the proposal details..

state(uint256 proposalId) → enum IGovernor.ProposalState public

Current state of a proposal, following Compound’s convention

proposalSnapshot(uint256 proposalId) → uint256 public

Timepoint used to retrieve user’s votes and quorum. If using block number (as per Compound’s Comp), the snapshot is performed at the end of this block. Hence, voting for this proposal starts at the beginning of the following block.

proposalDeadline(uint256 proposalId) → uint256 public

Timepoint at which votes close. If using block number, votes close at the end of this block, so it is possible to cast a vote during this block.

proposalProposer(uint256 proposalId) → address public

The account that created a proposal.

votingDelay() → uint256 public

Delay, between the proposal is created and the vote starts. The unit this duration is expressed in depends on the clock (see EIP-6372) this contract uses.

This can be increased to leave time for users to buy voting power, or delegate it, before the voting of a proposal starts.

votingPeriod() → uint256 public

Delay between the vote start and vote end. The unit this duration is expressed in depends on the clock (see EIP-6372) this contract uses.

The votingDelay can delay the start of the vote. This must be considered when setting the voting duration compared to the voting delay.

quorum(uint256 timepoint) → uint256 public

Minimum number of cast voted required for a proposal to be successful.

The timepoint parameter corresponds to the snapshot used for counting vote. This allows to scale the quorum depending on values such as the totalSupply of a token at this timepoint (see ERC20Votes).

getVotes(address account, uint256 timepoint) → uint256 public

Voting power of an account at a specific timepoint.

Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or multiple), ERC20Votes tokens.

getVotesWithParams(address account, uint256 timepoint, bytes params) → uint256 public

Voting power of an account at a specific timepoint given additional encoded parameters.

hasVoted(uint256 proposalId, address account) → bool public

Returns whether account has cast a vote on proposalId.

propose(address[] targets, uint256[] values, bytes[] calldatas, string description) → uint256 proposalId public

Create a new proposal. Vote start after a delay specified by IGovernor.votingDelay and lasts for a duration specified by IGovernor.votingPeriod.

Emits a ProposalCreated event.

execute(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) → uint256 proposalId public

Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the deadline to be reached.

Emits a ProposalExecuted event.

Note: some module can modify the requirements for execution, for example by adding an additional timelock.

cancel(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) → uint256 proposalId public

Cancel a proposal. A proposal is cancellable by the proposer, but only while it is Pending state, i.e. before the vote starts.

Emits a ProposalCanceled event.

castVote(uint256 proposalId, uint8 support) → uint256 balance public

Cast a vote

Emits a VoteCast event.

castVoteWithReason(uint256 proposalId, uint8 support, string reason) → uint256 balance public

Cast a vote with a reason

Emits a VoteCast event.

castVoteWithReasonAndParams(uint256 proposalId, uint8 support, string reason, bytes params) → uint256 balance public

Cast a vote with a reason and additional encoded parameters

Emits a VoteCast or VoteCastWithParams event depending on the length of params.

castVoteBySig(uint256 proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s) → uint256 balance public

Cast a vote using the user’s cryptographic signature.

Emits a VoteCast event.

castVoteWithReasonAndParamsBySig(uint256 proposalId, uint8 support, string reason, bytes params, uint8 v, bytes32 r, bytes32 s) → uint256 balance public

Cast a vote with a reason and additional encoded parameters using the user’s cryptographic signature.

Emits a VoteCast or VoteCastWithParams event depending on the length of params.

ProposalCreated(uint256 proposalId, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 voteStart, uint256 voteEnd, string description) event

Emitted when a proposal is created.

ProposalCanceled(uint256 proposalId) event

Emitted when a proposal is canceled.

ProposalExecuted(uint256 proposalId) event

Emitted when a proposal is executed.

VoteCast(address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason) event

Emitted when a vote is cast without params.

Note: support values should be seen as buckets. Their interpretation depends on the voting module used.

VoteCastWithParams(address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason, bytes params) event

Emitted when a vote is cast with params.

Note: support values should be seen as buckets. Their interpretation depends on the voting module used. params are additional encoded parameters. Their interpepretation also depends on the voting module used.

Governor

import "@openzeppelin/contracts/governance/Governor.sol";

Core of the governance system, designed to be extended though various modules.

This contract is abstract and requires several functions to be implemented in various modules:

Available since v4.3.

Modifiers
Functions

onlyGovernance() modifier

Restricts a function so it can only be executed through governance proposals. For example, governance parameter setters in GovernorSettings are protected using this modifier.

The governance executing address may be different from the Governor’s own address, for example it could be a timelock. This can be customized by modules by overriding _executor. The executor is only able to invoke these functions during the execution of the governor’s execute function, and not under any other circumstances. Thus, for example, additional timelock proposers are not able to change governance parameters without going through the governance protocol (since v4.6).

constructor(string name_) internal

Sets the value for name and version

receive() external

Function to receive ETH that will be handled by the governor (disabled if executor is a third party contract)

supportsInterface(bytes4 interfaceId) → bool public

name() → string public

version() → string public

hashProposal(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) → uint256 public

The proposal id is produced by hashing the ABI encoded targets array, the values array, the calldatas array and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id can be produced from the proposal data which is part of the ProposalCreated event. It can even be computed in advance, before the proposal is submitted.

Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the same proposal (with same operation and same description) will have the same id if submitted on multiple governors across multiple networks. This also means that in order to execute the same operation twice (on the same governor) the proposer will have to change the description in order to avoid proposal id conflicts.

state(uint256 proposalId) → enum IGovernor.ProposalState public

proposalThreshold() → uint256 public

Part of the Governor Bravo’s interface: "The number of votes required in order for a voter to become a proposer".

proposalSnapshot(uint256 proposalId) → uint256 public

proposalDeadline(uint256 proposalId) → uint256 public

proposalProposer(uint256 proposalId) → address public

Returns the account that created a given proposal.

_quorumReached(uint256 proposalId) → bool internal

Amount of votes already cast passes the threshold limit.

_voteSucceeded(uint256 proposalId) → bool internal

Is the proposal successful or not.

_getVotes(address account, uint256 timepoint, bytes params) → uint256 internal

Get the voting weight of account at a specific timepoint, for a vote as described by params.

_countVote(uint256 proposalId, address account, uint8 support, uint256 weight, bytes params) internal

Register a vote for proposalId by account with a given support, voting weight and voting params.

Note: Support is generic and can represent various things depending on the voting system used.

_defaultParams() → bytes internal

Default additional encoded parameters used by castVote methods that don’t include them

Note: Should be overridden by specific implementations to use an appropriate value, the meaning of the additional params, in the context of that implementation

propose(address[] targets, uint256[] values, bytes[] calldatas, string description) → uint256 public

See IGovernor.propose. This function has opt-in frontrunning protection, described in _isValidDescriptionForProposer.

execute(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) → uint256 public

cancel(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) → uint256 public

_execute(uint256, address[] targets, uint256[] values, bytes[] calldatas, bytes32) internal

Internal execution mechanism. Can be overridden to implement different execution mechanism

_beforeExecute(uint256, address[] targets, uint256[], bytes[] calldatas, bytes32) internal

Hook before execution is triggered.

_afterExecute(uint256, address[], uint256[], bytes[], bytes32) internal

Hook after execution is triggered.

_cancel(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) → uint256 internal

Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as canceled to allow distinguishing it from executed proposals.

getVotes(address account, uint256 timepoint) → uint256 public

getVotesWithParams(address account, uint256 timepoint, bytes params) → uint256 public

castVote(uint256 proposalId, uint8 support) → uint256 public

castVoteWithReason(uint256 proposalId, uint8 support, string reason) → uint256 public

castVoteWithReasonAndParams(uint256 proposalId, uint8 support, string reason, bytes params) → uint256 public

castVoteBySig(uint256 proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s) → uint256 public

castVoteWithReasonAndParamsBySig(uint256 proposalId, uint8 support, string reason, bytes params, uint8 v, bytes32 r, bytes32 s) → uint256 public

_castVote(uint256 proposalId, address account, uint8 support, string reason) → uint256 internal

Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve voting weight using IGovernor.getVotes and call the _countVote internal function. Uses the _defaultParams().

Emits a IGovernor.VoteCast event.

_castVote(uint256 proposalId, address account, uint8 support, string reason, bytes params) → uint256 internal

Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve voting weight using IGovernor.getVotes and call the _countVote internal function.

Emits a IGovernor.VoteCast event.

relay(address target, uint256 value, bytes data) external

Relays a transaction or function call to an arbitrary target. In cases where the governance executor is some contract other than the governor itself, like when using a timelock, this function can be invoked in a governance proposal to recover tokens or Ether that was sent to the governor contract by mistake. Note that if the executor is simply the governor itself, use of relay is redundant.

_executor() → address internal

Address through which the governor executes action. Will be overloaded by module that execute actions through another contract such as a timelock.

onERC721Received(address, address, uint256, bytes) → bytes4 public

onERC1155Received(address, address, uint256, uint256, bytes) → bytes4 public

onERC1155BatchReceived(address, address, uint256[], uint256[], bytes) → bytes4 public

_isValidDescriptionForProposer(address proposer, string description) → bool internal

Check if the proposer is authorized to submit a proposal with the given description.

If the proposal description ends with #proposer=0x???, where 0x??? is an address written as a hex string (case insensitive), then the submission of this proposal will only be authorized to said address.

This is used for frontrunning protection. By adding this pattern at the end of their proposal, one can ensure that no other address can submit the same proposal. An attacker would have to either remove or change that part, which would result in a different proposal id.

If the description does not match this pattern, it is unrestricted and anyone can submit it. This includes: - If the 0x??? part is not a valid hex string. - If the 0x??? part is a valid hex string, but does not contain exactly 40 hex digits. - If it ends with the expected suffix followed by newlines or other whitespace. - If it ends with some other similar suffix, e.g. #other=abc. - If it does not end with any such suffix.

Modules

GovernorCountingSimple

import "@openzeppelin/contracts/governance/extensions/GovernorCountingSimple.sol";

Extension of Governor for simple, 3 options, vote counting.

Available since v4.3.

Functions

COUNTING_MODE() → string public

hasVoted(uint256 proposalId, address account) → bool public

proposalVotes(uint256 proposalId) → uint256 againstVotes, uint256 forVotes, uint256 abstainVotes public

Accessor to the internal vote counts.

_quorumReached(uint256 proposalId) → bool internal

_voteSucceeded(uint256 proposalId) → bool internal

See Governor._voteSucceeded. In this module, the forVotes must be strictly over the againstVotes.

_countVote(uint256 proposalId, address account, uint8 support, uint256 weight, bytes) internal

See Governor._countVote. In this module, the support follows the VoteType enum (from Governor Bravo).

GovernorVotes

import "@openzeppelin/contracts/governance/extensions/GovernorVotes.sol";

Extension of Governor for voting weight extraction from an ERC20Votes token, or since v4.5 an ERC721Votes token.

Available since v4.3.

Functions

constructor(contract IVotes tokenAddress) internal

clock() → uint48 public

Clock (as specified in EIP-6372) is set to match the token’s clock. Fallback to block numbers if the token does not implement EIP-6372.

CLOCK_MODE() → string public

Machine-readable description of the clock as specified in EIP-6372.

_getVotes(address account, uint256 timepoint, bytes) → uint256 internal

GovernorVotesQuorumFraction

import "@openzeppelin/contracts/governance/extensions/GovernorVotesQuorumFraction.sol";

Extension of Governor for voting weight extraction from an ERC20Votes token and a quorum expressed as a fraction of the total supply.

Available since v4.3.

Functions

constructor(uint256 quorumNumeratorValue) internal

Initialize quorum as a fraction of the token’s total supply.

The fraction is specified as numerator / denominator. By default the denominator is 100, so quorum is specified as a percent: a numerator of 10 corresponds to quorum being 10% of total supply. The denominator can be customized by overriding quorumDenominator.

quorumNumerator() → uint256 public

Returns the current quorum numerator. See quorumDenominator.

quorumNumerator(uint256 timepoint) → uint256 public

Returns the quorum numerator at a specific timepoint. See quorumDenominator.

quorumDenominator() → uint256 public

Returns the quorum denominator. Defaults to 100, but may be overridden.

quorum(uint256 timepoint) → uint256 public

Returns the quorum for a timepoint, in terms of number of votes: supply * numerator / denominator.

updateQuorumNumerator(uint256 newQuorumNumerator) external

Changes the quorum numerator.

Emits a QuorumNumeratorUpdated event.

Requirements:

  • Must be called through a governance proposal.

  • New numerator must be smaller or equal to the denominator.

_updateQuorumNumerator(uint256 newQuorumNumerator) internal

Changes the quorum numerator.

Emits a QuorumNumeratorUpdated event.

Requirements:

  • New numerator must be smaller or equal to the denominator.

QuorumNumeratorUpdated(uint256 oldQuorumNumerator, uint256 newQuorumNumerator) event

GovernorVotesComp

import "@openzeppelin/contracts/governance/extensions/GovernorVotesComp.sol";

Extension of Governor for voting weight extraction from a Comp token.

Available since v4.3.

Functions

constructor(contract ERC20VotesComp token_) internal

clock() → uint48 public

Clock (as specified in EIP-6372) is set to match the token’s clock. Fallback to block numbers if the token does not implement EIP-6372.

CLOCK_MODE() → string public

Machine-readable description of the clock as specified in EIP-6372.

_getVotes(address account, uint256 timepoint, bytes) → uint256 internal

Extensions

GovernorTimelockControl

import "@openzeppelin/contracts/governance/extensions/GovernorTimelockControl.sol";

Extension of Governor that binds the execution process to an instance of TimelockController. This adds a delay, enforced by the TimelockController to all successful proposal (in addition to the voting duration). The Governor needs the proposer (and ideally the executor) roles for the Governor to work properly.

Using this model means the proposal will be operated by the TimelockController and not by the Governor. Thus, the assets and permissions must be attached to the TimelockController. Any asset sent to the Governor will be inaccessible.

Setting up the TimelockController to have additional proposers besides the governor is very risky, as it grants them powers that they must be trusted or known not to use: 1) onlyGovernance functions like relay are available to them through the timelock, and 2) approved governance proposals can be blocked by them, effectively executing a Denial of Service attack. This risk will be mitigated in a future release.

Available since v4.3.

Functions

constructor(contract TimelockController timelockAddress) internal

Set the timelock.

supportsInterface(bytes4 interfaceId) → bool public

state(uint256 proposalId) → enum IGovernor.ProposalState public

Overridden version of the Governor.state function with added support for the Queued state.

timelock() → address public

Public accessor to check the address of the timelock

proposalEta(uint256 proposalId) → uint256 public

Public accessor to check the eta of a queued proposal

queue(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) → uint256 public

Function to queue a proposal to the timelock.

_execute(uint256, address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) internal

Overridden execute function that run the already queued proposal through the timelock.

_cancel(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) → uint256 internal

Overridden version of the Governor._cancel function to cancel the timelocked proposal if it as already been queued.

_executor() → address internal

Address through which the governor executes action. In this case, the timelock.

updateTimelock(contract TimelockController newTimelock) external

Public endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates must be proposed, scheduled, and executed through governance proposals.

It is not recommended to change the timelock while there are other queued governance proposals.

TimelockChange(address oldTimelock, address newTimelock) event

Emitted when the timelock controller used for proposal execution is modified.

GovernorTimelockCompound

import "@openzeppelin/contracts/governance/extensions/GovernorTimelockCompound.sol";

Extension of Governor that binds the execution process to a Compound Timelock. This adds a delay, enforced by the external timelock to all successful proposal (in addition to the voting duration). The Governor needs to be the admin of the timelock for any operation to be performed. A public, unrestricted, GovernorTimelockCompound.acceptAdmin is available to accept ownership of the timelock.

Using this model means the proposal will be operated by the TimelockController and not by the Governor. Thus, the assets and permissions must be attached to the TimelockController. Any asset sent to the Governor will be inaccessible.

Available since v4.3.

Functions

constructor(contract ICompoundTimelock timelockAddress) internal

Set the timelock.

supportsInterface(bytes4 interfaceId) → bool public

state(uint256 proposalId) → enum IGovernor.ProposalState public

Overridden version of the Governor.state function with added support for the Queued and Expired state.

timelock() → address public

Public accessor to check the address of the timelock

proposalEta(uint256 proposalId) → uint256 public

Public accessor to check the eta of a queued proposal

queue(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) → uint256 public

Function to queue a proposal to the timelock.

_execute(uint256 proposalId, address[] targets, uint256[] values, bytes[] calldatas, bytes32) internal

Overridden execute function that run the already queued proposal through the timelock.

_cancel(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) → uint256 internal

Overridden version of the Governor._cancel function to cancel the timelocked proposal if it as already been queued.

_executor() → address internal

Address through which the governor executes action. In this case, the timelock.

__acceptAdmin() public

Accept admin right over the timelock.

updateTimelock(contract ICompoundTimelock newTimelock) external

Public endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates must be proposed, scheduled, and executed through governance proposals.

For security reasons, the timelock must be handed over to another admin before setting up a new one. The two operations (hand over the timelock) and do the update can be batched in a single proposal.

Note that if the timelock admin has been handed over in a previous operation, we refuse updates made through the timelock if admin of the timelock has already been accepted and the operation is executed outside the scope of governance.

It is not recommended to change the timelock while there are other queued governance proposals.

TimelockChange(address oldTimelock, address newTimelock) event

Emitted when the timelock controller used for proposal execution is modified.

GovernorSettings

import "@openzeppelin/contracts/governance/extensions/GovernorSettings.sol";

Extension of Governor for settings updatable through governance.

Available since v4.4.

Functions

constructor(uint256 initialVotingDelay, uint256 initialVotingPeriod, uint256 initialProposalThreshold) internal

Initialize the governance parameters.

votingDelay() → uint256 public

votingPeriod() → uint256 public

proposalThreshold() → uint256 public

setVotingDelay(uint256 newVotingDelay) public

Update the voting delay. This operation can only be performed through a governance proposal.

Emits a VotingDelaySet event.

setVotingPeriod(uint256 newVotingPeriod) public

Update the voting period. This operation can only be performed through a governance proposal.

Emits a VotingPeriodSet event.

setProposalThreshold(uint256 newProposalThreshold) public

Update the proposal threshold. This operation can only be performed through a governance proposal.

Emits a ProposalThresholdSet event.

_setVotingDelay(uint256 newVotingDelay) internal

Internal setter for the voting delay.

Emits a VotingDelaySet event.

_setVotingPeriod(uint256 newVotingPeriod) internal

Internal setter for the voting period.

Emits a VotingPeriodSet event.

_setProposalThreshold(uint256 newProposalThreshold) internal

Internal setter for the proposal threshold.

Emits a ProposalThresholdSet event.

VotingDelaySet(uint256 oldVotingDelay, uint256 newVotingDelay) event

VotingPeriodSet(uint256 oldVotingPeriod, uint256 newVotingPeriod) event

ProposalThresholdSet(uint256 oldProposalThreshold, uint256 newProposalThreshold) event

GovernorPreventLateQuorum

import "@openzeppelin/contracts/governance/extensions/GovernorPreventLateQuorum.sol";

A module that ensures there is a minimum voting period after quorum is reached. This prevents a large voter from swaying a vote and triggering quorum at the last minute, by ensuring there is always time for other voters to react and try to oppose the decision.

If a vote causes quorum to be reached, the proposal’s voting period may be extended so that it does not end before at least a specified time has passed (the "vote extension" parameter). This parameter can be set through a governance proposal.

Available since v4.5.

Functions

constructor(uint64 initialVoteExtension) internal

Initializes the vote extension parameter: the time in either number of blocks or seconds (depending on the governor clock mode) that is required to pass since the moment a proposal reaches quorum until its voting period ends. If necessary the voting period will be extended beyond the one set during proposal creation.

proposalDeadline(uint256 proposalId) → uint256 public

Returns the proposal deadline, which may have been extended beyond that set at proposal creation, if the proposal reached quorum late in the voting period. See Governor.proposalDeadline.

_castVote(uint256 proposalId, address account, uint8 support, string reason, bytes params) → uint256 internal

Casts a vote and detects if it caused quorum to be reached, potentially extending the voting period. See Governor._castVote.

May emit a ProposalExtended event.

lateQuorumVoteExtension() → uint64 public

Returns the current value of the vote extension parameter: the number of blocks that are required to pass from the time a proposal reaches quorum until its voting period ends.

setLateQuorumVoteExtension(uint64 newVoteExtension) public

Changes the lateQuorumVoteExtension. This operation can only be performed by the governance executor, generally through a governance proposal.

_setLateQuorumVoteExtension(uint64 newVoteExtension) internal

Changes the lateQuorumVoteExtension. This is an internal function that can be exposed in a public function like setLateQuorumVoteExtension if another access control mechanism is needed.

ProposalExtended(uint256 indexed proposalId, uint64 extendedDeadline) event

Emitted when a proposal deadline is pushed back due to reaching quorum late in its voting period.

LateQuorumVoteExtensionSet(uint64 oldVoteExtension, uint64 newVoteExtension) event

Emitted when the lateQuorumVoteExtension parameter is changed.

GovernorCompatibilityBravo

import "@openzeppelin/contracts/governance/compatibility/GovernorCompatibilityBravo.sol";

Compatibility layer that implements GovernorBravo compatibility on top of Governor.

This compatibility layer includes a voting system and requires a IGovernorTimelock compatible module to be added through inheritance. It does not include token bindings, nor does it include any variable upgrade patterns.

When using this module, you may need to enable the Solidity optimizer to avoid hitting the contract size limit.

Available since v4.3.

Functions

COUNTING_MODE() → string public

A description of the possible support values for castVote and the way these votes are counted, meant to be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of key-value pairs that each describe one aspect, for example support=bravo&quorum=for,abstain.

There are 2 standard keys: support and quorum.

  • support=bravo refers to the vote options 0 = Against, 1 = For, 2 = Abstain, as in GovernorBravo.

  • quorum=bravo means that only For votes are counted towards quorum.

  • quorum=for,abstain means that both For and Abstain votes are counted towards quorum.

If a counting module makes use of encoded params, it should include this under a params key with a unique name that describes the behavior. For example:

  • params=fractional might refer to a scheme where votes are divided fractionally between for/against/abstain.

  • params=erc721 might refer to a scheme where specific NFTs are delegated to vote.

The string can be decoded by the standard URLSearchParams JavaScript class.

propose(address[] targets, uint256[] values, bytes[] calldatas, string description) → uint256 public

propose(address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, string description) → uint256 public

queue(uint256 proposalId) public

execute(uint256 proposalId) public

cancel(uint256 proposalId) public

Cancel a proposal with GovernorBravo logic.

cancel(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) → uint256 public

Cancel a proposal with GovernorBravo logic. At any moment a proposal can be cancelled, either by the proposer, or by third parties if the proposer’s voting power has dropped below the proposal threshold.

proposals(uint256 proposalId) → uint256 id, address proposer, uint256 eta, uint256 startBlock, uint256 endBlock, uint256 forVotes, uint256 againstVotes, uint256 abstainVotes, bool canceled, bool executed public

getActions(uint256 proposalId) → address[] targets, uint256[] values, string[] signatures, bytes[] calldatas public

getReceipt(uint256 proposalId, address voter) → struct IGovernorCompatibilityBravo.Receipt public

quorumVotes() → uint256 public

hasVoted(uint256 proposalId, address account) → bool public

_quorumReached(uint256 proposalId) → bool internal

See Governor._quorumReached. In this module, only forVotes count toward the quorum.

_voteSucceeded(uint256 proposalId) → bool internal

See Governor._voteSucceeded. In this module, the forVotes must be strictly over the againstVotes.

_countVote(uint256 proposalId, address account, uint8 support, uint256 weight, bytes) internal

See Governor._countVote. In this module, the support follows Governor Bravo.

Deprecated

GovernorProposalThreshold

import "@openzeppelin/contracts/governance/extensions/GovernorProposalThreshold.sol";

Extension of Governor for proposal restriction to token holders with a minimum balance.

Available since v4.3. Deprecated since v4.4.

Functions

propose(address[] targets, uint256[] values, bytes[] calldatas, string description) → uint256 public

See IGovernor.propose. This function has opt-in frontrunning protection, described in _isValidDescriptionForProposer.

Utils

Votes

import "@openzeppelin/contracts/governance/utils/Votes.sol";

This is a base abstract contract that tracks voting units, which are a measure of voting power that can be transferred, and provides a system of vote delegation, where an account can delegate its voting units to a sort of "representative" that will pool delegated voting units from different accounts and can then use it to vote in decisions. In fact, voting units must be delegated in order to count as actual votes, and an account has to delegate those votes to itself if it wishes to participate in decisions and does not have a trusted representative.

This contract is often combined with a token contract such that voting units correspond to token units. For an example, see ERC721Votes.

The full history of delegate votes is tracked on-chain so that governance protocols can consider votes as distributed at a particular block number to protect against flash loans and double voting. The opt-in delegate system makes the cost of this history tracking optional.

When using this module the derived contract must implement _getVotingUnits (for example, make it return ERC721.balanceOf), and can use _transferVotingUnits to track a change in the distribution of those units (in the previous example, it would be included in ERC721._beforeTokenTransfer).

Available since v4.5.

clock() → uint48 public

Clock used for flagging checkpoints. Can be overridden to implement timestamp based checkpoints (and voting), in which case CLOCK_MODE should be overridden as well to match.

CLOCK_MODE() → string public

Machine-readable description of the clock as specified in EIP-6372.

getVotes(address account) → uint256 public

Returns the current amount of votes that account has.

getPastVotes(address account, uint256 timepoint) → uint256 public

Returns the amount of votes that account had at a specific moment in the past. If the clock() is configured to use block numbers, this will return the value at the end of the corresponding block.

Requirements:

  • timepoint must be in the past. If operating using block numbers, the block must be already mined.

getPastTotalSupply(uint256 timepoint) → uint256 public

Returns the total supply of votes available at a specific moment in the past. If the clock() is configured to use block numbers, this will return the value at the end of the corresponding block.

This value is the sum of all available votes, which is not necessarily the sum of all delegated votes. Votes that have not been delegated are still part of total supply, even though they would not participate in a vote.

Requirements:

  • timepoint must be in the past. If operating using block numbers, the block must be already mined.

_getTotalSupply() → uint256 internal

Returns the current total supply of votes.

delegates(address account) → address public

Returns the delegate that account has chosen.

delegate(address delegatee) public

Delegates votes from the sender to delegatee.

delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) public

Delegates votes from signer to delegatee.

_delegate(address account, address delegatee) internal

Delegate all of account’s voting units to `delegatee.

_transferVotingUnits(address from, address to, uint256 amount) internal

Transfers, mints, or burns voting units. To register a mint, from should be zero. To register a burn, to should be zero. Total supply of voting units will be adjusted with mints and burns.

_useNonce(address owner) → uint256 current internal

Consumes a nonce.

Returns the current value and increments nonce.

nonces(address owner) → uint256 public

Returns an address nonce.

DOMAIN_SEPARATOR() → bytes32 external

Returns the contract’s EIP712 domain separator.

_getVotingUnits(address) → uint256 internal

Must return the voting units held by an account.

Timelock

In a governance system, the TimelockController contract is in charge of introducing a delay between a proposal and its execution. It can be used with or without a Governor.

TimelockController

import "@openzeppelin/contracts/governance/TimelockController.sol";

Contract module which acts as a timelocked controller. When set as the owner of an Ownable smart contract, it enforces a timelock on all onlyOwner maintenance operations. This gives time for users of the controlled contract to exit before a potentially dangerous maintenance operation is applied.

By default, this contract is self administered, meaning administration tasks have to go through the timelock process. The proposer (resp executor) role is in charge of proposing (resp executing) operations. A common use case is to position this TimelockController as the owner of a smart contract, with a multisig or a DAO as the sole proposer.

Available since v3.3.

onlyRoleOrOpenRole(bytes32 role) modifier

Modifier to make a function callable only by a certain role. In addition to checking the sender’s role, address(0) 's role is also considered. Granting a role to address(0) is equivalent to enabling this role for everyone.

constructor(uint256 minDelay, address[] proposers, address[] executors, address admin) public

Initializes the contract with the following parameters:

  • minDelay: initial minimum delay for operations

  • proposers: accounts to be granted proposer and canceller roles

  • executors: accounts to be granted executor role

  • admin: optional account to be granted admin role; disable with zero address

The optional admin can aid with initial configuration of roles after deployment without being subject to delay, but this role should be subsequently renounced in favor of administration through timelocked proposals. Previous versions of this contract would assign this admin to the deployer automatically and should be renounced as well.

receive() external

Contract might receive/hold ETH as part of the maintenance process.

supportsInterface(bytes4 interfaceId) → bool public

isOperation(bytes32 id) → bool public

Returns whether an id correspond to a registered operation. This includes both Pending, Ready and Done operations.

isOperationPending(bytes32 id) → bool public

Returns whether an operation is pending or not. Note that a "pending" operation may also be "ready".

isOperationReady(bytes32 id) → bool public

Returns whether an operation is ready for execution. Note that a "ready" operation is also "pending".

isOperationDone(bytes32 id) → bool public

Returns whether an operation is done or not.

getTimestamp(bytes32 id) → uint256 public

Returns the timestamp at which an operation becomes ready (0 for unset operations, 1 for done operations).

getMinDelay() → uint256 public

Returns the minimum delay for an operation to become valid.

This value can be changed by executing an operation that calls updateDelay.

hashOperation(address target, uint256 value, bytes data, bytes32 predecessor, bytes32 salt) → bytes32 public

Returns the identifier of an operation containing a single transaction.

hashOperationBatch(address[] targets, uint256[] values, bytes[] payloads, bytes32 predecessor, bytes32 salt) → bytes32 public

Returns the identifier of an operation containing a batch of transactions.

schedule(address target, uint256 value, bytes data, bytes32 predecessor, bytes32 salt, uint256 delay) public

Schedule an operation containing a single transaction.

Emits CallSalt if salt is nonzero, and CallScheduled.

Requirements:

  • the caller must have the 'proposer' role.

scheduleBatch(address[] targets, uint256[] values, bytes[] payloads, bytes32 predecessor, bytes32 salt, uint256 delay) public

Schedule an operation containing a batch of transactions.

Emits CallSalt if salt is nonzero, and one CallScheduled event per transaction in the batch.

Requirements:

  • the caller must have the 'proposer' role.

cancel(bytes32 id) public

Cancel an operation.

Requirements:

  • the caller must have the 'canceller' role.

execute(address target, uint256 value, bytes payload, bytes32 predecessor, bytes32 salt) public

Execute an (ready) operation containing a single transaction.

Emits a CallExecuted event.

Requirements:

  • the caller must have the 'executor' role.

executeBatch(address[] targets, uint256[] values, bytes[] payloads, bytes32 predecessor, bytes32 salt) public

Execute an (ready) operation containing a batch of transactions.

Emits one CallExecuted event per transaction in the batch.

Requirements:

  • the caller must have the 'executor' role.

_execute(address target, uint256 value, bytes data) internal

Execute an operation’s call.

updateDelay(uint256 newDelay) external

Changes the minimum timelock duration for future operations.

Emits a MinDelayChange event.

Requirements:

  • the caller must be the timelock itself. This can only be achieved by scheduling and later executing an operation where the timelock is the target and the data is the ABI-encoded call to this function.

onERC721Received(address, address, uint256, bytes) → bytes4 public

onERC1155Received(address, address, uint256, uint256, bytes) → bytes4 public

onERC1155BatchReceived(address, address, uint256[], uint256[], bytes) → bytes4 public

CallScheduled(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data, bytes32 predecessor, uint256 delay) event

Emitted when a call is scheduled as part of operation id.

CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data) event

Emitted when a call is performed as part of operation id.

CallSalt(bytes32 indexed id, bytes32 salt) event

Emitted when new proposal is scheduled with non-zero salt.

Cancelled(bytes32 indexed id) event

Emitted when operation id is cancelled.

MinDelayChange(uint256 oldDuration, uint256 newDuration) event

Emitted when the minimum delay for future operations is modified.

Terminology

  • Operation: A transaction (or a set of transactions) that is the subject of the timelock. It has to be scheduled by a proposer and executed by an executor. The timelock enforces a minimum delay between the proposition and the execution (see operation lifecycle). If the operation contains multiple transactions (batch mode), they are executed atomically. Operations are identified by the hash of their content.

  • Operation status:

    • Unset: An operation that is not part of the timelock mechanism.

    • Pending: An operation that has been scheduled, before the timer expires.

    • Ready: An operation that has been scheduled, after the timer expires.

    • Done: An operation that has been executed.

  • Predecessor: An (optional) dependency between operations. An operation can depend on another operation (its predecessor), forcing the execution order of these two operations.

  • Role:

    • Admin: An address (smart contract or EOA) that is in charge of granting the roles of Proposer and Executor.

    • Proposer: An address (smart contract or EOA) that is in charge of scheduling (and cancelling) operations.

    • Executor: An address (smart contract or EOA) that is in charge of executing operations once the timelock has expired. This role can be given to the zero address to allow anyone to execute operations.

Operation structure

Operation executed by the TimelockController can contain one or multiple subsequent calls. Depending on whether you need to multiple calls to be executed atomically, you can either use simple or batched operations.

Both operations contain:

  • Target, the address of the smart contract that the timelock should operate on.

  • Value, in wei, that should be sent with the transaction. Most of the time this will be 0. Ether can be deposited before-end or passed along when executing the transaction.

  • Data, containing the encoded function selector and parameters of the call. This can be produced using a number of tools. For example, a maintenance operation granting role ROLE to ACCOUNT can be encoded using web3js as follows:

const data = timelock.contract.methods.grantRole(ROLE, ACCOUNT).encodeABI()
  • Predecessor, that specifies a dependency between operations. This dependency is optional. Use bytes32(0) if the operation does not have any dependency.

  • Salt, used to disambiguate two otherwise identical operations. This can be any random value.

In the case of batched operations, target, value and data are specified as arrays, which must be of the same length.

Operation lifecycle

Timelocked operations are identified by a unique id (their hash) and follow a specific lifecycle:

UnsetPendingPending + ReadyDone

  • By calling schedule (or scheduleBatch), a proposer moves the operation from the Unset to the Pending state. This starts a timer that must be longer than the minimum delay. The timer expires at a timestamp accessible through the getTimestamp method.

  • Once the timer expires, the operation automatically gets the Ready state. At this point, it can be executed.

  • By calling execute (or executeBatch), an executor triggers the operation’s underlying transactions and moves it to the Done state. If the operation has a predecessor, it has to be in the Done state for this transition to succeed.

  • cancel allows proposers to cancel any Pending operation. This resets the operation to the Unset state. It is thus possible for a proposer to re-schedule an operation that has been cancelled. In this case, the timer restarts when the operation is re-scheduled.

Operations status can be queried using the functions:

Roles

Admin

The admins are in charge of managing proposers and executors. For the timelock to be self-governed, this role should only be given to the timelock itself. Upon deployment, the admin role can be granted to any address (in addition to the timelock itself). After further configuration and testing, this optional admin should renounce its role such that all further maintenance operations have to go through the timelock process.

This role is identified by the TIMELOCK_ADMIN_ROLE value: 0x5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca5

Proposer

The proposers are in charge of scheduling (and cancelling) operations. This is a critical role, that should be given to governing entities. This could be an EOA, a multisig, or a DAO.

Proposer fight: Having multiple proposers, while providing redundancy in case one becomes unavailable, can be dangerous. As proposer have their say on all operations, they could cancel operations they disagree with, including operations to remove them for the proposers.

This role is identified by the PROPOSER_ROLE value: 0xb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc1

Executor

The executors are in charge of executing the operations scheduled by the proposers once the timelock expires. Logic dictates that multisig or DAO that are proposers should also be executors in order to guarantee operations that have been scheduled will eventually be executed. However, having additional executors can reduce the cost (the executing transaction does not require validation by the multisig or DAO that proposed it), while ensuring whoever is in charge of execution cannot trigger actions that have not been scheduled by the proposers. Alternatively, it is possible to allow any address to execute a proposal once the timelock has expired by granting the executor role to the zero address.

This role is identified by the EXECUTOR_ROLE value: 0xd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e63

A live contract without at least one proposer and one executor is locked. Make sure these roles are filled by reliable entities before the deployer renounces its administrative rights in favour of the timelock contract itself. See the AccessControl documentation to learn more about role management.