Governor.sol 20 KB

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