Governor.sol 19 KB

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