Governor.sol 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.2.0-rc.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 Hook that should be called every time the tally for a proposal is updated.
  229. *
  230. * Note: This function must run successfully. Reverts will result in the bricking of governance
  231. */
  232. function _tallyUpdated(uint256 proposalId) internal virtual {}
  233. /**
  234. * @dev Default additional encoded parameters used by castVote methods that don't include them
  235. *
  236. * Note: Should be overridden by specific implementations to use an appropriate value, the
  237. * meaning of the additional params, in the context of that implementation
  238. */
  239. function _defaultParams() internal view virtual returns (bytes memory) {
  240. return "";
  241. }
  242. /**
  243. * @dev See {IGovernor-propose}. This function has opt-in frontrunning protection, described in {_isValidDescriptionForProposer}.
  244. */
  245. function propose(
  246. address[] memory targets,
  247. uint256[] memory values,
  248. bytes[] memory calldatas,
  249. string memory description
  250. ) public virtual returns (uint256) {
  251. address proposer = _msgSender();
  252. // check description restriction
  253. if (!_isValidDescriptionForProposer(proposer, description)) {
  254. revert GovernorRestrictedProposer(proposer);
  255. }
  256. // check proposal threshold
  257. uint256 votesThreshold = proposalThreshold();
  258. if (votesThreshold > 0) {
  259. uint256 proposerVotes = getVotes(proposer, clock() - 1);
  260. if (proposerVotes < votesThreshold) {
  261. revert GovernorInsufficientProposerVotes(proposer, proposerVotes, votesThreshold);
  262. }
  263. }
  264. return _propose(targets, values, calldatas, description, proposer);
  265. }
  266. /**
  267. * @dev Internal propose mechanism. Can be overridden to add more logic on proposal creation.
  268. *
  269. * Emits a {IGovernor-ProposalCreated} event.
  270. */
  271. function _propose(
  272. address[] memory targets,
  273. uint256[] memory values,
  274. bytes[] memory calldatas,
  275. string memory description,
  276. address proposer
  277. ) internal virtual returns (uint256 proposalId) {
  278. proposalId = hashProposal(targets, values, calldatas, keccak256(bytes(description)));
  279. if (targets.length != values.length || targets.length != calldatas.length || targets.length == 0) {
  280. revert GovernorInvalidProposalLength(targets.length, calldatas.length, values.length);
  281. }
  282. if (_proposals[proposalId].voteStart != 0) {
  283. revert GovernorUnexpectedProposalState(proposalId, state(proposalId), bytes32(0));
  284. }
  285. uint256 snapshot = clock() + votingDelay();
  286. uint256 duration = votingPeriod();
  287. ProposalCore storage proposal = _proposals[proposalId];
  288. proposal.proposer = proposer;
  289. proposal.voteStart = SafeCast.toUint48(snapshot);
  290. proposal.voteDuration = SafeCast.toUint32(duration);
  291. emit ProposalCreated(
  292. proposalId,
  293. proposer,
  294. targets,
  295. values,
  296. new string[](targets.length),
  297. calldatas,
  298. snapshot,
  299. snapshot + duration,
  300. description
  301. );
  302. // Using a named return variable to avoid stack too deep errors
  303. }
  304. /**
  305. * @dev See {IGovernor-queue}.
  306. */
  307. function queue(
  308. address[] memory targets,
  309. uint256[] memory values,
  310. bytes[] memory calldatas,
  311. bytes32 descriptionHash
  312. ) public virtual returns (uint256) {
  313. uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
  314. _validateStateBitmap(proposalId, _encodeStateBitmap(ProposalState.Succeeded));
  315. uint48 etaSeconds = _queueOperations(proposalId, targets, values, calldatas, descriptionHash);
  316. if (etaSeconds != 0) {
  317. _proposals[proposalId].etaSeconds = etaSeconds;
  318. emit ProposalQueued(proposalId, etaSeconds);
  319. } else {
  320. revert GovernorQueueNotImplemented();
  321. }
  322. return proposalId;
  323. }
  324. /**
  325. * @dev Internal queuing mechanism. Can be overridden (without a super call) to modify the way queuing is
  326. * performed (for example adding a vault/timelock).
  327. *
  328. * This is empty by default, and must be overridden to implement queuing.
  329. *
  330. * This function returns a timestamp that describes the expected ETA for execution. If the returned value is 0
  331. * (which is the default value), the core will consider queueing did not succeed, and the public {queue} function
  332. * will revert.
  333. *
  334. * NOTE: Calling this function directly will NOT check the current state of the proposal, or emit the
  335. * `ProposalQueued` event. Queuing a proposal should be done using {queue}.
  336. */
  337. function _queueOperations(
  338. uint256 /*proposalId*/,
  339. address[] memory /*targets*/,
  340. uint256[] memory /*values*/,
  341. bytes[] memory /*calldatas*/,
  342. bytes32 /*descriptionHash*/
  343. ) internal virtual returns (uint48) {
  344. return 0;
  345. }
  346. /**
  347. * @dev See {IGovernor-execute}.
  348. */
  349. function execute(
  350. address[] memory targets,
  351. uint256[] memory values,
  352. bytes[] memory calldatas,
  353. bytes32 descriptionHash
  354. ) public payable virtual returns (uint256) {
  355. uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
  356. _validateStateBitmap(
  357. proposalId,
  358. _encodeStateBitmap(ProposalState.Succeeded) | _encodeStateBitmap(ProposalState.Queued)
  359. );
  360. // mark as executed before calls to avoid reentrancy
  361. _proposals[proposalId].executed = true;
  362. // before execute: register governance call in queue.
  363. if (_executor() != address(this)) {
  364. for (uint256 i = 0; i < targets.length; ++i) {
  365. if (targets[i] == address(this)) {
  366. _governanceCall.pushBack(keccak256(calldatas[i]));
  367. }
  368. }
  369. }
  370. _executeOperations(proposalId, targets, values, calldatas, descriptionHash);
  371. // after execute: cleanup governance call queue.
  372. if (_executor() != address(this) && !_governanceCall.empty()) {
  373. _governanceCall.clear();
  374. }
  375. emit ProposalExecuted(proposalId);
  376. return proposalId;
  377. }
  378. /**
  379. * @dev Internal execution mechanism. Can be overridden (without a super call) to modify the way execution is
  380. * performed (for example adding a vault/timelock).
  381. *
  382. * NOTE: Calling this function directly will NOT check the current state of the proposal, set the executed flag to
  383. * true or emit the `ProposalExecuted` event. Executing a proposal should be done using {execute} or {_execute}.
  384. */
  385. function _executeOperations(
  386. uint256 /* proposalId */,
  387. address[] memory targets,
  388. uint256[] memory values,
  389. bytes[] memory calldatas,
  390. bytes32 /*descriptionHash*/
  391. ) internal virtual {
  392. for (uint256 i = 0; i < targets.length; ++i) {
  393. (bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]);
  394. Address.verifyCallResult(success, returndata);
  395. }
  396. }
  397. /**
  398. * @dev See {IGovernor-cancel}.
  399. */
  400. function cancel(
  401. address[] memory targets,
  402. uint256[] memory values,
  403. bytes[] memory calldatas,
  404. bytes32 descriptionHash
  405. ) public virtual returns (uint256) {
  406. // The proposalId will be recomputed in the `_cancel` call further down. However we need the value before we
  407. // do the internal call, because we need to check the proposal state BEFORE the internal `_cancel` call
  408. // changes it. The `hashProposal` duplication has a cost that is limited, and that we accept.
  409. uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
  410. // public cancel restrictions (on top of existing _cancel restrictions).
  411. _validateStateBitmap(proposalId, _encodeStateBitmap(ProposalState.Pending));
  412. if (_msgSender() != proposalProposer(proposalId)) {
  413. revert GovernorOnlyProposer(_msgSender());
  414. }
  415. return _cancel(targets, values, calldatas, descriptionHash);
  416. }
  417. /**
  418. * @dev Internal cancel mechanism with minimal restrictions. A proposal can be cancelled in any state other than
  419. * Canceled, Expired, or Executed. Once cancelled a proposal can't be re-submitted.
  420. *
  421. * Emits a {IGovernor-ProposalCanceled} event.
  422. */
  423. function _cancel(
  424. address[] memory targets,
  425. uint256[] memory values,
  426. bytes[] memory calldatas,
  427. bytes32 descriptionHash
  428. ) internal virtual returns (uint256) {
  429. uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
  430. _validateStateBitmap(
  431. proposalId,
  432. ALL_PROPOSAL_STATES_BITMAP ^
  433. _encodeStateBitmap(ProposalState.Canceled) ^
  434. _encodeStateBitmap(ProposalState.Expired) ^
  435. _encodeStateBitmap(ProposalState.Executed)
  436. );
  437. _proposals[proposalId].canceled = true;
  438. emit ProposalCanceled(proposalId);
  439. return proposalId;
  440. }
  441. /**
  442. * @dev See {IGovernor-getVotes}.
  443. */
  444. function getVotes(address account, uint256 timepoint) public view virtual returns (uint256) {
  445. return _getVotes(account, timepoint, _defaultParams());
  446. }
  447. /**
  448. * @dev See {IGovernor-getVotesWithParams}.
  449. */
  450. function getVotesWithParams(
  451. address account,
  452. uint256 timepoint,
  453. bytes memory params
  454. ) public view virtual returns (uint256) {
  455. return _getVotes(account, timepoint, params);
  456. }
  457. /**
  458. * @dev See {IGovernor-castVote}.
  459. */
  460. function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256) {
  461. address voter = _msgSender();
  462. return _castVote(proposalId, voter, support, "");
  463. }
  464. /**
  465. * @dev See {IGovernor-castVoteWithReason}.
  466. */
  467. function castVoteWithReason(
  468. uint256 proposalId,
  469. uint8 support,
  470. string calldata reason
  471. ) public virtual returns (uint256) {
  472. address voter = _msgSender();
  473. return _castVote(proposalId, voter, support, reason);
  474. }
  475. /**
  476. * @dev See {IGovernor-castVoteWithReasonAndParams}.
  477. */
  478. function castVoteWithReasonAndParams(
  479. uint256 proposalId,
  480. uint8 support,
  481. string calldata reason,
  482. bytes memory params
  483. ) public virtual returns (uint256) {
  484. address voter = _msgSender();
  485. return _castVote(proposalId, voter, support, reason, params);
  486. }
  487. /**
  488. * @dev See {IGovernor-castVoteBySig}.
  489. */
  490. function castVoteBySig(
  491. uint256 proposalId,
  492. uint8 support,
  493. address voter,
  494. bytes memory signature
  495. ) public virtual returns (uint256) {
  496. bool valid = SignatureChecker.isValidSignatureNow(
  497. voter,
  498. _hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support, voter, _useNonce(voter)))),
  499. signature
  500. );
  501. if (!valid) {
  502. revert GovernorInvalidSignature(voter);
  503. }
  504. return _castVote(proposalId, voter, support, "");
  505. }
  506. /**
  507. * @dev See {IGovernor-castVoteWithReasonAndParamsBySig}.
  508. */
  509. function castVoteWithReasonAndParamsBySig(
  510. uint256 proposalId,
  511. uint8 support,
  512. address voter,
  513. string calldata reason,
  514. bytes memory params,
  515. bytes memory signature
  516. ) public virtual returns (uint256) {
  517. bool valid = SignatureChecker.isValidSignatureNow(
  518. voter,
  519. _hashTypedDataV4(
  520. keccak256(
  521. abi.encode(
  522. EXTENDED_BALLOT_TYPEHASH,
  523. proposalId,
  524. support,
  525. voter,
  526. _useNonce(voter),
  527. keccak256(bytes(reason)),
  528. keccak256(params)
  529. )
  530. )
  531. ),
  532. signature
  533. );
  534. if (!valid) {
  535. revert GovernorInvalidSignature(voter);
  536. }
  537. return _castVote(proposalId, voter, support, reason, params);
  538. }
  539. /**
  540. * @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
  541. * voting weight using {IGovernor-getVotes} and call the {_countVote} internal function. Uses the _defaultParams().
  542. *
  543. * Emits a {IGovernor-VoteCast} event.
  544. */
  545. function _castVote(
  546. uint256 proposalId,
  547. address account,
  548. uint8 support,
  549. string memory reason
  550. ) internal virtual returns (uint256) {
  551. return _castVote(proposalId, account, support, reason, _defaultParams());
  552. }
  553. /**
  554. * @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
  555. * voting weight using {IGovernor-getVotes} and call the {_countVote} internal function.
  556. *
  557. * Emits a {IGovernor-VoteCast} event.
  558. */
  559. function _castVote(
  560. uint256 proposalId,
  561. address account,
  562. uint8 support,
  563. string memory reason,
  564. bytes memory params
  565. ) internal virtual returns (uint256) {
  566. _validateStateBitmap(proposalId, _encodeStateBitmap(ProposalState.Active));
  567. uint256 totalWeight = _getVotes(account, proposalSnapshot(proposalId), params);
  568. uint256 votedWeight = _countVote(proposalId, account, support, totalWeight, params);
  569. if (params.length == 0) {
  570. emit VoteCast(account, proposalId, support, votedWeight, reason);
  571. } else {
  572. emit VoteCastWithParams(account, proposalId, support, votedWeight, reason, params);
  573. }
  574. _tallyUpdated(proposalId);
  575. return votedWeight;
  576. }
  577. /**
  578. * @dev Relays a transaction or function call to an arbitrary target. In cases where the governance executor
  579. * is some contract other than the governor itself, like when using a timelock, this function can be invoked
  580. * in a governance proposal to recover tokens or Ether that was sent to the governor contract by mistake.
  581. * Note that if the executor is simply the governor itself, use of `relay` is redundant.
  582. */
  583. function relay(address target, uint256 value, bytes calldata data) external payable virtual onlyGovernance {
  584. (bool success, bytes memory returndata) = target.call{value: value}(data);
  585. Address.verifyCallResult(success, returndata);
  586. }
  587. /**
  588. * @dev Address through which the governor executes action. Will be overloaded by module that execute actions
  589. * through another contract such as a timelock.
  590. */
  591. function _executor() internal view virtual returns (address) {
  592. return address(this);
  593. }
  594. /**
  595. * @dev See {IERC721Receiver-onERC721Received}.
  596. * Receiving tokens is disabled if the governance executor is other than the governor itself (eg. when using with a timelock).
  597. */
  598. function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) {
  599. if (_executor() != address(this)) {
  600. revert GovernorDisabledDeposit();
  601. }
  602. return this.onERC721Received.selector;
  603. }
  604. /**
  605. * @dev See {IERC1155Receiver-onERC1155Received}.
  606. * Receiving tokens is disabled if the governance executor is other than the governor itself (eg. when using with a timelock).
  607. */
  608. function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual returns (bytes4) {
  609. if (_executor() != address(this)) {
  610. revert GovernorDisabledDeposit();
  611. }
  612. return this.onERC1155Received.selector;
  613. }
  614. /**
  615. * @dev See {IERC1155Receiver-onERC1155BatchReceived}.
  616. * Receiving tokens is disabled if the governance executor is other than the governor itself (eg. when using with a timelock).
  617. */
  618. function onERC1155BatchReceived(
  619. address,
  620. address,
  621. uint256[] memory,
  622. uint256[] memory,
  623. bytes memory
  624. ) public virtual returns (bytes4) {
  625. if (_executor() != address(this)) {
  626. revert GovernorDisabledDeposit();
  627. }
  628. return this.onERC1155BatchReceived.selector;
  629. }
  630. /**
  631. * @dev Encodes a `ProposalState` into a `bytes32` representation where each bit enabled corresponds to
  632. * the underlying position in the `ProposalState` enum. For example:
  633. *
  634. * 0x000...10000
  635. * ^^^^^^------ ...
  636. * ^----- Succeeded
  637. * ^---- Defeated
  638. * ^--- Canceled
  639. * ^-- Active
  640. * ^- Pending
  641. */
  642. function _encodeStateBitmap(ProposalState proposalState) internal pure returns (bytes32) {
  643. return bytes32(1 << uint8(proposalState));
  644. }
  645. /**
  646. * @dev Check that the current state of a proposal matches the requirements described by the `allowedStates` bitmap.
  647. * This bitmap should be built using `_encodeStateBitmap`.
  648. *
  649. * If requirements are not met, reverts with a {GovernorUnexpectedProposalState} error.
  650. */
  651. function _validateStateBitmap(uint256 proposalId, bytes32 allowedStates) internal view returns (ProposalState) {
  652. ProposalState currentState = state(proposalId);
  653. if (_encodeStateBitmap(currentState) & allowedStates == bytes32(0)) {
  654. revert GovernorUnexpectedProposalState(proposalId, currentState, allowedStates);
  655. }
  656. return currentState;
  657. }
  658. /*
  659. * @dev Check if the proposer is authorized to submit a proposal with the given description.
  660. *
  661. * If the proposal description ends with `#proposer=0x???`, where `0x???` is an address written as a hex string
  662. * (case insensitive), then the submission of this proposal will only be authorized to said address.
  663. *
  664. * This is used for frontrunning protection. By adding this pattern at the end of their proposal, one can ensure
  665. * that no other address can submit the same proposal. An attacker would have to either remove or change that part,
  666. * which would result in a different proposal id.
  667. *
  668. * If the description does not match this pattern, it is unrestricted and anyone can submit it. This includes:
  669. * - If the `0x???` part is not a valid hex string.
  670. * - If the `0x???` part is a valid hex string, but does not contain exactly 40 hex digits.
  671. * - If it ends with the expected suffix followed by newlines or other whitespace.
  672. * - If it ends with some other similar suffix, e.g. `#other=abc`.
  673. * - If it does not end with any such suffix.
  674. */
  675. function _isValidDescriptionForProposer(
  676. address proposer,
  677. string memory description
  678. ) internal view virtual returns (bool) {
  679. unchecked {
  680. uint256 length = bytes(description).length;
  681. // Length is too short to contain a valid proposer suffix
  682. if (length < 52) {
  683. return true;
  684. }
  685. // Extract what would be the `#proposer=` marker beginning the suffix
  686. bytes10 marker = bytes10(_unsafeReadBytesOffset(bytes(description), length - 52));
  687. // If the marker is not found, there is no proposer suffix to check
  688. if (marker != bytes10("#proposer=")) {
  689. return true;
  690. }
  691. // Check that the last 42 characters (after the marker) are a properly formatted address.
  692. (bool success, address recovered) = Strings.tryParseAddress(description, length - 42, length);
  693. return !success || recovered == proposer;
  694. }
  695. }
  696. /**
  697. * @inheritdoc IERC6372
  698. */
  699. function clock() public view virtual returns (uint48);
  700. /**
  701. * @inheritdoc IERC6372
  702. */
  703. // solhint-disable-next-line func-name-mixedcase
  704. function CLOCK_MODE() public view virtual returns (string memory);
  705. /**
  706. * @inheritdoc IGovernor
  707. */
  708. function votingDelay() public view virtual returns (uint256);
  709. /**
  710. * @inheritdoc IGovernor
  711. */
  712. function votingPeriod() public view virtual returns (uint256);
  713. /**
  714. * @inheritdoc IGovernor
  715. */
  716. function quorum(uint256 timepoint) public view virtual returns (uint256);
  717. /**
  718. * @dev Reads a bytes32 from a bytes array without bounds checking.
  719. *
  720. * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
  721. * assembly block as such would prevent some optimizations.
  722. */
  723. function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
  724. // This is not memory safe in the general case, but all calls to this private function are within bounds.
  725. assembly ("memory-safe") {
  726. value := mload(add(buffer, add(0x20, offset)))
  727. }
  728. }
  729. }