123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686 |
- // SPDX-License-Identifier: MIT
- // OpenZeppelin Contracts (last updated v4.9.0) (governance/Governor.sol)
- pragma solidity ^0.8.19;
- import "../token/ERC721/IERC721Receiver.sol";
- import "../token/ERC1155/IERC1155Receiver.sol";
- import "../utils/cryptography/ECDSA.sol";
- import "../utils/cryptography/EIP712.sol";
- import "../utils/introspection/ERC165.sol";
- import "../utils/math/SafeCast.sol";
- import "../utils/structs/DoubleEndedQueue.sol";
- import "../utils/Address.sol";
- import "../utils/Context.sol";
- import "./IGovernor.sol";
- /**
- * @dev 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:
- *
- * - A counting module must implement {quorum}, {_quorumReached}, {_voteSucceeded} and {_countVote}
- * - A voting module must implement {_getVotes}
- * - Additionally, {votingPeriod} must also be implemented
- *
- * _Available since v4.3._
- */
- abstract contract Governor is Context, ERC165, EIP712, IGovernor, IERC721Receiver, IERC1155Receiver {
- using DoubleEndedQueue for DoubleEndedQueue.Bytes32Deque;
- bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)");
- bytes32 public constant EXTENDED_BALLOT_TYPEHASH =
- keccak256("ExtendedBallot(uint256 proposalId,uint8 support,string reason,bytes params)");
- // solhint-disable var-name-mixedcase
- struct ProposalCore {
- // --- start retyped from Timers.BlockNumber at offset 0x00 ---
- uint64 voteStart;
- address proposer;
- bytes4 __gap_unused0;
- // --- start retyped from Timers.BlockNumber at offset 0x20 ---
- uint64 voteEnd;
- bytes24 __gap_unused1;
- // --- Remaining fields starting at offset 0x40 ---------------
- bool executed;
- bool canceled;
- }
- // solhint-enable var-name-mixedcase
- string private _name;
- /// @custom:oz-retyped-from mapping(uint256 => Governor.ProposalCore)
- mapping(uint256 => ProposalCore) private _proposals;
- // This queue keeps track of the governor operating on itself. Calls to functions protected by the
- // {onlyGovernance} modifier needs to be whitelisted in this queue. Whitelisting is set in {_beforeExecute},
- // consumed by the {onlyGovernance} modifier and eventually reset in {_afterExecute}. This ensures that the
- // execution of {onlyGovernance} protected calls can only be achieved through successful proposals.
- DoubleEndedQueue.Bytes32Deque private _governanceCall;
- /**
- * @dev 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).
- */
- modifier onlyGovernance() {
- if (_msgSender() != _executor()) {
- revert GovernorOnlyGovernance();
- }
- if (_executor() != address(this)) {
- bytes32 msgDataHash = keccak256(_msgData());
- // loop until popping the expected operation - throw if deque is empty (operation not authorized)
- while (_governanceCall.popFront() != msgDataHash) {}
- }
- _;
- }
- /**
- * @dev Sets the value for {name} and {version}
- */
- constructor(string memory name_) EIP712(name_, version()) {
- _name = name_;
- }
- /**
- * @dev Function to receive ETH that will be handled by the governor (disabled if executor is a third party contract)
- */
- receive() external payable virtual {
- if (_executor() != address(this)) {
- revert GovernorDepositDisabled(address(this));
- }
- }
- /**
- * @dev See {IERC165-supportsInterface}.
- */
- function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
- bytes4 governorCancelId = this.cancel.selector ^ this.proposalProposer.selector;
- bytes4 governorParamsId = this.castVoteWithReasonAndParams.selector ^
- this.castVoteWithReasonAndParamsBySig.selector ^
- this.getVotesWithParams.selector;
- // The original interface id in v4.3.
- bytes4 governor43Id = type(IGovernor).interfaceId ^
- type(IERC6372).interfaceId ^
- governorCancelId ^
- governorParamsId;
- // An updated interface id in v4.6, with params added.
- bytes4 governor46Id = type(IGovernor).interfaceId ^ type(IERC6372).interfaceId ^ governorCancelId;
- // For the updated interface id in v4.9, we use governorCancelId directly.
- return
- interfaceId == governor43Id ||
- interfaceId == governor46Id ||
- interfaceId == governorCancelId ||
- interfaceId == type(IERC1155Receiver).interfaceId ||
- super.supportsInterface(interfaceId);
- }
- /**
- * @dev See {IGovernor-name}.
- */
- function name() public view virtual override returns (string memory) {
- return _name;
- }
- /**
- * @dev See {IGovernor-version}.
- */
- function version() public view virtual override returns (string memory) {
- return "1";
- }
- /**
- * @dev See {IGovernor-hashProposal}.
- *
- * 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.
- */
- function hashProposal(
- address[] memory targets,
- uint256[] memory values,
- bytes[] memory calldatas,
- bytes32 descriptionHash
- ) public pure virtual override returns (uint256) {
- return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash)));
- }
- /**
- * @dev See {IGovernor-state}.
- */
- function state(uint256 proposalId) public view virtual override returns (ProposalState) {
- ProposalCore storage proposal = _proposals[proposalId];
- if (proposal.executed) {
- return ProposalState.Executed;
- }
- if (proposal.canceled) {
- return ProposalState.Canceled;
- }
- uint256 snapshot = proposalSnapshot(proposalId);
- if (snapshot == 0) {
- revert GovernorNonexistentProposal(proposalId);
- }
- uint256 currentTimepoint = clock();
- if (snapshot >= currentTimepoint) {
- return ProposalState.Pending;
- }
- uint256 deadline = proposalDeadline(proposalId);
- if (deadline >= currentTimepoint) {
- return ProposalState.Active;
- }
- if (_quorumReached(proposalId) && _voteSucceeded(proposalId)) {
- return ProposalState.Succeeded;
- } else {
- return ProposalState.Defeated;
- }
- }
- /**
- * @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_.
- */
- function proposalThreshold() public view virtual returns (uint256) {
- return 0;
- }
- /**
- * @dev See {IGovernor-proposalSnapshot}.
- */
- function proposalSnapshot(uint256 proposalId) public view virtual override returns (uint256) {
- return _proposals[proposalId].voteStart;
- }
- /**
- * @dev See {IGovernor-proposalDeadline}.
- */
- function proposalDeadline(uint256 proposalId) public view virtual override returns (uint256) {
- return _proposals[proposalId].voteEnd;
- }
- /**
- * @dev Returns the account that created a given proposal.
- */
- function proposalProposer(uint256 proposalId) public view virtual override returns (address) {
- return _proposals[proposalId].proposer;
- }
- /**
- * @dev Amount of votes already cast passes the threshold limit.
- */
- function _quorumReached(uint256 proposalId) internal view virtual returns (bool);
- /**
- * @dev Is the proposal successful or not.
- */
- function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool);
- /**
- * @dev Get the voting weight of `account` at a specific `timepoint`, for a vote as described by `params`.
- */
- function _getVotes(address account, uint256 timepoint, bytes memory params) internal view virtual returns (uint256);
- /**
- * @dev 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.
- */
- function _countVote(
- uint256 proposalId,
- address account,
- uint8 support,
- uint256 weight,
- bytes memory params
- ) internal virtual;
- /**
- * @dev 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
- */
- function _defaultParams() internal view virtual returns (bytes memory) {
- return "";
- }
- /**
- * @dev See {IGovernor-propose}.
- */
- function propose(
- address[] memory targets,
- uint256[] memory values,
- bytes[] memory calldatas,
- string memory description
- ) public virtual override returns (uint256) {
- address proposer = _msgSender();
- uint256 currentTimepoint = clock();
- // Avoid stack too deep
- {
- uint256 proposerVotes = getVotes(proposer, currentTimepoint - 1);
- uint256 votesThreshold = proposalThreshold();
- if (proposerVotes < votesThreshold) {
- revert GovernorProposerInvalidTreshold(proposer, proposerVotes, votesThreshold);
- }
- }
- uint256 proposalId = hashProposal(targets, values, calldatas, keccak256(bytes(description)));
- if (targets.length != values.length || targets.length != calldatas.length || targets.length == 0) {
- revert GovernorInvalidProposalLength(targets.length, calldatas.length, values.length);
- }
- if (_proposals[proposalId].voteStart != 0) {
- revert GovernorIncorrectState(proposalId, state(proposalId), bytes32(0));
- }
- uint256 snapshot = currentTimepoint + votingDelay();
- uint256 deadline = snapshot + votingPeriod();
- _proposals[proposalId] = ProposalCore({
- proposer: proposer,
- voteStart: SafeCast.toUint64(snapshot),
- voteEnd: SafeCast.toUint64(deadline),
- executed: false,
- canceled: false,
- __gap_unused0: 0,
- __gap_unused1: 0
- });
- emit ProposalCreated(
- proposalId,
- proposer,
- targets,
- values,
- new string[](targets.length),
- calldatas,
- snapshot,
- deadline,
- description
- );
- return proposalId;
- }
- /**
- * @dev See {IGovernor-execute}.
- */
- function execute(
- address[] memory targets,
- uint256[] memory values,
- bytes[] memory calldatas,
- bytes32 descriptionHash
- ) public payable virtual override returns (uint256) {
- uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
- ProposalState currentState = state(proposalId);
- if (currentState != ProposalState.Succeeded && currentState != ProposalState.Queued) {
- revert GovernorIncorrectState(
- proposalId,
- currentState,
- _encodeState(ProposalState.Succeeded) | _encodeState(ProposalState.Queued)
- );
- }
- _proposals[proposalId].executed = true;
- emit ProposalExecuted(proposalId);
- _beforeExecute(proposalId, targets, values, calldatas, descriptionHash);
- _execute(proposalId, targets, values, calldatas, descriptionHash);
- _afterExecute(proposalId, targets, values, calldatas, descriptionHash);
- return proposalId;
- }
- /**
- * @dev See {IGovernor-cancel}.
- */
- function cancel(
- address[] memory targets,
- uint256[] memory values,
- bytes[] memory calldatas,
- bytes32 descriptionHash
- ) public virtual override returns (uint256) {
- uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
- ProposalState currentState = state(proposalId);
- if (currentState != ProposalState.Pending) {
- revert GovernorIncorrectState(proposalId, currentState, _encodeState(ProposalState.Pending));
- }
- if (_msgSender() != proposalProposer(proposalId)) {
- revert GovernorOnlyProposer(_msgSender());
- }
- return _cancel(targets, values, calldatas, descriptionHash);
- }
- /**
- * @dev Internal execution mechanism. Can be overridden to implement different execution mechanism
- */
- function _execute(
- uint256 /* proposalId */,
- address[] memory targets,
- uint256[] memory values,
- bytes[] memory calldatas,
- bytes32 /*descriptionHash*/
- ) internal virtual {
- for (uint256 i = 0; i < targets.length; ++i) {
- (bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]);
- Address.verifyCallResult(success, returndata, _customGovernorRevert);
- }
- }
- /**
- * @dev Hook before execution is triggered.
- */
- function _beforeExecute(
- uint256 /* proposalId */,
- address[] memory targets,
- uint256[] memory /* values */,
- bytes[] memory calldatas,
- bytes32 /*descriptionHash*/
- ) internal virtual {
- if (_executor() != address(this)) {
- for (uint256 i = 0; i < targets.length; ++i) {
- if (targets[i] == address(this)) {
- _governanceCall.pushBack(keccak256(calldatas[i]));
- }
- }
- }
- }
- /**
- * @dev Hook after execution is triggered.
- */
- function _afterExecute(
- uint256 /* proposalId */,
- address[] memory /* targets */,
- uint256[] memory /* values */,
- bytes[] memory /* calldatas */,
- bytes32 /*descriptionHash*/
- ) internal virtual {
- if (_executor() != address(this)) {
- if (!_governanceCall.empty()) {
- _governanceCall.clear();
- }
- }
- }
- /**
- * @dev 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.
- *
- * Emits a {IGovernor-ProposalCanceled} event.
- */
- function _cancel(
- address[] memory targets,
- uint256[] memory values,
- bytes[] memory calldatas,
- bytes32 descriptionHash
- ) internal virtual returns (uint256) {
- uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
- ProposalState currentState = state(proposalId);
- if (
- currentState == ProposalState.Canceled ||
- currentState == ProposalState.Expired ||
- currentState == ProposalState.Executed
- ) {
- uint256 maxProposalState = uint256(type(ProposalState).max); // All proposal states
- bytes32 mask = bytes32(uint256(2 ** maxProposalState - 1)); // 0x...1111
- bytes32 forbiddenStates = _encodeState(ProposalState.Canceled) |
- _encodeState(ProposalState.Expired) |
- _encodeState(ProposalState.Executed);
- revert GovernorIncorrectState(proposalId, currentState, mask ^ forbiddenStates);
- }
- _proposals[proposalId].canceled = true;
- emit ProposalCanceled(proposalId);
- return proposalId;
- }
- /**
- * @dev See {IGovernor-getVotes}.
- */
- function getVotes(address account, uint256 timepoint) public view virtual override returns (uint256) {
- return _getVotes(account, timepoint, _defaultParams());
- }
- /**
- * @dev See {IGovernor-getVotesWithParams}.
- */
- function getVotesWithParams(
- address account,
- uint256 timepoint,
- bytes memory params
- ) public view virtual override returns (uint256) {
- return _getVotes(account, timepoint, params);
- }
- /**
- * @dev See {IGovernor-castVote}.
- */
- function castVote(uint256 proposalId, uint8 support) public virtual override returns (uint256) {
- address voter = _msgSender();
- return _castVote(proposalId, voter, support, "");
- }
- /**
- * @dev See {IGovernor-castVoteWithReason}.
- */
- function castVoteWithReason(
- uint256 proposalId,
- uint8 support,
- string calldata reason
- ) public virtual override returns (uint256) {
- address voter = _msgSender();
- return _castVote(proposalId, voter, support, reason);
- }
- /**
- * @dev See {IGovernor-castVoteWithReasonAndParams}.
- */
- function castVoteWithReasonAndParams(
- uint256 proposalId,
- uint8 support,
- string calldata reason,
- bytes memory params
- ) public virtual override returns (uint256) {
- address voter = _msgSender();
- return _castVote(proposalId, voter, support, reason, params);
- }
- /**
- * @dev See {IGovernor-castVoteBySig}.
- */
- function castVoteBySig(
- uint256 proposalId,
- uint8 support,
- uint8 v,
- bytes32 r,
- bytes32 s
- ) public virtual override returns (uint256) {
- address voter = ECDSA.recover(
- _hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))),
- v,
- r,
- s
- );
- return _castVote(proposalId, voter, support, "");
- }
- /**
- * @dev See {IGovernor-castVoteWithReasonAndParamsBySig}.
- */
- function castVoteWithReasonAndParamsBySig(
- uint256 proposalId,
- uint8 support,
- string calldata reason,
- bytes memory params,
- uint8 v,
- bytes32 r,
- bytes32 s
- ) public virtual override returns (uint256) {
- address voter = ECDSA.recover(
- _hashTypedDataV4(
- keccak256(
- abi.encode(
- EXTENDED_BALLOT_TYPEHASH,
- proposalId,
- support,
- keccak256(bytes(reason)),
- keccak256(params)
- )
- )
- ),
- v,
- r,
- s
- );
- return _castVote(proposalId, voter, support, reason, params);
- }
- /**
- * @dev 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.
- */
- function _castVote(
- uint256 proposalId,
- address account,
- uint8 support,
- string memory reason
- ) internal virtual returns (uint256) {
- return _castVote(proposalId, account, support, reason, _defaultParams());
- }
- /**
- * @dev 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.
- */
- function _castVote(
- uint256 proposalId,
- address account,
- uint8 support,
- string memory reason,
- bytes memory params
- ) internal virtual returns (uint256) {
- ProposalCore storage proposal = _proposals[proposalId];
- ProposalState currentState = state(proposalId);
- if (currentState != ProposalState.Active) {
- revert GovernorIncorrectState(proposalId, currentState, _encodeState(ProposalState.Active));
- }
- uint256 weight = _getVotes(account, proposal.voteStart, params);
- _countVote(proposalId, account, support, weight, params);
- if (params.length == 0) {
- emit VoteCast(account, proposalId, support, weight, reason);
- } else {
- emit VoteCastWithParams(account, proposalId, support, weight, reason, params);
- }
- return weight;
- }
- /**
- * @dev 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.
- */
- function relay(address target, uint256 value, bytes calldata data) external payable virtual onlyGovernance {
- (bool success, bytes memory returndata) = target.call{value: value}(data);
- Address.verifyCallResult(success, returndata, _customGovernorRevert);
- }
- /**
- * @dev Address through which the governor executes action. Will be overloaded by module that execute actions
- * through another contract such as a timelock.
- */
- function _executor() internal view virtual returns (address) {
- return address(this);
- }
- /**
- * @dev See {IERC721Receiver-onERC721Received}.
- */
- function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) {
- return this.onERC721Received.selector;
- }
- /**
- * @dev See {IERC1155Receiver-onERC1155Received}.
- */
- function onERC1155Received(
- address,
- address,
- uint256,
- uint256,
- bytes memory
- ) public virtual override returns (bytes4) {
- return this.onERC1155Received.selector;
- }
- /**
- * @dev See {IERC1155Receiver-onERC1155BatchReceived}.
- */
- function onERC1155BatchReceived(
- address,
- address,
- uint256[] memory,
- uint256[] memory,
- bytes memory
- ) public virtual override returns (bytes4) {
- return this.onERC1155BatchReceived.selector;
- }
- /**
- * @dev 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
- */
- function _encodeState(ProposalState proposalState) internal pure returns (bytes32) {
- return bytes32(1 << uint8(proposalState));
- }
- /**
- * @dev Default revert function for failed executed functions without any other bubbled up reason.
- */
- function _customGovernorRevert() internal pure {
- revert GovernorFailedCall();
- }
- }
|