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.
-
GovernorVotes
: Extracts voting weight from anERC20Votes
, or since v4.5 anERC721Votes
token. -
GovernorVotesQuorumFraction
: Combines withGovernorVotes
to set the quorum as a fraction of the total token supply.
Counting modules determine valid voting options.
-
GovernorCountingSimple
: Simple voting mechanism with 3 voting options: Against, For and Abstain.
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.
-
GovernorTimelockAccess
: Connects with an instance of anAccessManager
. This allows restrictions (and delays) enforced by the manager to be considered by the Governor and integrated into the AccessManager’s "schedule + execute" workflow. -
GovernorTimelockControl
: Connects with an instance ofTimelockController
. Allows multiple proposers and executors, in addition to the Governor itself. -
GovernorTimelockCompound
: Connects with an instance of Compound’sTimelock
contract.
Other extensions can customize the behavior or interface in multiple ways.
-
GovernorStorage
: Stores the proposal details onchain and provides enumerability of the proposals. This can be useful for some L2 chains where storage is cheap compared to calldata. -
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 atimepoint
argument (see EIP-6372) so the quorum can adapt through time, for example, to follow a token’stotalSupply
.
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.
|
IGovernor
import "@openzeppelin/contracts/governance/IGovernor.sol";
Interface of the Governor
core.
name() → string
external
Name of the governor instance (used in building the ERC712 domain separator).
version() → string
external
Version of the governor instance (used in building the ERC712 domain separator). Default: "1"
COUNTING_MODE() → string
external
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 inGovernorBravo
. -
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
external
Hashing function used to (re)build the proposal id from the proposal details..
state(uint256 proposalId) → enum IGovernor.ProposalState
external
Current state of a proposal, following Compound’s convention
proposalThreshold() → uint256
external
The number of votes required in order for a voter to become a proposer.
proposalSnapshot(uint256 proposalId) → uint256
external
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
external
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.
proposalEta(uint256 proposalId) → uint256
external
The time when a queued proposal becomes executable ("ETA"). Unlike proposalSnapshot
and
proposalDeadline
, this doesn’t use the governor clock, and instead relies on the executor’s clock which may be
different. In most cases this will be a timestamp.
proposalNeedsQueuing(uint256 proposalId) → bool
external
Whether a proposal needs to be queued before execution.
votingDelay() → uint256
external
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.
While this interface returns a uint256, timepoints are stored as uint48 following the ERC-6372 clock type.
Consequently this value must fit in a uint48 (when added to the current clock). See IERC6372.clock .
|
votingPeriod() → uint256
external
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.
|
This value is stored when the proposal is submitted so that possible changes to the value do not affect proposals that have already been submitted. The type used to save it is a uint32. Consequently, while this interface returns a uint256, the value it returns should fit in a uint32. |
quorum(uint256 timepoint) → uint256
external
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
external
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
external
Voting power of an account
at a specific timepoint
given additional encoded parameters.
hasVoted(uint256 proposalId, address account) → bool
external
Returns whether account
has cast a vote on proposalId
.
propose(address[] targets, uint256[] values, bytes[] calldatas, string description) → uint256 proposalId
external
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.
queue(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) → uint256 proposalId
external
Queue a proposal. Some governors require this step to be performed before execution can happen. If queuing is not necessary, this function may revert. Queuing a proposal requires the quorum to be reached, the vote to be successful, and the deadline to be reached.
Emits a ProposalQueued
event.
execute(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) → uint256 proposalId
external
Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the deadline to be reached. Depending on the governor it might also be required that the proposal was queued and that some delay passed.
Emits a ProposalExecuted
event.
Some modules can modify the requirements for execution, for example by adding an additional timelock. |
cancel(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) → uint256 proposalId
external
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
external
Cast a vote
Emits a VoteCast
event.
castVoteWithReason(uint256 proposalId, uint8 support, string reason) → uint256 balance
external
Cast a vote with a reason
Emits a VoteCast
event.
castVoteWithReasonAndParams(uint256 proposalId, uint8 support, string reason, bytes params) → uint256 balance
external
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, address voter, bytes signature) → uint256 balance
external
Cast a vote using the voter’s signature, including ERC-1271 signature support.
Emits a VoteCast
event.
castVoteWithReasonAndParamsBySig(uint256 proposalId, uint8 support, address voter, string reason, bytes params, bytes signature) → uint256 balance
external
Cast a vote with a reason and additional encoded parameters using the voter’s signature, including ERC-1271 signature support.
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.
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.
GovernorInvalidProposalLength(uint256 targets, uint256 calldatas, uint256 values)
error
Empty proposal or a mismatch between the parameters length for a proposal call.
GovernorUnexpectedProposalState(uint256 proposalId, enum IGovernor.ProposalState current, bytes32 expectedStates)
error
The current state of a proposal is not the required for performing an operation.
The expectedStates
is a bitmap with the bits enabled for each ProposalState enum position
counting from right to left.
If expectedState is bytes32(0) , the proposal is expected to not be in any state (i.e. not exist).
This is the case when a proposal that is expected to be unset is already initiated (the proposal is duplicated).
|
GovernorInvalidVotingPeriod(uint256 votingPeriod)
error
The voting period set is not a valid period.
GovernorInsufficientProposerVotes(address proposer, uint256 votes, uint256 threshold)
error
The proposer
does not have the required votes to create a proposal.
GovernorRestrictedProposer(address proposer)
error
The proposer
is not allowed to create a proposal.
GovernorInvalidVoteType()
error
The vote type used is not valid for the corresponding counting module.
GovernorQueueNotImplemented()
error
Queue operation is not implemented for this governor. Execute should be called directly.
GovernorInvalidSignature(address voter)
error
The provided signature is not valid for the expected voter
.
If the voter
is a contract, the signature is not valid using IERC1271.isValidSignature
.
Governor
import "@openzeppelin/contracts/governance/Governor.sol";
Core of the governance system, designed to be extended through various modules.
This contract is abstract and requires several functions to be implemented in various modules:
-
A counting module must implement
quorum
,_quorumReached
,_voteSucceeded
and_countVote
-
A voting module must implement
_getVotes
-
Additionally,
votingPeriod
must also be implemented
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).
receive()
external
Function to receive ETH that will be handled by the governor (disabled if executor is a third party contract)
name() → string
public
See IGovernor.name
.
version() → string
public
See IGovernor.version
.
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
See IGovernor.state
.
_checkGovernance()
internal
Reverts if the msg.sender
is not the executor. In case the executor is not this contract
itself, the function reverts if msg.data
is not whitelisted as a result of an execute
operation. See onlyGovernance
.
_quorumReached(uint256 proposalId) → bool
internal
Amount of votes already cast passes the threshold limit.
_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
.
_propose(address[] targets, uint256[] values, bytes[] calldatas, string description, address proposer) → uint256 proposalId
internal
Internal propose mechanism. Can be overridden to add more logic on proposal creation.
Emits a IGovernor.ProposalCreated
event.
queue(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) → uint256
public
See IGovernor.queue
.
_queueOperations(uint256, address[], uint256[], bytes[], bytes32) → uint48
internal
Internal queuing mechanism. Can be overridden (without a super call) to modify the way queuing is performed (for example adding a vault/timelock).
This is empty by default, and must be overridden to implement queuing.
This function returns a timestamp that describes the expected ETA for execution. If the returned value is 0
(which is the default value), the core will consider queueing did not succeed, and the public queue
function
will revert.
Calling this function directly will NOT check the current state of the proposal, or emit the
ProposalQueued event. Queuing a proposal should be done using queue .
|
execute(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) → uint256
public
See IGovernor.execute
.
_executeOperations(uint256, address[] targets, uint256[] values, bytes[] calldatas, bytes32)
internal
Internal execution mechanism. Can be overridden (without a super call) to modify the way execution is performed (for example adding a vault/timelock).
Calling this function directly will NOT check the current state of the proposal, set the executed flag to
true or emit the ProposalExecuted event. Executing a proposal should be done using execute or {_execute}.
|
cancel(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) → uint256
public
See IGovernor.cancel
.
_cancel(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) → uint256
internal
Internal cancel mechanism with minimal restrictions. A proposal can be cancelled in any state other than Canceled, Expired, or Executed. Once cancelled a proposal can’t be re-submitted.
Emits a IGovernor.ProposalCanceled
event.
getVotes(address account, uint256 timepoint) → uint256
public
See IGovernor.getVotes
.
castVote(uint256 proposalId, uint8 support) → uint256
public
See IGovernor.castVote
.
castVoteWithReasonAndParams(uint256 proposalId, uint8 support, string reason, bytes params) → uint256
public
castVoteWithReasonAndParamsBySig(uint256 proposalId, uint8 support, address voter, string reason, bytes params, bytes signature) → 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
See IERC721Receiver.onERC721Received
.
Receiving tokens is disabled if the governance executor is other than the governor itself (eg. when using with a timelock).
onERC1155Received(address, address, uint256, uint256, bytes) → bytes4
public
See IERC1155Receiver.onERC1155Received
.
Receiving tokens is disabled if the governance executor is other than the governor itself (eg. when using with a timelock).
onERC1155BatchReceived(address, address, uint256[], uint256[], bytes) → bytes4
public
See IERC1155Receiver.onERC1155BatchReceived
.
Receiving tokens is disabled if the governance executor is other than the governor itself (eg. when using with a timelock).
_encodeStateBitmap(enum IGovernor.ProposalState proposalState) → bytes32
internal
Encodes a ProposalState
into a bytes32
representation where each bit enabled corresponds to
the underlying position in the ProposalState
enum. For example:
0x000…10000 ^^------ … ^----- Succeeded ^---- Defeated ^--- Canceled ^-- Active ^- Pending
clock() → uint48
public
Clock used for flagging checkpoints. Can be overridden to implement timestamp based checkpoints (and voting).
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.
While this interface returns a uint256, timepoints are stored as uint48 following the ERC-6372 clock type.
Consequently this value must fit in a uint48 (when added to the current clock). See IERC6372.clock .
|
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.
|
This value is stored when the proposal is submitted so that possible changes to the value do not affect proposals that have already been submitted. The type used to save it is a uint32. Consequently, while this interface returns a uint256, the value it returns should fit in a uint32. |
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 ).
|
GovernorCountingSimple
import "@openzeppelin/contracts/governance/extensions/GovernorCountingSimple.sol";
Extension of Governor
for simple, 3 options, vote counting.
hasVoted(uint256 proposalId, address account) → bool
public
See IGovernor.hasVoted
.
proposalVotes(uint256 proposalId) → uint256 againstVotes, uint256 forVotes, uint256 abstainVotes
public
Accessor to the internal vote counts.
_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.
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.
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.
GovernorTimelockAccess
import "@openzeppelin/contracts/governance/extensions/GovernorTimelockAccess.sol";
This module connects a Governor
instance to an accessManager
instance, allowing the governor to make calls
that are delay-restricted by the manager using the normal queue
workflow. An optional base delay is applied to
operations that are not delayed externally by the manager. Execution of a proposal will be delayed as much as
necessary to meet the required delays of all of its operations.
This extension allows the governor to hold and use its own assets and permissions, unlike GovernorTimelockControl
and GovernorTimelockCompound
, where the timelock is a separate contract that must be the one to hold assets and
permissions. Operations that are delay-restricted by the manager, however, will be executed through the
AccessManager.execute
function.
Security Considerations
Some operations may be cancelable in the AccessManager
by the admin or a set of guardians, depending on the
restricted function being invoked. Since proposals are atomic, the cancellation by a guardian of a single operation
in a proposal will cause all of the proposal to become unable to execute. Consider proposing cancellable operations
separately.
By default, function calls will be routed through the associated AccessManager
whenever it claims the target
function to be restricted by it. However, admins may configure the manager to make that claim for functions that a
governor would want to call directly (e.g., token transfers) in an attempt to deny it access to those functions. To
mitigate this attack vector, the governor is able to ignore the restrictions claimed by the AccessManager
using
setAccessManagerIgnored
. While permanent denial of service is mitigated, temporary DoS may still be technically
possible. All of the governor’s own functions (e.g., setBaseDelaySeconds
) ignore the AccessManager
by default.
constructor(address manager, uint32 initialBaseDelay)
internal
Initialize the governor with an accessManager
and initial base delay.
accessManager() → contract IAccessManager
public
Returns the accessManager
instance associated to this governor.
baseDelaySeconds() → uint32
public
Base delay that will be applied to all function calls. Some may be further delayed by their associated
AccessManager
authority; in this case the final delay will be the maximum of the base delay and the one
demanded by the authority.
Execution delays are processed by the AccessManager contracts, and according to that contract are
expressed in seconds. Therefore, the base delay is also in seconds, regardless of the governor’s clock mode.
|
setBaseDelaySeconds(uint32 newBaseDelay)
public
Change the value of baseDelaySeconds
. This operation can only be invoked through a governance proposal.
_setBaseDelaySeconds(uint32 newBaseDelay)
internal
Change the value of baseDelaySeconds
. Internal function without access control.
isAccessManagerIgnored(address target, bytes4 selector) → bool
public
Check if restrictions from the associated accessManager
are ignored for a target function. Returns true
when the target function will be invoked directly regardless of AccessManager
settings for the function.
See setAccessManagerIgnored
and Security Considerations above.
setAccessManagerIgnored(address target, bytes4[] selectors, bool ignored)
public
Configure whether restrictions from the associated accessManager
are ignored for a target function.
See Security Considerations above.
_setAccessManagerIgnored(address target, bytes4 selector, bool ignored)
internal
Internal version of setAccessManagerIgnored
without access restriction.
proposalExecutionPlan(uint256 proposalId) → uint32 delay, bool[] indirect, bool[] withDelay
public
Public accessor to check the execution plan, including the number of seconds that the proposal will be
delayed since queuing, an array indicating which of the proposal actions will be executed indirectly through
the associated accessManager
, and another indicating which will be scheduled in queue
. Note that
those that must be scheduled are cancellable by AccessManager
guardians.
propose(address[] targets, uint256[] values, bytes[] calldatas, string description) → uint256
public
_queueOperations(uint256 proposalId, address[] targets, uint256[], bytes[] calldatas, bytes32) → uint48
internal
Mechanism to queue a proposal, potentially scheduling some of its operations in the AccessManager.
The execution delay is chosen based on the delay information retrieved in propose . This value may be
off if the delay was updated since proposal creation. In this case, the proposal needs to be recreated.
|
_executeOperations(uint256 proposalId, address[] targets, uint256[] values, bytes[] calldatas, bytes32)
internal
Mechanism to execute a proposal, potentially going through AccessManager.execute
for delayed operations.
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 from a proposal, unless executed via Governor.relay
.
Setting up the TimelockController to have additional proposers or cancellers besides the governor is very risky, as it grants them the ability to: 1) execute operations as the timelock, and thus possibly performing operations or accessing funds that are expected to only be accessible through a vote, and 2) block governance proposals that have been approved by the voters, effectively executing a Denial of Service attack. |
AccessManager does not support scheduling more than one operation with the same target and calldata at
the same time. See AccessManager.schedule for a workaround.
|
state(uint256 proposalId) → enum IGovernor.ProposalState
public
Overridden version of the Governor.state
function that considers the status reported by the timelock.
_queueOperations(uint256 proposalId, address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) → uint48
internal
Function to queue a proposal to the timelock.
_executeOperations(uint256 proposalId, address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash)
internal
Overridden version of the Governor._executeOperations
function that runs 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 has 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. |
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.
state(uint256 proposalId) → enum IGovernor.ProposalState
public
Overridden version of the Governor.state
function with added support for the Expired
state.
_queueOperations(uint256 proposalId, address[] targets, uint256[] values, bytes[] calldatas, bytes32) → uint48
internal
Function to queue a proposal to the timelock.
_executeOperations(uint256 proposalId, address[] targets, uint256[] values, bytes[] calldatas, bytes32)
internal
Overridden version of the Governor._executeOperations
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 has already
been queued.
_executor() → address
internal
Address through which the governor executes action. In this case, 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. |
GovernorSettings
import "@openzeppelin/contracts/governance/extensions/GovernorSettings.sol";
Extension of Governor
for settings updatable through governance.
constructor(uint48 initialVotingDelay, uint32 initialVotingPeriod, uint256 initialProposalThreshold)
internal
Initialize the governance parameters.
setVotingDelay(uint48 newVotingDelay)
public
Update the voting delay. This operation can only be performed through a governance proposal.
Emits a VotingDelaySet
event.
setVotingPeriod(uint32 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(uint48 newVotingDelay)
internal
Internal setter for the voting delay.
Emits a VotingDelaySet
event.
_setVotingPeriod(uint32 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.
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.
constructor(uint48 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() → uint48
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(uint48 newVoteExtension)
public
Changes the lateQuorumVoteExtension
. This operation can only be performed by the governance executor,
generally through a governance proposal.
Emits a LateQuorumVoteExtensionSet
event.
_setLateQuorumVoteExtension(uint48 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.
Emits a LateQuorumVoteExtensionSet
event.
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.
GovernorStorage
import "@openzeppelin/contracts/governance/extensions/GovernorStorage.sol";
Extension of Governor
that implements storage of proposal details. This modules also provides primitives for
the enumerability of proposals.
Use cases for this module include:
- UIs that explore the proposal state without relying on event indexing.
- Using only the proposalId as an argument in the Governor.queue
and Governor.execute
functions for L2 chains
where storage is cheap compared to calldata.
_propose(address[] targets, uint256[] values, bytes[] calldatas, string description, address proposer) → uint256
internal
Hook into the proposing mechanism
queue(uint256 proposalId)
public
Version of {IGovernorTimelock-queue} with only proposalId
as an argument.
execute(uint256 proposalId)
public
Version of IGovernor.execute
with only proposalId
as an argument.
cancel(uint256 proposalId)
public
ProposalId version of IGovernor.cancel
.
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._update
).
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.
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.
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
.
Emits events IVotes.DelegateChanged
and IVotes.DelegateVotesChanged
.
_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.
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.
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 in seconds 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. |
isOperation(bytes32 id) → bool
public
Returns whether an id corresponds to a registered operation. This includes both Waiting, 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".
getTimestamp(bytes32 id) → uint256
public
Returns the timestamp at which an operation becomes ready (0 for unset operations, 1 for done operations).
getOperationState(bytes32 id) → enum TimelockController.OperationState
public
Returns operation state.
getMinDelay() → uint256
public
Returns the minimum delay in seconds 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.
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.
_encodeStateBitmap(enum TimelockController.OperationState operationState) → bytes32
internal
Encodes a OperationState
into a bytes32
representation where each bit enabled corresponds to
the underlying position in the OperationState
enum. For example:
0x000…1000 ^^----- … ^---- Done ^--- Ready ^-- Waiting ^- Unset
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.
MinDelayChange(uint256 oldDuration, uint256 newDuration)
event
Emitted when the minimum delay for future operations is modified.
TimelockInvalidOperationLength(uint256 targets, uint256 payloads, uint256 values)
error
Mismatch between the parameters length for an operation call.
TimelockInsufficientDelay(uint256 delay, uint256 minDelay)
error
The schedule operation doesn’t meet the minimum delay.
TimelockUnexpectedOperationState(bytes32 operationId, bytes32 expectedStates)
error
The current state of an operation is not as required.
The expectedStates
is a bitmap with the bits enabled for each OperationState enum position
counting from right to left.
See _encodeStateBitmap
.
TimelockUnexecutedPredecessor(bytes32 predecessorId)
error
The predecessor to an operation not yet done.
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.
-
Waiting: An operation that has been scheduled, before the timer expires.
-
Ready: An operation that has been scheduled, after the timer expires.
-
Pending: An operation that is either waiting or ready.
-
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
toACCOUNT
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:
Unset
→ Pending
→ Pending
+ Ready
→ Done
-
By calling
schedule
(orscheduleBatch
), a proposer moves the operation from theUnset
to thePending
state. This starts a timer that must be longer than the minimum delay. The timer expires at a timestamp accessible through thegetTimestamp
method. -
Once the timer expires, the operation automatically gets the
Ready
state. At this point, it can be executed. -
By calling
execute
(orexecuteBatch
), an executor triggers the operation’s underlying transactions and moves it to theDone
state. If the operation has a predecessor, it has to be in theDone
state for this transition to succeed. -
cancel
allows proposers to cancel anyPending
operation. This resets the operation to theUnset
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.
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.
|