Governor.sol 30 KB

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