Governor.sol 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.9.1) (governance/Governor.sol)
  3. pragma solidity ^0.8.20;
  4. import {IERC721Receiver} from "../token/ERC721/IERC721Receiver.sol";
  5. import {IERC1155Receiver} from "../token/ERC1155/IERC1155Receiver.sol";
  6. import {EIP712} from "../utils/cryptography/EIP712.sol";
  7. import {SignatureChecker} from "../utils/cryptography/SignatureChecker.sol";
  8. import {IERC165, ERC165} from "../utils/introspection/ERC165.sol";
  9. import {SafeCast} from "../utils/math/SafeCast.sol";
  10. import {DoubleEndedQueue} from "../utils/structs/DoubleEndedQueue.sol";
  11. import {Address} from "../utils/Address.sol";
  12. import {Context} from "../utils/Context.sol";
  13. import {Nonces} from "../utils/Nonces.sol";
  14. import {IGovernor, IERC6372} from "./IGovernor.sol";
  15. /**
  16. * @dev Core of the governance system, designed to be extended though various modules.
  17. *
  18. * This contract is abstract and requires several functions to be implemented in various modules:
  19. *
  20. * - A counting module must implement {quorum}, {_quorumReached}, {_voteSucceeded} and {_countVote}
  21. * - A voting module must implement {_getVotes}
  22. * - Additionally, {votingPeriod} must also be implemented
  23. */
  24. abstract contract Governor is Context, ERC165, EIP712, Nonces, IGovernor, IERC721Receiver, IERC1155Receiver {
  25. using DoubleEndedQueue for DoubleEndedQueue.Bytes32Deque;
  26. bytes32 public constant BALLOT_TYPEHASH =
  27. keccak256("Ballot(uint256 proposalId,uint8 support,address voter,uint256 nonce)");
  28. bytes32 public constant EXTENDED_BALLOT_TYPEHASH =
  29. keccak256(
  30. "ExtendedBallot(uint256 proposalId,uint8 support,address voter,uint256 nonce,string reason,bytes params)"
  31. );
  32. struct ProposalCore {
  33. address proposer;
  34. uint48 voteStart;
  35. uint32 voteDuration;
  36. bool executed;
  37. bool canceled;
  38. }
  39. struct ProposalExtra {
  40. uint48 eta;
  41. }
  42. // Each object in this should fit into a single slot so it can be cached efficiently
  43. struct ProposalFull {
  44. ProposalCore core;
  45. ProposalExtra extra;
  46. }
  47. bytes32 private constant _ALL_PROPOSAL_STATES_BITMAP = bytes32((2 ** (uint8(type(ProposalState).max) + 1)) - 1);
  48. string private _name;
  49. mapping(uint256 => ProposalFull) private _proposals;
  50. // This queue keeps track of the governor operating on itself. Calls to functions protected by the
  51. // {onlyGovernance} modifier needs to be whitelisted in this queue. Whitelisting is set in {_beforeExecute},
  52. // consumed by the {onlyGovernance} modifier and eventually reset in {_afterExecute}. This ensures that the
  53. // execution of {onlyGovernance} protected calls can only be achieved through successful proposals.
  54. DoubleEndedQueue.Bytes32Deque private _governanceCall;
  55. /**
  56. * @dev Restricts a function so it can only be executed through governance proposals. For example, governance
  57. * parameter setters in {GovernorSettings} are protected using this modifier.
  58. *
  59. * The governance executing address may be different from the Governor's own address, for example it could be a
  60. * timelock. This can be customized by modules by overriding {_executor}. The executor is only able to invoke these
  61. * functions during the execution of the governor's {execute} function, and not under any other circumstances. Thus,
  62. * for example, additional timelock proposers are not able to change governance parameters without going through the
  63. * governance protocol (since v4.6).
  64. */
  65. modifier onlyGovernance() {
  66. _checkGovernance();
  67. _;
  68. }
  69. /**
  70. * @dev Sets the value for {name} and {version}
  71. */
  72. constructor(string memory name_) EIP712(name_, version()) {
  73. _name = name_;
  74. }
  75. /**
  76. * @dev Function to receive ETH that will be handled by the governor (disabled if executor is a third party contract)
  77. */
  78. receive() external payable virtual {
  79. if (_executor() != address(this)) {
  80. revert GovernorDisabledDeposit();
  81. }
  82. }
  83. /**
  84. * @dev See {IERC165-supportsInterface}.
  85. */
  86. function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
  87. return
  88. interfaceId == type(IGovernor).interfaceId ^ type(IERC6372).interfaceId ||
  89. interfaceId == type(IERC1155Receiver).interfaceId ||
  90. super.supportsInterface(interfaceId);
  91. }
  92. /**
  93. * @dev See {IGovernor-name}.
  94. */
  95. function name() public view virtual override returns (string memory) {
  96. return _name;
  97. }
  98. /**
  99. * @dev See {IGovernor-version}.
  100. */
  101. function version() public view virtual override returns (string memory) {
  102. return "1";
  103. }
  104. /**
  105. * @dev See {IGovernor-hashProposal}.
  106. *
  107. * The proposal id is produced by hashing the ABI encoded `targets` array, the `values` array, the `calldatas` array
  108. * and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id
  109. * can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in
  110. * advance, before the proposal is submitted.
  111. *
  112. * Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the
  113. * same proposal (with same operation and same description) will have the same id if submitted on multiple governors
  114. * across multiple networks. This also means that in order to execute the same operation twice (on the same
  115. * governor) the proposer will have to change the description in order to avoid proposal id conflicts.
  116. */
  117. function hashProposal(
  118. address[] memory targets,
  119. uint256[] memory values,
  120. bytes[] memory calldatas,
  121. bytes32 descriptionHash
  122. ) public pure virtual override returns (uint256) {
  123. return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash)));
  124. }
  125. /**
  126. * @dev See {IGovernor-state}.
  127. */
  128. function state(uint256 proposalId) public view virtual override returns (ProposalState) {
  129. // ProposalCore is just one slot. We can load it from storage to memory with a single sload and use memory
  130. // object as a cache. This avoid duplicating expensive sloads.
  131. ProposalCore memory core = _proposals[proposalId].core;
  132. if (core.executed) {
  133. return ProposalState.Executed;
  134. } else if (core.canceled) {
  135. return ProposalState.Canceled;
  136. }
  137. uint256 snapshot = proposalSnapshot(proposalId);
  138. if (snapshot == 0) {
  139. revert GovernorNonexistentProposal(proposalId);
  140. }
  141. uint256 currentTimepoint = clock();
  142. if (snapshot >= currentTimepoint) {
  143. return ProposalState.Pending;
  144. }
  145. uint256 deadline = proposalDeadline(proposalId);
  146. if (deadline >= currentTimepoint) {
  147. return ProposalState.Active;
  148. } else if (!_quorumReached(proposalId) || !_voteSucceeded(proposalId)) {
  149. return ProposalState.Defeated;
  150. } else if (proposalEta(proposalId) == 0) {
  151. return ProposalState.Succeeded;
  152. } else {
  153. return ProposalState.Queued;
  154. }
  155. }
  156. /**
  157. * @dev See {IGovernor-proposalThreshold}.
  158. */
  159. function proposalThreshold() public view virtual override returns (uint256) {
  160. return 0;
  161. }
  162. /**
  163. * @dev See {IGovernor-proposalSnapshot}.
  164. */
  165. function proposalSnapshot(uint256 proposalId) public view virtual override returns (uint256) {
  166. return _proposals[proposalId].core.voteStart;
  167. }
  168. /**
  169. * @dev See {IGovernor-proposalDeadline}.
  170. */
  171. function proposalDeadline(uint256 proposalId) public view virtual override returns (uint256) {
  172. return _proposals[proposalId].core.voteStart + _proposals[proposalId].core.voteDuration;
  173. }
  174. /**
  175. * @dev See {IGovernor-proposalProposer}.
  176. */
  177. function proposalProposer(uint256 proposalId) public view virtual override returns (address) {
  178. return _proposals[proposalId].core.proposer;
  179. }
  180. /**
  181. * @dev See {IGovernor-proposalEta}.
  182. */
  183. function proposalEta(uint256 proposalId) public view virtual override returns (uint256) {
  184. return _proposals[proposalId].extra.eta;
  185. }
  186. /**
  187. * @dev Reverts if the `msg.sender` is not the executor. In case the executor is not this contract
  188. * itself, the function reverts if `msg.data` is not whitelisted as a result of an {execute}
  189. * operation. See {onlyGovernance}.
  190. */
  191. function _checkGovernance() internal virtual {
  192. if (_executor() != _msgSender()) {
  193. revert GovernorOnlyExecutor(_msgSender());
  194. }
  195. if (_executor() != address(this)) {
  196. bytes32 msgDataHash = keccak256(_msgData());
  197. // loop until popping the expected operation - throw if deque is empty (operation not authorized)
  198. while (_governanceCall.popFront() != msgDataHash) {}
  199. }
  200. }
  201. /**
  202. * @dev Amount of votes already cast passes the threshold limit.
  203. */
  204. function _quorumReached(uint256 proposalId) internal view virtual returns (bool);
  205. /**
  206. * @dev Is the proposal successful or not.
  207. */
  208. function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool);
  209. /**
  210. * @dev Get the voting weight of `account` at a specific `timepoint`, for a vote as described by `params`.
  211. */
  212. function _getVotes(address account, uint256 timepoint, bytes memory params) internal view virtual returns (uint256);
  213. /**
  214. * @dev Register a vote for `proposalId` by `account` with a given `support`, voting `weight` and voting `params`.
  215. *
  216. * Note: Support is generic and can represent various things depending on the voting system used.
  217. */
  218. function _countVote(
  219. uint256 proposalId,
  220. address account,
  221. uint8 support,
  222. uint256 weight,
  223. bytes memory params
  224. ) internal virtual;
  225. /**
  226. * @dev Default additional encoded parameters used by castVote methods that don't include them
  227. *
  228. * Note: Should be overridden by specific implementations to use an appropriate value, the
  229. * meaning of the additional params, in the context of that implementation
  230. */
  231. function _defaultParams() internal view virtual returns (bytes memory) {
  232. return "";
  233. }
  234. /**
  235. * @dev See {IGovernor-propose}. This function has opt-in frontrunning protection, described in {_isValidDescriptionForProposer}.
  236. */
  237. function propose(
  238. address[] memory targets,
  239. uint256[] memory values,
  240. bytes[] memory calldatas,
  241. string memory description
  242. ) public virtual override returns (uint256) {
  243. address proposer = _msgSender();
  244. // check description restriction
  245. if (!_isValidDescriptionForProposer(proposer, description)) {
  246. revert GovernorRestrictedProposer(proposer);
  247. }
  248. // check proposal threshold
  249. uint256 proposerVotes = getVotes(proposer, clock() - 1);
  250. uint256 votesThreshold = proposalThreshold();
  251. if (proposerVotes < votesThreshold) {
  252. revert GovernorInsufficientProposerVotes(proposer, proposerVotes, votesThreshold);
  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) {
  268. uint256 proposalId = hashProposal(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].core.voteStart != 0) {
  273. revert GovernorUnexpectedProposalState(proposalId, state(proposalId), bytes32(0));
  274. }
  275. uint256 snapshot = clock() + votingDelay();
  276. uint256 duration = votingPeriod();
  277. _proposals[proposalId].core = ProposalCore({
  278. proposer: proposer,
  279. voteStart: SafeCast.toUint48(snapshot),
  280. voteDuration: SafeCast.toUint32(duration),
  281. executed: false,
  282. canceled: false
  283. });
  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. return proposalId;
  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 override returns (uint256) {
  306. uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
  307. _validateStateBitmap(proposalId, _encodeStateBitmap(ProposalState.Succeeded));
  308. uint48 eta = _queueOperations(proposalId, targets, values, calldatas, descriptionHash);
  309. if (eta != 0) {
  310. _proposals[proposalId].extra.eta = eta;
  311. emit ProposalQueued(proposalId, eta);
  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} or {_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 override 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].core.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 override 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].core.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 override 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 override 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 override 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 override 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 override 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 override 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 override 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. ProposalState currentState = state(proposalId);
  560. if (currentState != ProposalState.Active) {
  561. revert GovernorUnexpectedProposalState(proposalId, currentState, _encodeStateBitmap(ProposalState.Active));
  562. }
  563. uint256 weight = _getVotes(account, proposalSnapshot(proposalId), params);
  564. _countVote(proposalId, account, support, weight, params);
  565. if (params.length == 0) {
  566. emit VoteCast(account, proposalId, support, weight, reason);
  567. } else {
  568. emit VoteCastWithParams(account, proposalId, support, weight, reason, params);
  569. }
  570. return weight;
  571. }
  572. /**
  573. * @dev Relays a transaction or function call to an arbitrary target. In cases where the governance executor
  574. * is some contract other than the governor itself, like when using a timelock, this function can be invoked
  575. * in a governance proposal to recover tokens or Ether that was sent to the governor contract by mistake.
  576. * Note that if the executor is simply the governor itself, use of `relay` is redundant.
  577. */
  578. function relay(address target, uint256 value, bytes calldata data) external payable virtual onlyGovernance {
  579. (bool success, bytes memory returndata) = target.call{value: value}(data);
  580. Address.verifyCallResult(success, returndata);
  581. }
  582. /**
  583. * @dev Address through which the governor executes action. Will be overloaded by module that execute actions
  584. * through another contract such as a timelock.
  585. */
  586. function _executor() internal view virtual returns (address) {
  587. return address(this);
  588. }
  589. /**
  590. * @dev See {IERC721Receiver-onERC721Received}.
  591. * Receiving tokens is disabled if the governance executor is other than the governor itself (eg. when using with a timelock).
  592. */
  593. function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) {
  594. if (_executor() != address(this)) {
  595. revert GovernorDisabledDeposit();
  596. }
  597. return this.onERC721Received.selector;
  598. }
  599. /**
  600. * @dev See {IERC1155Receiver-onERC1155Received}.
  601. * Receiving tokens is disabled if the governance executor is other than the governor itself (eg. when using with a timelock).
  602. */
  603. function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual returns (bytes4) {
  604. if (_executor() != address(this)) {
  605. revert GovernorDisabledDeposit();
  606. }
  607. return this.onERC1155Received.selector;
  608. }
  609. /**
  610. * @dev See {IERC1155Receiver-onERC1155BatchReceived}.
  611. * Receiving tokens is disabled if the governance executor is other than the governor itself (eg. when using with a timelock).
  612. */
  613. function onERC1155BatchReceived(
  614. address,
  615. address,
  616. uint256[] memory,
  617. uint256[] memory,
  618. bytes memory
  619. ) public virtual returns (bytes4) {
  620. if (_executor() != address(this)) {
  621. revert GovernorDisabledDeposit();
  622. }
  623. return this.onERC1155BatchReceived.selector;
  624. }
  625. /**
  626. * @dev Encodes a `ProposalState` into a `bytes32` representation where each bit enabled corresponds to
  627. * the underlying position in the `ProposalState` enum. For example:
  628. *
  629. * 0x000...10000
  630. * ^^^^^^------ ...
  631. * ^----- Succeeded
  632. * ^---- Defeated
  633. * ^--- Canceled
  634. * ^-- Active
  635. * ^- Pending
  636. */
  637. function _encodeStateBitmap(ProposalState proposalState) internal pure returns (bytes32) {
  638. return bytes32(1 << uint8(proposalState));
  639. }
  640. /**
  641. * @dev Check that the current state of a proposal matches the requirements described by the `allowedStates` bitmap.
  642. * This bitmap should be built using `_encodeStateBitmap`.
  643. *
  644. * If requirements are not met, reverts with a {GovernorUnexpectedProposalState} error.
  645. */
  646. function _validateStateBitmap(uint256 proposalId, bytes32 allowedStates) private view returns (ProposalState) {
  647. ProposalState currentState = state(proposalId);
  648. if (_encodeStateBitmap(currentState) & allowedStates == bytes32(0)) {
  649. revert GovernorUnexpectedProposalState(proposalId, currentState, allowedStates);
  650. }
  651. return currentState;
  652. }
  653. /*
  654. * @dev Check if the proposer is authorized to submit a proposal with the given description.
  655. *
  656. * If the proposal description ends with `#proposer=0x???`, where `0x???` is an address written as a hex string
  657. * (case insensitive), then the submission of this proposal will only be authorized to said address.
  658. *
  659. * This is used for frontrunning protection. By adding this pattern at the end of their proposal, one can ensure
  660. * that no other address can submit the same proposal. An attacker would have to either remove or change that part,
  661. * which would result in a different proposal id.
  662. *
  663. * If the description does not match this pattern, it is unrestricted and anyone can submit it. This includes:
  664. * - If the `0x???` part is not a valid hex string.
  665. * - If the `0x???` part is a valid hex string, but does not contain exactly 40 hex digits.
  666. * - If it ends with the expected suffix followed by newlines or other whitespace.
  667. * - If it ends with some other similar suffix, e.g. `#other=abc`.
  668. * - If it does not end with any such suffix.
  669. */
  670. function _isValidDescriptionForProposer(
  671. address proposer,
  672. string memory description
  673. ) internal view virtual returns (bool) {
  674. uint256 len = bytes(description).length;
  675. // Length is too short to contain a valid proposer suffix
  676. if (len < 52) {
  677. return true;
  678. }
  679. // Extract what would be the `#proposer=0x` marker beginning the suffix
  680. bytes12 marker;
  681. assembly {
  682. // - Start of the string contents in memory = description + 32
  683. // - First character of the marker = len - 52
  684. // - Length of "#proposer=0x0000000000000000000000000000000000000000" = 52
  685. // - We read the memory word starting at the first character of the marker:
  686. // - (description + 32) + (len - 52) = description + (len - 20)
  687. // - Note: Solidity will ignore anything past the first 12 bytes
  688. marker := mload(add(description, sub(len, 20)))
  689. }
  690. // If the marker is not found, there is no proposer suffix to check
  691. if (marker != bytes12("#proposer=0x")) {
  692. return true;
  693. }
  694. // Parse the 40 characters following the marker as uint160
  695. uint160 recovered = 0;
  696. for (uint256 i = len - 40; i < len; ++i) {
  697. (bool isHex, uint8 value) = _tryHexToUint(bytes(description)[i]);
  698. // If any of the characters is not a hex digit, ignore the suffix entirely
  699. if (!isHex) {
  700. return true;
  701. }
  702. recovered = (recovered << 4) | value;
  703. }
  704. return recovered == uint160(proposer);
  705. }
  706. /**
  707. * @dev Try to parse a character from a string as a hex value. Returns `(true, value)` if the char is in
  708. * `[0-9a-fA-F]` and `(false, 0)` otherwise. Value is guaranteed to be in the range `0 <= value < 16`
  709. */
  710. function _tryHexToUint(bytes1 char) private pure returns (bool, uint8) {
  711. uint8 c = uint8(char);
  712. unchecked {
  713. // Case 0-9
  714. if (47 < c && c < 58) {
  715. return (true, c - 48);
  716. }
  717. // Case A-F
  718. else if (64 < c && c < 71) {
  719. return (true, c - 55);
  720. }
  721. // Case a-f
  722. else if (96 < c && c < 103) {
  723. return (true, c - 87);
  724. }
  725. // Else: not a hex char
  726. else {
  727. return (false, 0);
  728. }
  729. }
  730. }
  731. /**
  732. * @inheritdoc IGovernor
  733. */
  734. function clock() public view virtual returns (uint48);
  735. /**
  736. * @inheritdoc IGovernor
  737. */
  738. // solhint-disable-next-line func-name-mixedcase
  739. function CLOCK_MODE() public view virtual returns (string memory);
  740. /**
  741. * @inheritdoc IGovernor
  742. */
  743. function votingDelay() public view virtual returns (uint256);
  744. /**
  745. * @inheritdoc IGovernor
  746. */
  747. function votingPeriod() public view virtual returns (uint256);
  748. /**
  749. * @inheritdoc IGovernor
  750. */
  751. function quorum(uint256 timepoint) public view virtual returns (uint256);
  752. }