Governor.sol 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  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. uint48 eta;
  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
  44. // {onlyGovernance} modifier needs to be whitelisted in this queue. Whitelisting is set in {_beforeExecute},
  45. // consumed by the {onlyGovernance} modifier and eventually reset in {_afterExecute}. 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 override returns (string memory) {
  89. return _name;
  90. }
  91. /**
  92. * @dev See {IGovernor-version}.
  93. */
  94. function version() public view virtual override 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 override 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 override returns (ProposalState) {
  122. // ProposalCore is just one slot. We can load it from storage to stack with 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 override returns (uint256) {
  155. return 0;
  156. }
  157. /**
  158. * @dev See {IGovernor-proposalSnapshot}.
  159. */
  160. function proposalSnapshot(uint256 proposalId) public view virtual override returns (uint256) {
  161. return _proposals[proposalId].voteStart;
  162. }
  163. /**
  164. * @dev See {IGovernor-proposalDeadline}.
  165. */
  166. function proposalDeadline(uint256 proposalId) public view virtual override 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 override returns (address) {
  173. return _proposals[proposalId].proposer;
  174. }
  175. /**
  176. * @dev See {IGovernor-proposalEta}.
  177. */
  178. function proposalEta(uint256 proposalId) public view virtual override returns (uint256) {
  179. return _proposals[proposalId].eta;
  180. }
  181. /**
  182. * @dev Reverts if the `msg.sender` is not the executor. In case the executor is not this contract
  183. * itself, the function reverts if `msg.data` is not whitelisted as a result of an {execute}
  184. * operation. See {onlyGovernance}.
  185. */
  186. function _checkGovernance() internal virtual {
  187. if (_executor() != _msgSender()) {
  188. revert GovernorOnlyExecutor(_msgSender());
  189. }
  190. if (_executor() != address(this)) {
  191. bytes32 msgDataHash = keccak256(_msgData());
  192. // loop until popping the expected operation - throw if deque is empty (operation not authorized)
  193. while (_governanceCall.popFront() != msgDataHash) {}
  194. }
  195. }
  196. /**
  197. * @dev Amount of votes already cast passes the threshold limit.
  198. */
  199. function _quorumReached(uint256 proposalId) internal view virtual returns (bool);
  200. /**
  201. * @dev Is the proposal successful or not.
  202. */
  203. function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool);
  204. /**
  205. * @dev Get the voting weight of `account` at a specific `timepoint`, for a vote as described by `params`.
  206. */
  207. function _getVotes(address account, uint256 timepoint, bytes memory params) internal view virtual returns (uint256);
  208. /**
  209. * @dev Register a vote for `proposalId` by `account` with a given `support`, voting `weight` and voting `params`.
  210. *
  211. * Note: Support is generic and can represent various things depending on the voting system used.
  212. */
  213. function _countVote(
  214. uint256 proposalId,
  215. address account,
  216. uint8 support,
  217. uint256 weight,
  218. bytes memory params
  219. ) internal virtual;
  220. /**
  221. * @dev Default additional encoded parameters used by castVote methods that don't include them
  222. *
  223. * Note: Should be overridden by specific implementations to use an appropriate value, the
  224. * meaning of the additional params, in the context of that implementation
  225. */
  226. function _defaultParams() internal view virtual returns (bytes memory) {
  227. return "";
  228. }
  229. /**
  230. * @dev See {IGovernor-propose}. This function has opt-in frontrunning protection, described in {_isValidDescriptionForProposer}.
  231. */
  232. function propose(
  233. address[] memory targets,
  234. uint256[] memory values,
  235. bytes[] memory calldatas,
  236. string memory description
  237. ) public virtual override returns (uint256) {
  238. address proposer = _msgSender();
  239. // check description restriction
  240. if (!_isValidDescriptionForProposer(proposer, description)) {
  241. revert GovernorRestrictedProposer(proposer);
  242. }
  243. // check proposal threshold
  244. uint256 proposerVotes = getVotes(proposer, clock() - 1);
  245. uint256 votesThreshold = proposalThreshold();
  246. if (proposerVotes < votesThreshold) {
  247. revert GovernorInsufficientProposerVotes(proposer, proposerVotes, votesThreshold);
  248. }
  249. return _propose(targets, values, calldatas, description, proposer);
  250. }
  251. /**
  252. * @dev Internal propose mechanism. Can be overridden to add more logic on proposal creation.
  253. *
  254. * Emits a {IGovernor-ProposalCreated} event.
  255. */
  256. function _propose(
  257. address[] memory targets,
  258. uint256[] memory values,
  259. bytes[] memory calldatas,
  260. string memory description,
  261. address proposer
  262. ) internal virtual returns (uint256) {
  263. uint256 proposalId = hashProposal(targets, values, calldatas, keccak256(bytes(description)));
  264. if (targets.length != values.length || targets.length != calldatas.length || targets.length == 0) {
  265. revert GovernorInvalidProposalLength(targets.length, calldatas.length, values.length);
  266. }
  267. if (_proposals[proposalId].voteStart != 0) {
  268. revert GovernorUnexpectedProposalState(proposalId, state(proposalId), bytes32(0));
  269. }
  270. uint256 snapshot = clock() + votingDelay();
  271. uint256 duration = votingPeriod();
  272. ProposalCore storage proposal = _proposals[proposalId];
  273. proposal.proposer = proposer;
  274. proposal.voteStart = SafeCast.toUint48(snapshot);
  275. proposal.voteDuration = SafeCast.toUint32(duration);
  276. emit ProposalCreated(
  277. proposalId,
  278. proposer,
  279. targets,
  280. values,
  281. new string[](targets.length),
  282. calldatas,
  283. snapshot,
  284. snapshot + duration,
  285. description
  286. );
  287. return proposalId;
  288. }
  289. /**
  290. * @dev See {IGovernor-queue}.
  291. */
  292. function queue(
  293. address[] memory targets,
  294. uint256[] memory values,
  295. bytes[] memory calldatas,
  296. bytes32 descriptionHash
  297. ) public virtual override returns (uint256) {
  298. uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
  299. _validateStateBitmap(proposalId, _encodeStateBitmap(ProposalState.Succeeded));
  300. uint48 eta = _queueOperations(proposalId, targets, values, calldatas, descriptionHash);
  301. if (eta != 0) {
  302. _proposals[proposalId].eta = eta;
  303. emit ProposalQueued(proposalId, eta);
  304. } else {
  305. revert GovernorQueueNotImplemented();
  306. }
  307. return proposalId;
  308. }
  309. /**
  310. * @dev Internal queuing mechanism. Can be overridden (without a super call) to modify the way queuing is
  311. * performed (for example adding a vault/timelock).
  312. *
  313. * This is empty by default, and must be overridden to implement queuing.
  314. *
  315. * This function returns a timestamp that describes the expected eta for execution. If the returned value is 0
  316. * (which is the default value), the core will consider queueing did not succeed, and the public {queue} function
  317. * will revert.
  318. *
  319. * NOTE: Calling this function directly will NOT check the current state of the proposal, or emit the
  320. * `ProposalQueued` event. Queuing a proposal should be done using {queue} or {_queue}.
  321. */
  322. function _queueOperations(
  323. uint256 /*proposalId*/,
  324. address[] memory /*targets*/,
  325. uint256[] memory /*values*/,
  326. bytes[] memory /*calldatas*/,
  327. bytes32 /*descriptionHash*/
  328. ) internal virtual returns (uint48) {
  329. return 0;
  330. }
  331. /**
  332. * @dev See {IGovernor-execute}.
  333. */
  334. function execute(
  335. address[] memory targets,
  336. uint256[] memory values,
  337. bytes[] memory calldatas,
  338. bytes32 descriptionHash
  339. ) public payable virtual override returns (uint256) {
  340. uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
  341. _validateStateBitmap(
  342. proposalId,
  343. _encodeStateBitmap(ProposalState.Succeeded) | _encodeStateBitmap(ProposalState.Queued)
  344. );
  345. // mark as executed before calls to avoid reentrancy
  346. _proposals[proposalId].executed = true;
  347. // before execute: register governance call in queue.
  348. if (_executor() != address(this)) {
  349. for (uint256 i = 0; i < targets.length; ++i) {
  350. if (targets[i] == address(this)) {
  351. _governanceCall.pushBack(keccak256(calldatas[i]));
  352. }
  353. }
  354. }
  355. _executeOperations(proposalId, targets, values, calldatas, descriptionHash);
  356. // after execute: cleanup governance call queue.
  357. if (_executor() != address(this) && !_governanceCall.empty()) {
  358. _governanceCall.clear();
  359. }
  360. emit ProposalExecuted(proposalId);
  361. return proposalId;
  362. }
  363. /**
  364. * @dev Internal execution mechanism. Can be overridden (without a super call) to modify the way execution is
  365. * performed (for example adding a vault/timelock).
  366. *
  367. * NOTE: Calling this function directly will NOT check the current state of the proposal, set the executed flag to
  368. * true or emit the `ProposalExecuted` event. Executing a proposal should be done using {execute} or {_execute}.
  369. */
  370. function _executeOperations(
  371. uint256 /* proposalId */,
  372. address[] memory targets,
  373. uint256[] memory values,
  374. bytes[] memory calldatas,
  375. bytes32 /*descriptionHash*/
  376. ) internal virtual {
  377. for (uint256 i = 0; i < targets.length; ++i) {
  378. (bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]);
  379. Address.verifyCallResult(success, returndata);
  380. }
  381. }
  382. /**
  383. * @dev See {IGovernor-cancel}.
  384. */
  385. function cancel(
  386. address[] memory targets,
  387. uint256[] memory values,
  388. bytes[] memory calldatas,
  389. bytes32 descriptionHash
  390. ) public virtual override returns (uint256) {
  391. // The proposalId will be recomputed in the `_cancel` call further down. However we need the value before we
  392. // do the internal call, because we need to check the proposal state BEFORE the internal `_cancel` call
  393. // changes it. The `hashProposal` duplication has a cost that is limited, and that we accept.
  394. uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
  395. // public cancel restrictions (on top of existing _cancel restrictions).
  396. _validateStateBitmap(proposalId, _encodeStateBitmap(ProposalState.Pending));
  397. if (_msgSender() != proposalProposer(proposalId)) {
  398. revert GovernorOnlyProposer(_msgSender());
  399. }
  400. return _cancel(targets, values, calldatas, descriptionHash);
  401. }
  402. /**
  403. * @dev Internal cancel mechanism with minimal restrictions. A proposal can be cancelled in any state other than
  404. * Canceled, Expired, or Executed. Once cancelled a proposal can't be re-submitted.
  405. *
  406. * Emits a {IGovernor-ProposalCanceled} event.
  407. */
  408. function _cancel(
  409. address[] memory targets,
  410. uint256[] memory values,
  411. bytes[] memory calldatas,
  412. bytes32 descriptionHash
  413. ) internal virtual returns (uint256) {
  414. uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
  415. _validateStateBitmap(
  416. proposalId,
  417. _ALL_PROPOSAL_STATES_BITMAP ^
  418. _encodeStateBitmap(ProposalState.Canceled) ^
  419. _encodeStateBitmap(ProposalState.Expired) ^
  420. _encodeStateBitmap(ProposalState.Executed)
  421. );
  422. _proposals[proposalId].canceled = true;
  423. emit ProposalCanceled(proposalId);
  424. return proposalId;
  425. }
  426. /**
  427. * @dev See {IGovernor-getVotes}.
  428. */
  429. function getVotes(address account, uint256 timepoint) public view virtual override returns (uint256) {
  430. return _getVotes(account, timepoint, _defaultParams());
  431. }
  432. /**
  433. * @dev See {IGovernor-getVotesWithParams}.
  434. */
  435. function getVotesWithParams(
  436. address account,
  437. uint256 timepoint,
  438. bytes memory params
  439. ) public view virtual override returns (uint256) {
  440. return _getVotes(account, timepoint, params);
  441. }
  442. /**
  443. * @dev See {IGovernor-castVote}.
  444. */
  445. function castVote(uint256 proposalId, uint8 support) public virtual override returns (uint256) {
  446. address voter = _msgSender();
  447. return _castVote(proposalId, voter, support, "");
  448. }
  449. /**
  450. * @dev See {IGovernor-castVoteWithReason}.
  451. */
  452. function castVoteWithReason(
  453. uint256 proposalId,
  454. uint8 support,
  455. string calldata reason
  456. ) public virtual override returns (uint256) {
  457. address voter = _msgSender();
  458. return _castVote(proposalId, voter, support, reason);
  459. }
  460. /**
  461. * @dev See {IGovernor-castVoteWithReasonAndParams}.
  462. */
  463. function castVoteWithReasonAndParams(
  464. uint256 proposalId,
  465. uint8 support,
  466. string calldata reason,
  467. bytes memory params
  468. ) public virtual override returns (uint256) {
  469. address voter = _msgSender();
  470. return _castVote(proposalId, voter, support, reason, params);
  471. }
  472. /**
  473. * @dev See {IGovernor-castVoteBySig}.
  474. */
  475. function castVoteBySig(
  476. uint256 proposalId,
  477. uint8 support,
  478. address voter,
  479. bytes memory signature
  480. ) public virtual override returns (uint256) {
  481. bool valid = SignatureChecker.isValidSignatureNow(
  482. voter,
  483. _hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support, voter, _useNonce(voter)))),
  484. signature
  485. );
  486. if (!valid) {
  487. revert GovernorInvalidSignature(voter);
  488. }
  489. return _castVote(proposalId, voter, support, "");
  490. }
  491. /**
  492. * @dev See {IGovernor-castVoteWithReasonAndParamsBySig}.
  493. */
  494. function castVoteWithReasonAndParamsBySig(
  495. uint256 proposalId,
  496. uint8 support,
  497. address voter,
  498. string calldata reason,
  499. bytes memory params,
  500. bytes memory signature
  501. ) public virtual override returns (uint256) {
  502. bool valid = SignatureChecker.isValidSignatureNow(
  503. voter,
  504. _hashTypedDataV4(
  505. keccak256(
  506. abi.encode(
  507. EXTENDED_BALLOT_TYPEHASH,
  508. proposalId,
  509. support,
  510. voter,
  511. _useNonce(voter),
  512. keccak256(bytes(reason)),
  513. keccak256(params)
  514. )
  515. )
  516. ),
  517. signature
  518. );
  519. if (!valid) {
  520. revert GovernorInvalidSignature(voter);
  521. }
  522. return _castVote(proposalId, voter, support, reason, params);
  523. }
  524. /**
  525. * @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
  526. * voting weight using {IGovernor-getVotes} and call the {_countVote} internal function. Uses the _defaultParams().
  527. *
  528. * Emits a {IGovernor-VoteCast} event.
  529. */
  530. function _castVote(
  531. uint256 proposalId,
  532. address account,
  533. uint8 support,
  534. string memory reason
  535. ) internal virtual returns (uint256) {
  536. return _castVote(proposalId, account, support, reason, _defaultParams());
  537. }
  538. /**
  539. * @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
  540. * voting weight using {IGovernor-getVotes} and call the {_countVote} internal function.
  541. *
  542. * Emits a {IGovernor-VoteCast} event.
  543. */
  544. function _castVote(
  545. uint256 proposalId,
  546. address account,
  547. uint8 support,
  548. string memory reason,
  549. bytes memory params
  550. ) internal virtual returns (uint256) {
  551. ProposalState currentState = state(proposalId);
  552. if (currentState != ProposalState.Active) {
  553. revert GovernorUnexpectedProposalState(proposalId, currentState, _encodeStateBitmap(ProposalState.Active));
  554. }
  555. uint256 weight = _getVotes(account, proposalSnapshot(proposalId), params);
  556. _countVote(proposalId, account, support, weight, params);
  557. if (params.length == 0) {
  558. emit VoteCast(account, proposalId, support, weight, reason);
  559. } else {
  560. emit VoteCastWithParams(account, proposalId, support, weight, reason, params);
  561. }
  562. return weight;
  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) private 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. uint256 len = bytes(description).length;
  667. // Length is too short to contain a valid proposer suffix
  668. if (len < 52) {
  669. return true;
  670. }
  671. // Extract what would be the `#proposer=0x` marker beginning the suffix
  672. bytes12 marker;
  673. assembly {
  674. // - Start of the string contents in memory = description + 32
  675. // - First character of the marker = len - 52
  676. // - Length of "#proposer=0x0000000000000000000000000000000000000000" = 52
  677. // - We read the memory word starting at the first character of the marker:
  678. // - (description + 32) + (len - 52) = description + (len - 20)
  679. // - Note: Solidity will ignore anything past the first 12 bytes
  680. marker := mload(add(description, sub(len, 20)))
  681. }
  682. // If the marker is not found, there is no proposer suffix to check
  683. if (marker != bytes12("#proposer=0x")) {
  684. return true;
  685. }
  686. // Parse the 40 characters following the marker as uint160
  687. uint160 recovered = 0;
  688. for (uint256 i = len - 40; i < len; ++i) {
  689. (bool isHex, uint8 value) = _tryHexToUint(bytes(description)[i]);
  690. // If any of the characters is not a hex digit, ignore the suffix entirely
  691. if (!isHex) {
  692. return true;
  693. }
  694. recovered = (recovered << 4) | value;
  695. }
  696. return recovered == uint160(proposer);
  697. }
  698. /**
  699. * @dev Try to parse a character from a string as a hex value. Returns `(true, value)` if the char is in
  700. * `[0-9a-fA-F]` and `(false, 0)` otherwise. Value is guaranteed to be in the range `0 <= value < 16`
  701. */
  702. function _tryHexToUint(bytes1 char) private pure returns (bool, uint8) {
  703. uint8 c = uint8(char);
  704. unchecked {
  705. // Case 0-9
  706. if (47 < c && c < 58) {
  707. return (true, c - 48);
  708. }
  709. // Case A-F
  710. else if (64 < c && c < 71) {
  711. return (true, c - 55);
  712. }
  713. // Case a-f
  714. else if (96 < c && c < 103) {
  715. return (true, c - 87);
  716. }
  717. // Else: not a hex char
  718. else {
  719. return (false, 0);
  720. }
  721. }
  722. }
  723. /**
  724. * @inheritdoc IERC6372
  725. */
  726. function clock() public view virtual returns (uint48);
  727. /**
  728. * @inheritdoc IERC6372
  729. */
  730. // solhint-disable-next-line func-name-mixedcase
  731. function CLOCK_MODE() public view virtual returns (string memory);
  732. /**
  733. * @inheritdoc IGovernor
  734. */
  735. function votingDelay() public view virtual returns (uint256);
  736. /**
  737. * @inheritdoc IGovernor
  738. */
  739. function votingPeriod() public view virtual returns (uint256);
  740. /**
  741. * @inheritdoc IGovernor
  742. */
  743. function quorum(uint256 timepoint) public view virtual returns (uint256);
  744. }