Governor.sol 22 KB

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