Governor.sol 22 KB

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