Governor.sol 31 KB

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