Governor.sol 31 KB

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