Governor.sol 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.9.1) (governance/Governor.sol)
  3. pragma solidity ^0.8.20;
  4. import {IERC721Receiver} from "../token/ERC721/IERC721Receiver.sol";
  5. import {IERC1155Receiver} from "../token/ERC1155/IERC1155Receiver.sol";
  6. import {EIP712} from "../utils/cryptography/EIP712.sol";
  7. import {SignatureChecker} from "../utils/cryptography/SignatureChecker.sol";
  8. import {IERC165, ERC165} from "../utils/introspection/ERC165.sol";
  9. import {SafeCast} from "../utils/math/SafeCast.sol";
  10. import {DoubleEndedQueue} from "../utils/structs/DoubleEndedQueue.sol";
  11. import {Address} from "../utils/Address.sol";
  12. import {Context} from "../utils/Context.sol";
  13. import {Nonces} from "../utils/Nonces.sol";
  14. import {IGovernor, IERC6372} from "./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 functions 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. * - Additionally, {votingPeriod} must also be implemented
  23. */
  24. abstract contract Governor is Context, ERC165, EIP712, Nonces, IGovernor, IERC721Receiver, IERC1155Receiver {
  25. using DoubleEndedQueue for DoubleEndedQueue.Bytes32Deque;
  26. bytes32 public constant BALLOT_TYPEHASH =
  27. keccak256("Ballot(uint256 proposalId,uint8 support,address voter,uint256 nonce)");
  28. bytes32 public constant EXTENDED_BALLOT_TYPEHASH =
  29. keccak256(
  30. "ExtendedBallot(uint256 proposalId,uint8 support,address voter,uint256 nonce,string reason,bytes params)"
  31. );
  32. struct ProposalCore {
  33. address proposer;
  34. uint48 voteStart;
  35. uint32 voteDuration;
  36. bool executed;
  37. bool canceled;
  38. uint48 eta;
  39. }
  40. bytes32 private constant ALL_PROPOSAL_STATES_BITMAP = bytes32((2 ** (uint8(type(ProposalState).max) + 1)) - 1);
  41. string private _name;
  42. mapping(uint256 proposalId => ProposalCore) private _proposals;
  43. // This queue keeps track of the governor operating on itself. Calls to functions protected by the
  44. // {onlyGovernance} modifier needs to be whitelisted in this queue. Whitelisting is set in {_beforeExecute},
  45. // consumed by the {onlyGovernance} modifier and eventually reset in {_afterExecute}. This ensures that the
  46. // execution of {onlyGovernance} protected calls can only be achieved through successful proposals.
  47. DoubleEndedQueue.Bytes32Deque private _governanceCall;
  48. /**
  49. * @dev Restricts a function so it can only be executed through governance proposals. For example, governance
  50. * parameter setters in {GovernorSettings} are protected using this modifier.
  51. *
  52. * The governance executing address may be different from the Governor's own address, for example it could be a
  53. * timelock. This can be customized by modules by overriding {_executor}. The executor is only able to invoke these
  54. * functions during the execution of the governor's {execute} function, and not under any other circumstances. Thus,
  55. * for example, additional timelock proposers are not able to change governance parameters without going through the
  56. * governance protocol (since v4.6).
  57. */
  58. modifier onlyGovernance() {
  59. _checkGovernance();
  60. _;
  61. }
  62. /**
  63. * @dev Sets the value for {name} and {version}
  64. */
  65. constructor(string memory name_) EIP712(name_, version()) {
  66. _name = name_;
  67. }
  68. /**
  69. * @dev Function to receive ETH that will be handled by the governor (disabled if executor is a third party contract)
  70. */
  71. receive() external payable virtual {
  72. if (_executor() != address(this)) {
  73. revert GovernorDisabledDeposit();
  74. }
  75. }
  76. /**
  77. * @dev See {IERC165-supportsInterface}.
  78. */
  79. function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
  80. return
  81. interfaceId == type(IGovernor).interfaceId ||
  82. interfaceId == type(IERC1155Receiver).interfaceId ||
  83. super.supportsInterface(interfaceId);
  84. }
  85. /**
  86. * @dev See {IGovernor-name}.
  87. */
  88. function name() public view virtual returns (string memory) {
  89. return _name;
  90. }
  91. /**
  92. * @dev See {IGovernor-version}.
  93. */
  94. function version() public view virtual returns (string memory) {
  95. return "1";
  96. }
  97. /**
  98. * @dev See {IGovernor-hashProposal}.
  99. *
  100. * The proposal id is produced by hashing the ABI encoded `targets` array, the `values` array, the `calldatas` array
  101. * and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id
  102. * can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in
  103. * advance, before the proposal is submitted.
  104. *
  105. * Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the
  106. * same proposal (with same operation and same description) will have the same id if submitted on multiple governors
  107. * across multiple networks. This also means that in order to execute the same operation twice (on the same
  108. * governor) the proposer will have to change the description in order to avoid proposal id conflicts.
  109. */
  110. function hashProposal(
  111. address[] memory targets,
  112. uint256[] memory values,
  113. bytes[] memory calldatas,
  114. bytes32 descriptionHash
  115. ) public pure virtual returns (uint256) {
  116. return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash)));
  117. }
  118. /**
  119. * @dev See {IGovernor-state}.
  120. */
  121. function state(uint256 proposalId) public view virtual returns (ProposalState) {
  122. // ProposalCore is just one slot. We can load it from storage to stack with a single sload
  123. ProposalCore storage proposal = _proposals[proposalId];
  124. bool proposalExecuted = proposal.executed;
  125. bool proposalCanceled = proposal.canceled;
  126. if (proposalExecuted) {
  127. return ProposalState.Executed;
  128. }
  129. if (proposalCanceled) {
  130. return ProposalState.Canceled;
  131. }
  132. uint256 snapshot = proposalSnapshot(proposalId);
  133. if (snapshot == 0) {
  134. revert GovernorNonexistentProposal(proposalId);
  135. }
  136. uint256 currentTimepoint = clock();
  137. if (snapshot >= currentTimepoint) {
  138. return ProposalState.Pending;
  139. }
  140. uint256 deadline = proposalDeadline(proposalId);
  141. if (deadline >= currentTimepoint) {
  142. return ProposalState.Active;
  143. } else if (!_quorumReached(proposalId) || !_voteSucceeded(proposalId)) {
  144. return ProposalState.Defeated;
  145. } else if (proposalEta(proposalId) == 0) {
  146. return ProposalState.Succeeded;
  147. } else {
  148. return ProposalState.Queued;
  149. }
  150. }
  151. /**
  152. * @dev See {IGovernor-proposalThreshold}.
  153. */
  154. function proposalThreshold() public view virtual returns (uint256) {
  155. return 0;
  156. }
  157. /**
  158. * @dev See {IGovernor-proposalSnapshot}.
  159. */
  160. function proposalSnapshot(uint256 proposalId) public view virtual returns (uint256) {
  161. return _proposals[proposalId].voteStart;
  162. }
  163. /**
  164. * @dev See {IGovernor-proposalDeadline}.
  165. */
  166. function proposalDeadline(uint256 proposalId) public view virtual returns (uint256) {
  167. return _proposals[proposalId].voteStart + _proposals[proposalId].voteDuration;
  168. }
  169. /**
  170. * @dev See {IGovernor-proposalProposer}.
  171. */
  172. function proposalProposer(uint256 proposalId) public view virtual returns (address) {
  173. return _proposals[proposalId].proposer;
  174. }
  175. /**
  176. * @dev See {IGovernor-proposalEta}.
  177. */
  178. function proposalEta(uint256 proposalId) public view virtual returns (uint256) {
  179. return _proposals[proposalId].eta;
  180. }
  181. /**
  182. * @dev See {IGovernor-proposalNeedsQueuing}.
  183. */
  184. function proposalNeedsQueuing(uint256) public view virtual returns (bool) {
  185. return false;
  186. }
  187. /**
  188. * @dev Reverts if the `msg.sender` is not the executor. In case the executor is not this contract
  189. * itself, the function reverts if `msg.data` is not whitelisted as a result of an {execute}
  190. * operation. See {onlyGovernance}.
  191. */
  192. function _checkGovernance() internal virtual {
  193. if (_executor() != _msgSender()) {
  194. revert GovernorOnlyExecutor(_msgSender());
  195. }
  196. if (_executor() != address(this)) {
  197. bytes32 msgDataHash = keccak256(_msgData());
  198. // loop until popping the expected operation - throw if deque is empty (operation not authorized)
  199. while (_governanceCall.popFront() != msgDataHash) {}
  200. }
  201. }
  202. /**
  203. * @dev Amount of votes already cast passes the threshold limit.
  204. */
  205. function _quorumReached(uint256 proposalId) internal view virtual returns (bool);
  206. /**
  207. * @dev Is the proposal successful or not.
  208. */
  209. function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool);
  210. /**
  211. * @dev Get the voting weight of `account` at a specific `timepoint`, for a vote as described by `params`.
  212. */
  213. function _getVotes(address account, uint256 timepoint, bytes memory params) internal view virtual returns (uint256);
  214. /**
  215. * @dev Register a vote for `proposalId` by `account` with a given `support`, voting `weight` and voting `params`.
  216. *
  217. * Note: Support is generic and can represent various things depending on the voting system used.
  218. */
  219. function _countVote(
  220. uint256 proposalId,
  221. address account,
  222. uint8 support,
  223. uint256 weight,
  224. bytes memory params
  225. ) internal virtual;
  226. /**
  227. * @dev Default additional encoded parameters used by castVote methods that don't include them
  228. *
  229. * Note: Should be overridden by specific implementations to use an appropriate value, the
  230. * meaning of the additional params, in the context of that implementation
  231. */
  232. function _defaultParams() internal view virtual returns (bytes memory) {
  233. return "";
  234. }
  235. /**
  236. * @dev See {IGovernor-propose}. This function has opt-in frontrunning protection, described in {_isValidDescriptionForProposer}.
  237. */
  238. function propose(
  239. address[] memory targets,
  240. uint256[] memory values,
  241. bytes[] memory calldatas,
  242. string memory description
  243. ) public virtual returns (uint256) {
  244. address proposer = _msgSender();
  245. // check description restriction
  246. if (!_isValidDescriptionForProposer(proposer, description)) {
  247. revert GovernorRestrictedProposer(proposer);
  248. }
  249. // check proposal threshold
  250. uint256 proposerVotes = getVotes(proposer, clock() - 1);
  251. uint256 votesThreshold = proposalThreshold();
  252. if (proposerVotes < votesThreshold) {
  253. revert GovernorInsufficientProposerVotes(proposer, proposerVotes, votesThreshold);
  254. }
  255. return _propose(targets, values, calldatas, description, proposer);
  256. }
  257. /**
  258. * @dev Internal propose mechanism. Can be overridden to add more logic on proposal creation.
  259. *
  260. * Emits a {IGovernor-ProposalCreated} event.
  261. */
  262. function _propose(
  263. address[] memory targets,
  264. uint256[] memory values,
  265. bytes[] memory calldatas,
  266. string memory description,
  267. address proposer
  268. ) internal virtual returns (uint256) {
  269. uint256 proposalId = hashProposal(targets, values, calldatas, keccak256(bytes(description)));
  270. if (targets.length != values.length || targets.length != calldatas.length || targets.length == 0) {
  271. revert GovernorInvalidProposalLength(targets.length, calldatas.length, values.length);
  272. }
  273. if (_proposals[proposalId].voteStart != 0) {
  274. revert GovernorUnexpectedProposalState(proposalId, state(proposalId), bytes32(0));
  275. }
  276. uint256 snapshot = clock() + votingDelay();
  277. uint256 duration = votingPeriod();
  278. ProposalCore storage proposal = _proposals[proposalId];
  279. proposal.proposer = proposer;
  280. proposal.voteStart = SafeCast.toUint48(snapshot);
  281. proposal.voteDuration = SafeCast.toUint32(duration);
  282. emit ProposalCreated(
  283. proposalId,
  284. proposer,
  285. targets,
  286. values,
  287. new string[](targets.length),
  288. calldatas,
  289. snapshot,
  290. snapshot + duration,
  291. description
  292. );
  293. return proposalId;
  294. }
  295. /**
  296. * @dev See {IGovernor-queue}.
  297. */
  298. function queue(
  299. address[] memory targets,
  300. uint256[] memory values,
  301. bytes[] memory calldatas,
  302. bytes32 descriptionHash
  303. ) public virtual returns (uint256) {
  304. uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
  305. _validateStateBitmap(proposalId, _encodeStateBitmap(ProposalState.Succeeded));
  306. uint48 eta = _queueOperations(proposalId, targets, values, calldatas, descriptionHash);
  307. if (eta != 0) {
  308. _proposals[proposalId].eta = eta;
  309. emit ProposalQueued(proposalId, eta);
  310. } else {
  311. revert GovernorQueueNotImplemented();
  312. }
  313. return proposalId;
  314. }
  315. /**
  316. * @dev Internal queuing mechanism. Can be overridden (without a super call) to modify the way queuing is
  317. * performed (for example adding a vault/timelock).
  318. *
  319. * This is empty by default, and must be overridden to implement queuing.
  320. *
  321. * This function returns a timestamp that describes the expected eta for execution. If the returned value is 0
  322. * (which is the default value), the core will consider queueing did not succeed, and the public {queue} function
  323. * will revert.
  324. *
  325. * NOTE: Calling this function directly will NOT check the current state of the proposal, or emit the
  326. * `ProposalQueued` event. Queuing a proposal should be done using {queue} or {_queue}.
  327. */
  328. function _queueOperations(
  329. uint256 /*proposalId*/,
  330. address[] memory /*targets*/,
  331. uint256[] memory /*values*/,
  332. bytes[] memory /*calldatas*/,
  333. bytes32 /*descriptionHash*/
  334. ) internal virtual returns (uint48) {
  335. return 0;
  336. }
  337. /**
  338. * @dev See {IGovernor-execute}.
  339. */
  340. function execute(
  341. address[] memory targets,
  342. uint256[] memory values,
  343. bytes[] memory calldatas,
  344. bytes32 descriptionHash
  345. ) public payable virtual returns (uint256) {
  346. uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
  347. _validateStateBitmap(
  348. proposalId,
  349. _encodeStateBitmap(ProposalState.Succeeded) | _encodeStateBitmap(ProposalState.Queued)
  350. );
  351. // mark as executed before calls to avoid reentrancy
  352. _proposals[proposalId].executed = true;
  353. // before execute: register governance call in queue.
  354. if (_executor() != address(this)) {
  355. for (uint256 i = 0; i < targets.length; ++i) {
  356. if (targets[i] == address(this)) {
  357. _governanceCall.pushBack(keccak256(calldatas[i]));
  358. }
  359. }
  360. }
  361. _executeOperations(proposalId, targets, values, calldatas, descriptionHash);
  362. // after execute: cleanup governance call queue.
  363. if (_executor() != address(this) && !_governanceCall.empty()) {
  364. _governanceCall.clear();
  365. }
  366. emit ProposalExecuted(proposalId);
  367. return proposalId;
  368. }
  369. /**
  370. * @dev Internal execution mechanism. Can be overridden (without a super call) to modify the way execution is
  371. * performed (for example adding a vault/timelock).
  372. *
  373. * NOTE: Calling this function directly will NOT check the current state of the proposal, set the executed flag to
  374. * true or emit the `ProposalExecuted` event. Executing a proposal should be done using {execute} or {_execute}.
  375. */
  376. function _executeOperations(
  377. uint256 /* proposalId */,
  378. address[] memory targets,
  379. uint256[] memory values,
  380. bytes[] memory calldatas,
  381. bytes32 /*descriptionHash*/
  382. ) internal virtual {
  383. for (uint256 i = 0; i < targets.length; ++i) {
  384. (bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]);
  385. Address.verifyCallResult(success, returndata);
  386. }
  387. }
  388. /**
  389. * @dev See {IGovernor-cancel}.
  390. */
  391. function cancel(
  392. address[] memory targets,
  393. uint256[] memory values,
  394. bytes[] memory calldatas,
  395. bytes32 descriptionHash
  396. ) public virtual returns (uint256) {
  397. // The proposalId will be recomputed in the `_cancel` call further down. However we need the value before we
  398. // do the internal call, because we need to check the proposal state BEFORE the internal `_cancel` call
  399. // changes it. The `hashProposal` duplication has a cost that is limited, and that we accept.
  400. uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
  401. // public cancel restrictions (on top of existing _cancel restrictions).
  402. _validateStateBitmap(proposalId, _encodeStateBitmap(ProposalState.Pending));
  403. if (_msgSender() != proposalProposer(proposalId)) {
  404. revert GovernorOnlyProposer(_msgSender());
  405. }
  406. return _cancel(targets, values, calldatas, descriptionHash);
  407. }
  408. /**
  409. * @dev Internal cancel mechanism with minimal restrictions. A proposal can be cancelled in any state other than
  410. * Canceled, Expired, or Executed. Once cancelled a proposal can't be re-submitted.
  411. *
  412. * Emits a {IGovernor-ProposalCanceled} event.
  413. */
  414. function _cancel(
  415. address[] memory targets,
  416. uint256[] memory values,
  417. bytes[] memory calldatas,
  418. bytes32 descriptionHash
  419. ) internal virtual returns (uint256) {
  420. uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
  421. _validateStateBitmap(
  422. proposalId,
  423. ALL_PROPOSAL_STATES_BITMAP ^
  424. _encodeStateBitmap(ProposalState.Canceled) ^
  425. _encodeStateBitmap(ProposalState.Expired) ^
  426. _encodeStateBitmap(ProposalState.Executed)
  427. );
  428. _proposals[proposalId].canceled = true;
  429. emit ProposalCanceled(proposalId);
  430. return proposalId;
  431. }
  432. /**
  433. * @dev See {IGovernor-getVotes}.
  434. */
  435. function getVotes(address account, uint256 timepoint) public view virtual returns (uint256) {
  436. return _getVotes(account, timepoint, _defaultParams());
  437. }
  438. /**
  439. * @dev See {IGovernor-getVotesWithParams}.
  440. */
  441. function getVotesWithParams(
  442. address account,
  443. uint256 timepoint,
  444. bytes memory params
  445. ) public view virtual returns (uint256) {
  446. return _getVotes(account, timepoint, params);
  447. }
  448. /**
  449. * @dev See {IGovernor-castVote}.
  450. */
  451. function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256) {
  452. address voter = _msgSender();
  453. return _castVote(proposalId, voter, support, "");
  454. }
  455. /**
  456. * @dev See {IGovernor-castVoteWithReason}.
  457. */
  458. function castVoteWithReason(
  459. uint256 proposalId,
  460. uint8 support,
  461. string calldata reason
  462. ) public virtual returns (uint256) {
  463. address voter = _msgSender();
  464. return _castVote(proposalId, voter, support, reason);
  465. }
  466. /**
  467. * @dev See {IGovernor-castVoteWithReasonAndParams}.
  468. */
  469. function castVoteWithReasonAndParams(
  470. uint256 proposalId,
  471. uint8 support,
  472. string calldata reason,
  473. bytes memory params
  474. ) public virtual returns (uint256) {
  475. address voter = _msgSender();
  476. return _castVote(proposalId, voter, support, reason, params);
  477. }
  478. /**
  479. * @dev See {IGovernor-castVoteBySig}.
  480. */
  481. function castVoteBySig(
  482. uint256 proposalId,
  483. uint8 support,
  484. address voter,
  485. bytes memory signature
  486. ) public virtual returns (uint256) {
  487. bool valid = SignatureChecker.isValidSignatureNow(
  488. voter,
  489. _hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support, voter, _useNonce(voter)))),
  490. signature
  491. );
  492. if (!valid) {
  493. revert GovernorInvalidSignature(voter);
  494. }
  495. return _castVote(proposalId, voter, support, "");
  496. }
  497. /**
  498. * @dev See {IGovernor-castVoteWithReasonAndParamsBySig}.
  499. */
  500. function castVoteWithReasonAndParamsBySig(
  501. uint256 proposalId,
  502. uint8 support,
  503. address voter,
  504. string calldata reason,
  505. bytes memory params,
  506. bytes memory signature
  507. ) public virtual returns (uint256) {
  508. bool valid = SignatureChecker.isValidSignatureNow(
  509. voter,
  510. _hashTypedDataV4(
  511. keccak256(
  512. abi.encode(
  513. EXTENDED_BALLOT_TYPEHASH,
  514. proposalId,
  515. support,
  516. voter,
  517. _useNonce(voter),
  518. keccak256(bytes(reason)),
  519. keccak256(params)
  520. )
  521. )
  522. ),
  523. signature
  524. );
  525. if (!valid) {
  526. revert GovernorInvalidSignature(voter);
  527. }
  528. return _castVote(proposalId, voter, support, reason, params);
  529. }
  530. /**
  531. * @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
  532. * voting weight using {IGovernor-getVotes} and call the {_countVote} internal function. Uses the _defaultParams().
  533. *
  534. * Emits a {IGovernor-VoteCast} event.
  535. */
  536. function _castVote(
  537. uint256 proposalId,
  538. address account,
  539. uint8 support,
  540. string memory reason
  541. ) internal virtual returns (uint256) {
  542. return _castVote(proposalId, account, support, reason, _defaultParams());
  543. }
  544. /**
  545. * @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
  546. * voting weight using {IGovernor-getVotes} and call the {_countVote} internal function.
  547. *
  548. * Emits a {IGovernor-VoteCast} event.
  549. */
  550. function _castVote(
  551. uint256 proposalId,
  552. address account,
  553. uint8 support,
  554. string memory reason,
  555. bytes memory params
  556. ) internal virtual returns (uint256) {
  557. _validateStateBitmap(proposalId, _encodeStateBitmap(ProposalState.Active));
  558. uint256 weight = _getVotes(account, proposalSnapshot(proposalId), params);
  559. _countVote(proposalId, account, support, weight, params);
  560. if (params.length == 0) {
  561. emit VoteCast(account, proposalId, support, weight, reason);
  562. } else {
  563. emit VoteCastWithParams(account, proposalId, support, weight, reason, params);
  564. }
  565. return weight;
  566. }
  567. /**
  568. * @dev Relays a transaction or function call to an arbitrary target. In cases where the governance executor
  569. * is some contract other than the governor itself, like when using a timelock, this function can be invoked
  570. * in a governance proposal to recover tokens or Ether that was sent to the governor contract by mistake.
  571. * Note that if the executor is simply the governor itself, use of `relay` is redundant.
  572. */
  573. function relay(address target, uint256 value, bytes calldata data) external payable virtual onlyGovernance {
  574. (bool success, bytes memory returndata) = target.call{value: value}(data);
  575. Address.verifyCallResult(success, returndata);
  576. }
  577. /**
  578. * @dev Address through which the governor executes action. Will be overloaded by module that execute actions
  579. * through another contract such as a timelock.
  580. */
  581. function _executor() internal view virtual returns (address) {
  582. return address(this);
  583. }
  584. /**
  585. * @dev See {IERC721Receiver-onERC721Received}.
  586. * Receiving tokens is disabled if the governance executor is other than the governor itself (eg. when using with a timelock).
  587. */
  588. function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) {
  589. if (_executor() != address(this)) {
  590. revert GovernorDisabledDeposit();
  591. }
  592. return this.onERC721Received.selector;
  593. }
  594. /**
  595. * @dev See {IERC1155Receiver-onERC1155Received}.
  596. * Receiving tokens is disabled if the governance executor is other than the governor itself (eg. when using with a timelock).
  597. */
  598. function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual returns (bytes4) {
  599. if (_executor() != address(this)) {
  600. revert GovernorDisabledDeposit();
  601. }
  602. return this.onERC1155Received.selector;
  603. }
  604. /**
  605. * @dev See {IERC1155Receiver-onERC1155BatchReceived}.
  606. * Receiving tokens is disabled if the governance executor is other than the governor itself (eg. when using with a timelock).
  607. */
  608. function onERC1155BatchReceived(
  609. address,
  610. address,
  611. uint256[] memory,
  612. uint256[] memory,
  613. bytes memory
  614. ) public virtual returns (bytes4) {
  615. if (_executor() != address(this)) {
  616. revert GovernorDisabledDeposit();
  617. }
  618. return this.onERC1155BatchReceived.selector;
  619. }
  620. /**
  621. * @dev Encodes a `ProposalState` into a `bytes32` representation where each bit enabled corresponds to
  622. * the underlying position in the `ProposalState` enum. For example:
  623. *
  624. * 0x000...10000
  625. * ^^^^^^------ ...
  626. * ^----- Succeeded
  627. * ^---- Defeated
  628. * ^--- Canceled
  629. * ^-- Active
  630. * ^- Pending
  631. */
  632. function _encodeStateBitmap(ProposalState proposalState) internal pure returns (bytes32) {
  633. return bytes32(1 << uint8(proposalState));
  634. }
  635. /**
  636. * @dev Check that the current state of a proposal matches the requirements described by the `allowedStates` bitmap.
  637. * This bitmap should be built using `_encodeStateBitmap`.
  638. *
  639. * If requirements are not met, reverts with a {GovernorUnexpectedProposalState} error.
  640. */
  641. function _validateStateBitmap(uint256 proposalId, bytes32 allowedStates) private view returns (ProposalState) {
  642. ProposalState currentState = state(proposalId);
  643. if (_encodeStateBitmap(currentState) & allowedStates == bytes32(0)) {
  644. revert GovernorUnexpectedProposalState(proposalId, currentState, allowedStates);
  645. }
  646. return currentState;
  647. }
  648. /*
  649. * @dev Check if the proposer is authorized to submit a proposal with the given description.
  650. *
  651. * If the proposal description ends with `#proposer=0x???`, where `0x???` is an address written as a hex string
  652. * (case insensitive), then the submission of this proposal will only be authorized to said address.
  653. *
  654. * This is used for frontrunning protection. By adding this pattern at the end of their proposal, one can ensure
  655. * that no other address can submit the same proposal. An attacker would have to either remove or change that part,
  656. * which would result in a different proposal id.
  657. *
  658. * If the description does not match this pattern, it is unrestricted and anyone can submit it. This includes:
  659. * - If the `0x???` part is not a valid hex string.
  660. * - If the `0x???` part is a valid hex string, but does not contain exactly 40 hex digits.
  661. * - If it ends with the expected suffix followed by newlines or other whitespace.
  662. * - If it ends with some other similar suffix, e.g. `#other=abc`.
  663. * - If it does not end with any such suffix.
  664. */
  665. function _isValidDescriptionForProposer(
  666. address proposer,
  667. string memory description
  668. ) internal view virtual returns (bool) {
  669. uint256 len = bytes(description).length;
  670. // Length is too short to contain a valid proposer suffix
  671. if (len < 52) {
  672. return true;
  673. }
  674. // Extract what would be the `#proposer=0x` marker beginning the suffix
  675. bytes12 marker;
  676. assembly {
  677. // - Start of the string contents in memory = description + 32
  678. // - First character of the marker = len - 52
  679. // - Length of "#proposer=0x0000000000000000000000000000000000000000" = 52
  680. // - We read the memory word starting at the first character of the marker:
  681. // - (description + 32) + (len - 52) = description + (len - 20)
  682. // - Note: Solidity will ignore anything past the first 12 bytes
  683. marker := mload(add(description, sub(len, 20)))
  684. }
  685. // If the marker is not found, there is no proposer suffix to check
  686. if (marker != bytes12("#proposer=0x")) {
  687. return true;
  688. }
  689. // Parse the 40 characters following the marker as uint160
  690. uint160 recovered = 0;
  691. for (uint256 i = len - 40; i < len; ++i) {
  692. (bool isHex, uint8 value) = _tryHexToUint(bytes(description)[i]);
  693. // If any of the characters is not a hex digit, ignore the suffix entirely
  694. if (!isHex) {
  695. return true;
  696. }
  697. recovered = (recovered << 4) | value;
  698. }
  699. return recovered == uint160(proposer);
  700. }
  701. /**
  702. * @dev Try to parse a character from a string as a hex value. Returns `(true, value)` if the char is in
  703. * `[0-9a-fA-F]` and `(false, 0)` otherwise. Value is guaranteed to be in the range `0 <= value < 16`
  704. */
  705. function _tryHexToUint(bytes1 char) private pure returns (bool, uint8) {
  706. uint8 c = uint8(char);
  707. unchecked {
  708. // Case 0-9
  709. if (47 < c && c < 58) {
  710. return (true, c - 48);
  711. }
  712. // Case A-F
  713. else if (64 < c && c < 71) {
  714. return (true, c - 55);
  715. }
  716. // Case a-f
  717. else if (96 < c && c < 103) {
  718. return (true, c - 87);
  719. }
  720. // Else: not a hex char
  721. else {
  722. return (false, 0);
  723. }
  724. }
  725. }
  726. /**
  727. * @inheritdoc IERC6372
  728. */
  729. function clock() public view virtual returns (uint48);
  730. /**
  731. * @inheritdoc IERC6372
  732. */
  733. // solhint-disable-next-line func-name-mixedcase
  734. function CLOCK_MODE() public view virtual returns (string memory);
  735. /**
  736. * @inheritdoc IGovernor
  737. */
  738. function votingDelay() public view virtual returns (uint256);
  739. /**
  740. * @inheritdoc IGovernor
  741. */
  742. function votingPeriod() public view virtual returns (uint256);
  743. /**
  744. * @inheritdoc IGovernor
  745. */
  746. function quorum(uint256 timepoint) public view virtual returns (uint256);
  747. }