Governor.sol 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.8.0) (governance/Governor.sol)
  3. pragma solidity ^0.8.0;
  4. import "../token/ERC721/IERC721Receiver.sol";
  5. import "../token/ERC1155/IERC1155Receiver.sol";
  6. import "../utils/cryptography/ECDSA.sol";
  7. import "../utils/cryptography/EIP712.sol";
  8. import "../utils/introspection/ERC165.sol";
  9. import "../utils/math/SafeCast.sol";
  10. import "../utils/structs/DoubleEndedQueue.sol";
  11. import "../utils/Address.sol";
  12. import "../utils/Context.sol";
  13. import "../utils/Timers.sol";
  14. import "./IGovernor.sol";
  15. /**
  16. * @dev Core of the governance system, designed to be extended though various modules.
  17. *
  18. * This contract is abstract and requires several function to be implemented in various modules:
  19. *
  20. * - A counting module must implement {quorum}, {_quorumReached}, {_voteSucceeded} and {_countVote}
  21. * - A voting module must implement {_getVotes}
  22. * - Additionally, the {votingPeriod} must also be implemented
  23. *
  24. * _Available since v4.3._
  25. */
  26. abstract contract Governor is Context, ERC165, EIP712, IGovernor, IERC721Receiver, IERC1155Receiver {
  27. using DoubleEndedQueue for DoubleEndedQueue.Bytes32Deque;
  28. using SafeCast for uint256;
  29. using Timers for Timers.BlockNumber;
  30. bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)");
  31. bytes32 public constant EXTENDED_BALLOT_TYPEHASH =
  32. keccak256("ExtendedBallot(uint256 proposalId,uint8 support,string reason,bytes params)");
  33. struct ProposalCore {
  34. Timers.BlockNumber voteStart;
  35. Timers.BlockNumber voteEnd;
  36. bool executed;
  37. bool canceled;
  38. address proposer;
  39. }
  40. string private _name;
  41. mapping(uint256 => ProposalCore) private _proposals;
  42. // This queue keeps track of the governor operating on itself. Calls to functions protected by the
  43. // {onlyGovernance} modifier needs to be whitelisted in this queue. Whitelisting is set in {_beforeExecute},
  44. // consumed by the {onlyGovernance} modifier and eventually reset in {_afterExecute}. This ensures that the
  45. // execution of {onlyGovernance} protected calls can only be achieved through successful proposals.
  46. DoubleEndedQueue.Bytes32Deque private _governanceCall;
  47. /**
  48. * @dev Restricts a function so it can only be executed through governance proposals. For example, governance
  49. * parameter setters in {GovernorSettings} are protected using this modifier.
  50. *
  51. * The governance executing address may be different from the Governor's own address, for example it could be a
  52. * timelock. This can be customized by modules by overriding {_executor}. The executor is only able to invoke these
  53. * functions during the execution of the governor's {execute} function, and not under any other circumstances. Thus,
  54. * for example, additional timelock proposers are not able to change governance parameters without going through the
  55. * governance protocol (since v4.6).
  56. */
  57. modifier onlyGovernance() {
  58. require(_msgSender() == _executor(), "Governor: onlyGovernance");
  59. if (_executor() != address(this)) {
  60. bytes32 msgDataHash = keccak256(_msgData());
  61. // loop until popping the expected operation - throw if deque is empty (operation not authorized)
  62. while (_governanceCall.popFront() != msgDataHash) {}
  63. }
  64. _;
  65. }
  66. /**
  67. * @dev Sets the value for {name} and {version}
  68. */
  69. constructor(string memory name_) EIP712(name_, version()) {
  70. _name = name_;
  71. }
  72. /**
  73. * @dev Function to receive ETH that will be handled by the governor (disabled if executor is a third party contract)
  74. */
  75. receive() external payable virtual {
  76. require(_executor() == address(this));
  77. }
  78. /**
  79. * @dev See {IERC165-supportsInterface}.
  80. */
  81. function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
  82. // In addition to the current interfaceId, also support previous version of the interfaceId that did not
  83. // include the castVoteWithReasonAndParams() function as standard
  84. return
  85. interfaceId ==
  86. (type(IGovernor).interfaceId ^
  87. this.cancel.selector ^
  88. this.castVoteWithReasonAndParams.selector ^
  89. this.castVoteWithReasonAndParamsBySig.selector ^
  90. this.getVotesWithParams.selector) ||
  91. interfaceId == (type(IGovernor).interfaceId ^ this.cancel.selector) ||
  92. interfaceId == type(IGovernor).interfaceId ||
  93. interfaceId == type(IERC1155Receiver).interfaceId ||
  94. super.supportsInterface(interfaceId);
  95. }
  96. /**
  97. * @dev See {IGovernor-name}.
  98. */
  99. function name() public view virtual override returns (string memory) {
  100. return _name;
  101. }
  102. /**
  103. * @dev See {IGovernor-version}.
  104. */
  105. function version() public view virtual override returns (string memory) {
  106. return "1";
  107. }
  108. /**
  109. * @dev See {IGovernor-hashProposal}.
  110. *
  111. * The proposal id is produced by hashing the ABI encoded `targets` array, the `values` array, the `calldatas` array
  112. * and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id
  113. * can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in
  114. * advance, before the proposal is submitted.
  115. *
  116. * Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the
  117. * same proposal (with same operation and same description) will have the same id if submitted on multiple governors
  118. * across multiple networks. This also means that in order to execute the same operation twice (on the same
  119. * governor) the proposer will have to change the description in order to avoid proposal id conflicts.
  120. */
  121. function hashProposal(
  122. address[] memory targets,
  123. uint256[] memory values,
  124. bytes[] memory calldatas,
  125. bytes32 descriptionHash
  126. ) public pure virtual override returns (uint256) {
  127. return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash)));
  128. }
  129. /**
  130. * @dev See {IGovernor-state}.
  131. */
  132. function state(uint256 proposalId) public view virtual override returns (ProposalState) {
  133. ProposalCore storage proposal = _proposals[proposalId];
  134. if (proposal.executed) {
  135. return ProposalState.Executed;
  136. }
  137. if (proposal.canceled) {
  138. return ProposalState.Canceled;
  139. }
  140. uint256 snapshot = proposalSnapshot(proposalId);
  141. if (snapshot == 0) {
  142. revert("Governor: unknown proposal id");
  143. }
  144. if (snapshot >= block.number) {
  145. return ProposalState.Pending;
  146. }
  147. uint256 deadline = proposalDeadline(proposalId);
  148. if (deadline >= block.number) {
  149. return ProposalState.Active;
  150. }
  151. if (_quorumReached(proposalId) && _voteSucceeded(proposalId)) {
  152. return ProposalState.Succeeded;
  153. } else {
  154. return ProposalState.Defeated;
  155. }
  156. }
  157. /**
  158. * @dev See {IGovernor-proposalSnapshot}.
  159. */
  160. function proposalSnapshot(uint256 proposalId) public view virtual override returns (uint256) {
  161. return _proposals[proposalId].voteStart.getDeadline();
  162. }
  163. /**
  164. * @dev See {IGovernor-proposalDeadline}.
  165. */
  166. function proposalDeadline(uint256 proposalId) public view virtual override returns (uint256) {
  167. return _proposals[proposalId].voteEnd.getDeadline();
  168. }
  169. /**
  170. * @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_.
  171. */
  172. function proposalThreshold() public view virtual returns (uint256) {
  173. return 0;
  174. }
  175. /**
  176. * @dev Amount of votes already cast passes the threshold limit.
  177. */
  178. function _quorumReached(uint256 proposalId) internal view virtual returns (bool);
  179. /**
  180. * @dev Is the proposal successful or not.
  181. */
  182. function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool);
  183. /**
  184. * @dev Get the voting weight of `account` at a specific `blockNumber`, for a vote as described by `params`.
  185. */
  186. function _getVotes(
  187. address account,
  188. uint256 blockNumber,
  189. bytes memory params
  190. ) internal view virtual returns (uint256);
  191. /**
  192. * @dev Register a vote for `proposalId` by `account` with a given `support`, voting `weight` and voting `params`.
  193. *
  194. * Note: Support is generic and can represent various things depending on the voting system used.
  195. */
  196. function _countVote(
  197. uint256 proposalId,
  198. address account,
  199. uint8 support,
  200. uint256 weight,
  201. bytes memory params
  202. ) internal virtual;
  203. /**
  204. * @dev Default additional encoded parameters used by castVote methods that don't include them
  205. *
  206. * Note: Should be overridden by specific implementations to use an appropriate value, the
  207. * meaning of the additional params, in the context of that implementation
  208. */
  209. function _defaultParams() internal view virtual returns (bytes memory) {
  210. return "";
  211. }
  212. /**
  213. * @dev See {IGovernor-propose}.
  214. */
  215. function propose(
  216. address[] memory targets,
  217. uint256[] memory values,
  218. bytes[] memory calldatas,
  219. string memory description
  220. ) public virtual override returns (uint256) {
  221. address proposer = _msgSender();
  222. require(
  223. getVotes(proposer, block.number - 1) >= proposalThreshold(),
  224. "Governor: proposer votes below proposal threshold"
  225. );
  226. uint256 proposalId = hashProposal(targets, values, calldatas, keccak256(bytes(description)));
  227. require(targets.length == values.length, "Governor: invalid proposal length");
  228. require(targets.length == calldatas.length, "Governor: invalid proposal length");
  229. require(targets.length > 0, "Governor: empty proposal");
  230. ProposalCore storage proposal = _proposals[proposalId];
  231. require(proposal.voteStart.isUnset(), "Governor: proposal already exists");
  232. uint64 snapshot = block.number.toUint64() + votingDelay().toUint64();
  233. uint64 deadline = snapshot + votingPeriod().toUint64();
  234. proposal.voteStart.setDeadline(snapshot);
  235. proposal.voteEnd.setDeadline(deadline);
  236. proposal.proposer = proposer;
  237. emit ProposalCreated(
  238. proposalId,
  239. proposer,
  240. targets,
  241. values,
  242. new string[](targets.length),
  243. calldatas,
  244. snapshot,
  245. deadline,
  246. description
  247. );
  248. return proposalId;
  249. }
  250. /**
  251. * @dev See {IGovernor-execute}.
  252. */
  253. function execute(
  254. address[] memory targets,
  255. uint256[] memory values,
  256. bytes[] memory calldatas,
  257. bytes32 descriptionHash
  258. ) public payable virtual override returns (uint256) {
  259. uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
  260. ProposalState status = state(proposalId);
  261. require(
  262. status == ProposalState.Succeeded || status == ProposalState.Queued,
  263. "Governor: proposal not successful"
  264. );
  265. _proposals[proposalId].executed = true;
  266. emit ProposalExecuted(proposalId);
  267. _beforeExecute(proposalId, targets, values, calldatas, descriptionHash);
  268. _execute(proposalId, targets, values, calldatas, descriptionHash);
  269. _afterExecute(proposalId, targets, values, calldatas, descriptionHash);
  270. return proposalId;
  271. }
  272. /**
  273. * @dev See {IGovernor-cancel}.
  274. */
  275. function cancel(uint256 proposalId) public virtual override {
  276. require(state(proposalId) == ProposalState.Pending, "Governor: too late to cancel");
  277. require(_msgSender() == _proposals[proposalId].proposer, "Governor: only proposer can cancel");
  278. _cancel(proposalId);
  279. }
  280. /**
  281. * @dev Internal execution mechanism. Can be overridden to implement different execution mechanism
  282. */
  283. function _execute(
  284. uint256 /* proposalId */,
  285. address[] memory targets,
  286. uint256[] memory values,
  287. bytes[] memory calldatas,
  288. bytes32 /*descriptionHash*/
  289. ) internal virtual {
  290. string memory errorMessage = "Governor: call reverted without message";
  291. for (uint256 i = 0; i < targets.length; ++i) {
  292. (bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]);
  293. Address.verifyCallResult(success, returndata, errorMessage);
  294. }
  295. }
  296. /**
  297. * @dev Hook before execution is triggered.
  298. */
  299. function _beforeExecute(
  300. uint256 /* proposalId */,
  301. address[] memory targets,
  302. uint256[] memory /* values */,
  303. bytes[] memory calldatas,
  304. bytes32 /*descriptionHash*/
  305. ) internal virtual {
  306. if (_executor() != address(this)) {
  307. for (uint256 i = 0; i < targets.length; ++i) {
  308. if (targets[i] == address(this)) {
  309. _governanceCall.pushBack(keccak256(calldatas[i]));
  310. }
  311. }
  312. }
  313. }
  314. /**
  315. * @dev Hook after execution is triggered.
  316. */
  317. function _afterExecute(
  318. uint256 /* proposalId */,
  319. address[] memory /* targets */,
  320. uint256[] memory /* values */,
  321. bytes[] memory /* calldatas */,
  322. bytes32 /*descriptionHash*/
  323. ) internal virtual {
  324. if (_executor() != address(this)) {
  325. if (!_governanceCall.empty()) {
  326. _governanceCall.clear();
  327. }
  328. }
  329. }
  330. /**
  331. * @dev Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as
  332. * canceled to allow distinguishing it from executed proposals.
  333. *
  334. * Emits a {IGovernor-ProposalCanceled} event.
  335. */
  336. function _cancel(
  337. address[] memory targets,
  338. uint256[] memory values,
  339. bytes[] memory calldatas,
  340. bytes32 descriptionHash
  341. ) internal virtual returns (uint256) {
  342. return _cancel(hashProposal(targets, values, calldatas, descriptionHash));
  343. }
  344. /**
  345. * @dev Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as
  346. * canceled to allow distinguishing it from executed proposals.
  347. *
  348. * Emits a {IGovernor-ProposalCanceled} event.
  349. */
  350. function _cancel(uint256 proposalId) internal virtual returns (uint256) {
  351. ProposalState status = state(proposalId);
  352. require(
  353. status != ProposalState.Canceled && status != ProposalState.Expired && status != ProposalState.Executed,
  354. "Governor: proposal not active"
  355. );
  356. _proposals[proposalId].canceled = true;
  357. emit ProposalCanceled(proposalId);
  358. return proposalId;
  359. }
  360. /**
  361. * @dev See {IGovernor-getVotes}.
  362. */
  363. function getVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) {
  364. return _getVotes(account, blockNumber, _defaultParams());
  365. }
  366. /**
  367. * @dev See {IGovernor-getVotesWithParams}.
  368. */
  369. function getVotesWithParams(
  370. address account,
  371. uint256 blockNumber,
  372. bytes memory params
  373. ) public view virtual override returns (uint256) {
  374. return _getVotes(account, blockNumber, params);
  375. }
  376. /**
  377. * @dev See {IGovernor-castVote}.
  378. */
  379. function castVote(uint256 proposalId, uint8 support) public virtual override returns (uint256) {
  380. address voter = _msgSender();
  381. return _castVote(proposalId, voter, support, "");
  382. }
  383. /**
  384. * @dev See {IGovernor-castVoteWithReason}.
  385. */
  386. function castVoteWithReason(
  387. uint256 proposalId,
  388. uint8 support,
  389. string calldata reason
  390. ) public virtual override returns (uint256) {
  391. address voter = _msgSender();
  392. return _castVote(proposalId, voter, support, reason);
  393. }
  394. /**
  395. * @dev See {IGovernor-castVoteWithReasonAndParams}.
  396. */
  397. function castVoteWithReasonAndParams(
  398. uint256 proposalId,
  399. uint8 support,
  400. string calldata reason,
  401. bytes memory params
  402. ) public virtual override returns (uint256) {
  403. address voter = _msgSender();
  404. return _castVote(proposalId, voter, support, reason, params);
  405. }
  406. /**
  407. * @dev See {IGovernor-castVoteBySig}.
  408. */
  409. function castVoteBySig(
  410. uint256 proposalId,
  411. uint8 support,
  412. uint8 v,
  413. bytes32 r,
  414. bytes32 s
  415. ) public virtual override returns (uint256) {
  416. address voter = ECDSA.recover(
  417. _hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))),
  418. v,
  419. r,
  420. s
  421. );
  422. return _castVote(proposalId, voter, support, "");
  423. }
  424. /**
  425. * @dev See {IGovernor-castVoteWithReasonAndParamsBySig}.
  426. */
  427. function castVoteWithReasonAndParamsBySig(
  428. uint256 proposalId,
  429. uint8 support,
  430. string calldata reason,
  431. bytes memory params,
  432. uint8 v,
  433. bytes32 r,
  434. bytes32 s
  435. ) public virtual override returns (uint256) {
  436. address voter = ECDSA.recover(
  437. _hashTypedDataV4(
  438. keccak256(
  439. abi.encode(
  440. EXTENDED_BALLOT_TYPEHASH,
  441. proposalId,
  442. support,
  443. keccak256(bytes(reason)),
  444. keccak256(params)
  445. )
  446. )
  447. ),
  448. v,
  449. r,
  450. s
  451. );
  452. return _castVote(proposalId, voter, support, reason, params);
  453. }
  454. /**
  455. * @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
  456. * voting weight using {IGovernor-getVotes} and call the {_countVote} internal function. Uses the _defaultParams().
  457. *
  458. * Emits a {IGovernor-VoteCast} event.
  459. */
  460. function _castVote(
  461. uint256 proposalId,
  462. address account,
  463. uint8 support,
  464. string memory reason
  465. ) internal virtual returns (uint256) {
  466. return _castVote(proposalId, account, support, reason, _defaultParams());
  467. }
  468. /**
  469. * @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
  470. * voting weight using {IGovernor-getVotes} and call the {_countVote} internal function.
  471. *
  472. * Emits a {IGovernor-VoteCast} event.
  473. */
  474. function _castVote(
  475. uint256 proposalId,
  476. address account,
  477. uint8 support,
  478. string memory reason,
  479. bytes memory params
  480. ) internal virtual returns (uint256) {
  481. ProposalCore storage proposal = _proposals[proposalId];
  482. require(state(proposalId) == ProposalState.Active, "Governor: vote not currently active");
  483. uint256 weight = _getVotes(account, proposal.voteStart.getDeadline(), params);
  484. _countVote(proposalId, account, support, weight, params);
  485. if (params.length == 0) {
  486. emit VoteCast(account, proposalId, support, weight, reason);
  487. } else {
  488. emit VoteCastWithParams(account, proposalId, support, weight, reason, params);
  489. }
  490. return weight;
  491. }
  492. /**
  493. * @dev Relays a transaction or function call to an arbitrary target. In cases where the governance executor
  494. * is some contract other than the governor itself, like when using a timelock, this function can be invoked
  495. * in a governance proposal to recover tokens or Ether that was sent to the governor contract by mistake.
  496. * Note that if the executor is simply the governor itself, use of `relay` is redundant.
  497. */
  498. function relay(address target, uint256 value, bytes calldata data) external payable virtual onlyGovernance {
  499. (bool success, bytes memory returndata) = target.call{value: value}(data);
  500. Address.verifyCallResult(success, returndata, "Governor: relay reverted without message");
  501. }
  502. /**
  503. * @dev Address through which the governor executes action. Will be overloaded by module that execute actions
  504. * through another contract such as a timelock.
  505. */
  506. function _executor() internal view virtual returns (address) {
  507. return address(this);
  508. }
  509. /**
  510. * @dev See {IERC721Receiver-onERC721Received}.
  511. */
  512. function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) {
  513. return this.onERC721Received.selector;
  514. }
  515. /**
  516. * @dev See {IERC1155Receiver-onERC1155Received}.
  517. */
  518. function onERC1155Received(
  519. address,
  520. address,
  521. uint256,
  522. uint256,
  523. bytes memory
  524. ) public virtual override returns (bytes4) {
  525. return this.onERC1155Received.selector;
  526. }
  527. /**
  528. * @dev See {IERC1155Receiver-onERC1155BatchReceived}.
  529. */
  530. function onERC1155BatchReceived(
  531. address,
  532. address,
  533. uint256[] memory,
  534. uint256[] memory,
  535. bytes memory
  536. ) public virtual override returns (bytes4) {
  537. return this.onERC1155BatchReceived.selector;
  538. }
  539. }