Governor.sol 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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. struct ProposalCore {
  30. Timers.BlockNumber voteStart;
  31. Timers.BlockNumber voteEnd;
  32. bool executed;
  33. bool canceled;
  34. }
  35. string private _name;
  36. mapping(uint256 => ProposalCore) private _proposals;
  37. // This queue keeps track of the governor operating on itself. Calls to functions protected by the
  38. // {onlyGovernance} modifier needs to be whitelisted in this queue. Whitelisting is set in {_beforeExecute},
  39. // consummed by the {onlyGovernance} modifier and eventually reset in {_afterExecute}. This ensures that the
  40. // execution of {onlyGovernance} protected calls can only be achieved through successful proposals.
  41. DoubleEndedQueue.Bytes32Deque private _governanceCall;
  42. /**
  43. * @dev Restricts a function so it can only be executed through governance proposals. For example, governance
  44. * parameter setters in {GovernorSettings} are protected using this modifier.
  45. *
  46. * The governance executing address may be different from the Governor's own address, for example it could be a
  47. * timelock. This can be customized by modules by overriding {_executor}. The executor is only able to invoke these
  48. * functions during the execution of the governor's {execute} function, and not under any other circumstances. Thus,
  49. * for example, additional timelock proposers are not able to change governance parameters without going through the
  50. * governance protocol (since v4.6).
  51. */
  52. modifier onlyGovernance() {
  53. require(_msgSender() == _executor(), "Governor: onlyGovernance");
  54. if (_executor() != address(this)) {
  55. bytes32 msgDataHash = keccak256(_msgData());
  56. // loop until poping the expected operation - throw if deque is empty (operation not authorized)
  57. while (_governanceCall.popFront() != msgDataHash) {}
  58. }
  59. _;
  60. }
  61. /**
  62. * @dev Sets the value for {name} and {version}
  63. */
  64. constructor(string memory name_) EIP712(name_, version()) {
  65. _name = name_;
  66. }
  67. /**
  68. * @dev Function to receive ETH that will be handled by the governor (disabled if executor is a third party contract)
  69. */
  70. receive() external payable virtual {
  71. require(_executor() == address(this));
  72. }
  73. /**
  74. * @dev See {IERC165-supportsInterface}.
  75. */
  76. function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
  77. return interfaceId == type(IGovernor).interfaceId || super.supportsInterface(interfaceId);
  78. }
  79. /**
  80. * @dev See {IGovernor-name}.
  81. */
  82. function name() public view virtual override returns (string memory) {
  83. return _name;
  84. }
  85. /**
  86. * @dev See {IGovernor-version}.
  87. */
  88. function version() public view virtual override returns (string memory) {
  89. return "1";
  90. }
  91. /**
  92. * @dev See {IGovernor-hashProposal}.
  93. *
  94. * The proposal id is produced by hashing the RLC encoded `targets` array, the `values` array, the `calldatas` array
  95. * and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id
  96. * can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in
  97. * advance, before the proposal is submitted.
  98. *
  99. * Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the
  100. * same proposal (with same operation and same description) will have the same id if submitted on multiple governors
  101. * accross multiple networks. This also means that in order to execute the same operation twice (on the same
  102. * governor) the proposer will have to change the description in order to avoid proposal id conflicts.
  103. */
  104. function hashProposal(
  105. address[] memory targets,
  106. uint256[] memory values,
  107. bytes[] memory calldatas,
  108. bytes32 descriptionHash
  109. ) public pure virtual override returns (uint256) {
  110. return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash)));
  111. }
  112. /**
  113. * @dev See {IGovernor-state}.
  114. */
  115. function state(uint256 proposalId) public view virtual override returns (ProposalState) {
  116. ProposalCore storage proposal = _proposals[proposalId];
  117. if (proposal.executed) {
  118. return ProposalState.Executed;
  119. }
  120. if (proposal.canceled) {
  121. return ProposalState.Canceled;
  122. }
  123. uint256 snapshot = proposalSnapshot(proposalId);
  124. if (snapshot == 0) {
  125. revert("Governor: unknown proposal id");
  126. }
  127. if (snapshot >= block.number) {
  128. return ProposalState.Pending;
  129. }
  130. uint256 deadline = proposalDeadline(proposalId);
  131. if (deadline >= block.number) {
  132. return ProposalState.Active;
  133. }
  134. if (_quorumReached(proposalId) && _voteSucceeded(proposalId)) {
  135. return ProposalState.Succeeded;
  136. } else {
  137. return ProposalState.Defeated;
  138. }
  139. }
  140. /**
  141. * @dev See {IGovernor-proposalSnapshot}.
  142. */
  143. function proposalSnapshot(uint256 proposalId) public view virtual override returns (uint256) {
  144. return _proposals[proposalId].voteStart.getDeadline();
  145. }
  146. /**
  147. * @dev See {IGovernor-proposalDeadline}.
  148. */
  149. function proposalDeadline(uint256 proposalId) public view virtual override returns (uint256) {
  150. return _proposals[proposalId].voteEnd.getDeadline();
  151. }
  152. /**
  153. * @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_.
  154. */
  155. function proposalThreshold() public view virtual returns (uint256) {
  156. return 0;
  157. }
  158. /**
  159. * @dev Amount of votes already cast passes the threshold limit.
  160. */
  161. function _quorumReached(uint256 proposalId) internal view virtual returns (bool);
  162. /**
  163. * @dev Is the proposal successful or not.
  164. */
  165. function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool);
  166. /**
  167. * @dev Register a vote with a given support and voting weight.
  168. *
  169. * Note: Support is generic and can represent various things depending on the voting system used.
  170. */
  171. function _countVote(
  172. uint256 proposalId,
  173. address account,
  174. uint8 support,
  175. uint256 weight
  176. ) internal virtual;
  177. /**
  178. * @dev See {IGovernor-propose}.
  179. */
  180. function propose(
  181. address[] memory targets,
  182. uint256[] memory values,
  183. bytes[] memory calldatas,
  184. string memory description
  185. ) public virtual override returns (uint256) {
  186. require(
  187. getVotes(_msgSender(), block.number - 1) >= proposalThreshold(),
  188. "GovernorCompatibilityBravo: proposer votes below proposal threshold"
  189. );
  190. uint256 proposalId = hashProposal(targets, values, calldatas, keccak256(bytes(description)));
  191. require(targets.length == values.length, "Governor: invalid proposal length");
  192. require(targets.length == calldatas.length, "Governor: invalid proposal length");
  193. require(targets.length > 0, "Governor: empty proposal");
  194. ProposalCore storage proposal = _proposals[proposalId];
  195. require(proposal.voteStart.isUnset(), "Governor: proposal already exists");
  196. uint64 snapshot = block.number.toUint64() + votingDelay().toUint64();
  197. uint64 deadline = snapshot + votingPeriod().toUint64();
  198. proposal.voteStart.setDeadline(snapshot);
  199. proposal.voteEnd.setDeadline(deadline);
  200. emit ProposalCreated(
  201. proposalId,
  202. _msgSender(),
  203. targets,
  204. values,
  205. new string[](targets.length),
  206. calldatas,
  207. snapshot,
  208. deadline,
  209. description
  210. );
  211. return proposalId;
  212. }
  213. /**
  214. * @dev See {IGovernor-execute}.
  215. */
  216. function execute(
  217. address[] memory targets,
  218. uint256[] memory values,
  219. bytes[] memory calldatas,
  220. bytes32 descriptionHash
  221. ) public payable virtual override returns (uint256) {
  222. uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
  223. ProposalState status = state(proposalId);
  224. require(
  225. status == ProposalState.Succeeded || status == ProposalState.Queued,
  226. "Governor: proposal not successful"
  227. );
  228. _proposals[proposalId].executed = true;
  229. emit ProposalExecuted(proposalId);
  230. _beforeExecute(proposalId, targets, values, calldatas, descriptionHash);
  231. _execute(proposalId, targets, values, calldatas, descriptionHash);
  232. _afterExecute(proposalId, targets, values, calldatas, descriptionHash);
  233. return proposalId;
  234. }
  235. /**
  236. * @dev Internal execution mechanism. Can be overriden to implement different execution mechanism
  237. */
  238. function _execute(
  239. uint256, /* proposalId */
  240. address[] memory targets,
  241. uint256[] memory values,
  242. bytes[] memory calldatas,
  243. bytes32 /*descriptionHash*/
  244. ) internal virtual {
  245. string memory errorMessage = "Governor: call reverted without message";
  246. for (uint256 i = 0; i < targets.length; ++i) {
  247. (bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]);
  248. Address.verifyCallResult(success, returndata, errorMessage);
  249. }
  250. }
  251. /**
  252. * @dev Hook before execution is trigerred.
  253. */
  254. function _beforeExecute(
  255. uint256, /* proposalId */
  256. address[] memory targets,
  257. uint256[] memory, /* values */
  258. bytes[] memory calldatas,
  259. bytes32 /*descriptionHash*/
  260. ) internal virtual {
  261. if (_executor() != address(this)) {
  262. for (uint256 i = 0; i < targets.length; ++i) {
  263. if (targets[i] == address(this)) {
  264. _governanceCall.pushBack(keccak256(calldatas[i]));
  265. }
  266. }
  267. }
  268. }
  269. /**
  270. * @dev Hook after execution is trigerred.
  271. */
  272. function _afterExecute(
  273. uint256, /* proposalId */
  274. address[] memory, /* targets */
  275. uint256[] memory, /* values */
  276. bytes[] memory, /* calldatas */
  277. bytes32 /*descriptionHash*/
  278. ) internal virtual {
  279. if (_executor() != address(this)) {
  280. if (!_governanceCall.empty()) {
  281. _governanceCall.clear();
  282. }
  283. }
  284. }
  285. /**
  286. * @dev Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as
  287. * canceled to allow distinguishing it from executed proposals.
  288. *
  289. * Emits a {IGovernor-ProposalCanceled} event.
  290. */
  291. function _cancel(
  292. address[] memory targets,
  293. uint256[] memory values,
  294. bytes[] memory calldatas,
  295. bytes32 descriptionHash
  296. ) internal virtual returns (uint256) {
  297. uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
  298. ProposalState status = state(proposalId);
  299. require(
  300. status != ProposalState.Canceled && status != ProposalState.Expired && status != ProposalState.Executed,
  301. "Governor: proposal not active"
  302. );
  303. _proposals[proposalId].canceled = true;
  304. emit ProposalCanceled(proposalId);
  305. return proposalId;
  306. }
  307. /**
  308. * @dev See {IGovernor-castVote}.
  309. */
  310. function castVote(uint256 proposalId, uint8 support) public virtual override returns (uint256) {
  311. address voter = _msgSender();
  312. return _castVote(proposalId, voter, support, "");
  313. }
  314. /**
  315. * @dev See {IGovernor-castVoteWithReason}.
  316. */
  317. function castVoteWithReason(
  318. uint256 proposalId,
  319. uint8 support,
  320. string calldata reason
  321. ) public virtual override returns (uint256) {
  322. address voter = _msgSender();
  323. return _castVote(proposalId, voter, support, reason);
  324. }
  325. /**
  326. * @dev See {IGovernor-castVoteBySig}.
  327. */
  328. function castVoteBySig(
  329. uint256 proposalId,
  330. uint8 support,
  331. uint8 v,
  332. bytes32 r,
  333. bytes32 s
  334. ) public virtual override returns (uint256) {
  335. address voter = ECDSA.recover(
  336. _hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))),
  337. v,
  338. r,
  339. s
  340. );
  341. return _castVote(proposalId, voter, support, "");
  342. }
  343. /**
  344. * @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
  345. * voting weight using {IGovernor-getVotes} and call the {_countVote} internal function.
  346. *
  347. * Emits a {IGovernor-VoteCast} event.
  348. */
  349. function _castVote(
  350. uint256 proposalId,
  351. address account,
  352. uint8 support,
  353. string memory reason
  354. ) internal virtual returns (uint256) {
  355. ProposalCore storage proposal = _proposals[proposalId];
  356. require(state(proposalId) == ProposalState.Active, "Governor: vote not currently active");
  357. uint256 weight = getVotes(account, proposal.voteStart.getDeadline());
  358. _countVote(proposalId, account, support, weight);
  359. emit VoteCast(account, proposalId, support, weight, reason);
  360. return weight;
  361. }
  362. /**
  363. * @dev Relays a transaction or function call to an arbitrary target. In cases where the governance executor
  364. * is some contract other than the governor itself, like when using a timelock, this function can be invoked
  365. * in a governance proposal to recover tokens or Ether that was sent to the governor contract by mistake.
  366. * Note that if the executor is simply the governor itself, use of `relay` is redundant.
  367. */
  368. function relay(
  369. address target,
  370. uint256 value,
  371. bytes calldata data
  372. ) external virtual onlyGovernance {
  373. Address.functionCallWithValue(target, data, value);
  374. }
  375. /**
  376. * @dev Address through which the governor executes action. Will be overloaded by module that execute actions
  377. * through another contract such as a timelock.
  378. */
  379. function _executor() internal view virtual returns (address) {
  380. return address(this);
  381. }
  382. }