Governor.sol 31 KB

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