Governor.sol 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  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 {_quorumReached}, {_voteSucceeded} and {_countVote}
  22. * - A voting module must implement {_getVotes}
  23. * - Additionally, {votingPeriod}, {votingDelay}, and {quorum} must also be implemented
  24. */
  25. abstract contract Governor is Context, ERC165, EIP712, Nonces, IGovernor, IERC721Receiver, IERC1155Receiver {
  26. using DoubleEndedQueue for DoubleEndedQueue.Bytes32Deque;
  27. bytes32 public constant BALLOT_TYPEHASH =
  28. keccak256("Ballot(uint256 proposalId,uint8 support,address voter,uint256 nonce)");
  29. bytes32 public constant EXTENDED_BALLOT_TYPEHASH =
  30. keccak256(
  31. "ExtendedBallot(uint256 proposalId,uint8 support,address voter,uint256 nonce,string reason,bytes params)"
  32. );
  33. struct ProposalCore {
  34. address proposer;
  35. uint48 voteStart;
  36. uint32 voteDuration;
  37. bool executed;
  38. bool canceled;
  39. uint48 etaSeconds;
  40. }
  41. bytes32 private constant ALL_PROPOSAL_STATES_BITMAP = bytes32((2 ** (uint8(type(ProposalState).max) + 1)) - 1);
  42. string private _name;
  43. mapping(uint256 proposalId => ProposalCore) private _proposals;
  44. // This queue keeps track of the governor operating on itself. Calls to functions protected by the {onlyGovernance}
  45. // modifier needs to be whitelisted in this queue. Whitelisting is set in {execute}, consumed by the
  46. // {onlyGovernance} modifier and eventually reset after {_executeOperations} completes. This ensures that the
  47. // execution of {onlyGovernance} protected calls can only be achieved through successful proposals.
  48. DoubleEndedQueue.Bytes32Deque private _governanceCall;
  49. /**
  50. * @dev Restricts a function so it can only be executed through governance proposals. For example, governance
  51. * parameter setters in {GovernorSettings} are protected using this modifier.
  52. *
  53. * The governance executing address may be different from the Governor's own address, for example it could be a
  54. * timelock. This can be customized by modules by overriding {_executor}. The executor is only able to invoke these
  55. * functions during the execution of the governor's {execute} function, and not under any other circumstances. Thus,
  56. * for example, additional timelock proposers are not able to change governance parameters without going through the
  57. * governance protocol (since v4.6).
  58. */
  59. modifier onlyGovernance() {
  60. _checkGovernance();
  61. _;
  62. }
  63. /**
  64. * @dev Sets the value for {name} and {version}
  65. */
  66. constructor(string memory name_) EIP712(name_, version()) {
  67. _name = name_;
  68. }
  69. /**
  70. * @dev Function to receive ETH that will be handled by the governor (disabled if executor is a third party contract)
  71. */
  72. receive() external payable virtual {
  73. if (_executor() != address(this)) {
  74. revert GovernorDisabledDeposit();
  75. }
  76. }
  77. /**
  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. address caller = _msgSender();
  423. if (!_validateCancel(proposalId, caller)) revert GovernorUnableToCancel(proposalId, caller);
  424. return _cancel(targets, values, calldatas, descriptionHash);
  425. }
  426. /**
  427. * @dev Internal cancel mechanism with minimal restrictions. A proposal can be cancelled in any state other than
  428. * Canceled, Expired, or Executed. Once cancelled a proposal can't be re-submitted.
  429. *
  430. * Emits a {IGovernor-ProposalCanceled} event.
  431. */
  432. function _cancel(
  433. address[] memory targets,
  434. uint256[] memory values,
  435. bytes[] memory calldatas,
  436. bytes32 descriptionHash
  437. ) internal virtual returns (uint256) {
  438. uint256 proposalId = getProposalId(targets, values, calldatas, descriptionHash);
  439. _validateStateBitmap(
  440. proposalId,
  441. ALL_PROPOSAL_STATES_BITMAP ^
  442. _encodeStateBitmap(ProposalState.Canceled) ^
  443. _encodeStateBitmap(ProposalState.Expired) ^
  444. _encodeStateBitmap(ProposalState.Executed)
  445. );
  446. _proposals[proposalId].canceled = true;
  447. emit ProposalCanceled(proposalId);
  448. return proposalId;
  449. }
  450. /**
  451. * @dev See {IGovernor-getVotes}.
  452. */
  453. function getVotes(address account, uint256 timepoint) public view virtual returns (uint256) {
  454. return _getVotes(account, timepoint, _defaultParams());
  455. }
  456. /**
  457. * @dev See {IGovernor-getVotesWithParams}.
  458. */
  459. function getVotesWithParams(
  460. address account,
  461. uint256 timepoint,
  462. bytes memory params
  463. ) public view virtual returns (uint256) {
  464. return _getVotes(account, timepoint, params);
  465. }
  466. /**
  467. * @dev See {IGovernor-castVote}.
  468. */
  469. function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256) {
  470. address voter = _msgSender();
  471. return _castVote(proposalId, voter, support, "");
  472. }
  473. /**
  474. * @dev See {IGovernor-castVoteWithReason}.
  475. */
  476. function castVoteWithReason(
  477. uint256 proposalId,
  478. uint8 support,
  479. string calldata reason
  480. ) public virtual returns (uint256) {
  481. address voter = _msgSender();
  482. return _castVote(proposalId, voter, support, reason);
  483. }
  484. /**
  485. * @dev See {IGovernor-castVoteWithReasonAndParams}.
  486. */
  487. function castVoteWithReasonAndParams(
  488. uint256 proposalId,
  489. uint8 support,
  490. string calldata reason,
  491. bytes memory params
  492. ) public virtual returns (uint256) {
  493. address voter = _msgSender();
  494. return _castVote(proposalId, voter, support, reason, params);
  495. }
  496. /**
  497. * @dev See {IGovernor-castVoteBySig}.
  498. */
  499. function castVoteBySig(
  500. uint256 proposalId,
  501. uint8 support,
  502. address voter,
  503. bytes memory signature
  504. ) public virtual returns (uint256) {
  505. bool valid = SignatureChecker.isValidSignatureNow(
  506. voter,
  507. _hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support, voter, _useNonce(voter)))),
  508. signature
  509. );
  510. if (!valid) {
  511. revert GovernorInvalidSignature(voter);
  512. }
  513. return _castVote(proposalId, voter, support, "");
  514. }
  515. /**
  516. * @dev See {IGovernor-castVoteWithReasonAndParamsBySig}.
  517. */
  518. function castVoteWithReasonAndParamsBySig(
  519. uint256 proposalId,
  520. uint8 support,
  521. address voter,
  522. string calldata reason,
  523. bytes memory params,
  524. bytes memory signature
  525. ) public virtual returns (uint256) {
  526. bool valid = SignatureChecker.isValidSignatureNow(
  527. voter,
  528. _hashTypedDataV4(
  529. keccak256(
  530. abi.encode(
  531. EXTENDED_BALLOT_TYPEHASH,
  532. proposalId,
  533. support,
  534. voter,
  535. _useNonce(voter),
  536. keccak256(bytes(reason)),
  537. keccak256(params)
  538. )
  539. )
  540. ),
  541. signature
  542. );
  543. if (!valid) {
  544. revert GovernorInvalidSignature(voter);
  545. }
  546. return _castVote(proposalId, voter, support, reason, params);
  547. }
  548. /**
  549. * @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
  550. * voting weight using {IGovernor-getVotes} and call the {_countVote} internal function. Uses the _defaultParams().
  551. *
  552. * Emits a {IGovernor-VoteCast} event.
  553. */
  554. function _castVote(
  555. uint256 proposalId,
  556. address account,
  557. uint8 support,
  558. string memory reason
  559. ) internal virtual returns (uint256) {
  560. return _castVote(proposalId, account, support, reason, _defaultParams());
  561. }
  562. /**
  563. * @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
  564. * voting weight using {IGovernor-getVotes} and call the {_countVote} internal function.
  565. *
  566. * Emits a {IGovernor-VoteCast} event.
  567. */
  568. function _castVote(
  569. uint256 proposalId,
  570. address account,
  571. uint8 support,
  572. string memory reason,
  573. bytes memory params
  574. ) internal virtual returns (uint256) {
  575. _validateStateBitmap(proposalId, _encodeStateBitmap(ProposalState.Active));
  576. uint256 totalWeight = _getVotes(account, proposalSnapshot(proposalId), params);
  577. uint256 votedWeight = _countVote(proposalId, account, support, totalWeight, params);
  578. if (params.length == 0) {
  579. emit VoteCast(account, proposalId, support, votedWeight, reason);
  580. } else {
  581. emit VoteCastWithParams(account, proposalId, support, votedWeight, reason, params);
  582. }
  583. _tallyUpdated(proposalId);
  584. return votedWeight;
  585. }
  586. /**
  587. * @dev Relays a transaction or function call to an arbitrary target. In cases where the governance executor
  588. * is some contract other than the governor itself, like when using a timelock, this function can be invoked
  589. * in a governance proposal to recover tokens or Ether that was sent to the governor contract by mistake.
  590. * Note that if the executor is simply the governor itself, use of `relay` is redundant.
  591. */
  592. function relay(address target, uint256 value, bytes calldata data) external payable virtual onlyGovernance {
  593. (bool success, bytes memory returndata) = target.call{value: value}(data);
  594. Address.verifyCallResult(success, returndata);
  595. }
  596. /**
  597. * @dev Address through which the governor executes action. Will be overloaded by module that execute actions
  598. * through another contract such as a timelock.
  599. */
  600. function _executor() internal view virtual returns (address) {
  601. return address(this);
  602. }
  603. /**
  604. * @dev See {IERC721Receiver-onERC721Received}.
  605. * Receiving tokens is disabled if the governance executor is other than the governor itself (eg. when using with a timelock).
  606. */
  607. function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) {
  608. if (_executor() != address(this)) {
  609. revert GovernorDisabledDeposit();
  610. }
  611. return this.onERC721Received.selector;
  612. }
  613. /**
  614. * @dev See {IERC1155Receiver-onERC1155Received}.
  615. * Receiving tokens is disabled if the governance executor is other than the governor itself (eg. when using with a timelock).
  616. */
  617. function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual returns (bytes4) {
  618. if (_executor() != address(this)) {
  619. revert GovernorDisabledDeposit();
  620. }
  621. return this.onERC1155Received.selector;
  622. }
  623. /**
  624. * @dev See {IERC1155Receiver-onERC1155BatchReceived}.
  625. * Receiving tokens is disabled if the governance executor is other than the governor itself (eg. when using with a timelock).
  626. */
  627. function onERC1155BatchReceived(
  628. address,
  629. address,
  630. uint256[] memory,
  631. uint256[] memory,
  632. bytes memory
  633. ) public virtual returns (bytes4) {
  634. if (_executor() != address(this)) {
  635. revert GovernorDisabledDeposit();
  636. }
  637. return this.onERC1155BatchReceived.selector;
  638. }
  639. /**
  640. * @dev Encodes a `ProposalState` into a `bytes32` representation where each bit enabled corresponds to
  641. * the underlying position in the `ProposalState` enum. For example:
  642. *
  643. * 0x000...10000
  644. * ^^^^^^------ ...
  645. * ^----- Succeeded
  646. * ^---- Defeated
  647. * ^--- Canceled
  648. * ^-- Active
  649. * ^- Pending
  650. */
  651. function _encodeStateBitmap(ProposalState proposalState) internal pure returns (bytes32) {
  652. return bytes32(1 << uint8(proposalState));
  653. }
  654. /**
  655. * @dev Check that the current state of a proposal matches the requirements described by the `allowedStates` bitmap.
  656. * This bitmap should be built using `_encodeStateBitmap`.
  657. *
  658. * If requirements are not met, reverts with a {GovernorUnexpectedProposalState} error.
  659. */
  660. function _validateStateBitmap(uint256 proposalId, bytes32 allowedStates) internal view returns (ProposalState) {
  661. ProposalState currentState = state(proposalId);
  662. if (_encodeStateBitmap(currentState) & allowedStates == bytes32(0)) {
  663. revert GovernorUnexpectedProposalState(proposalId, currentState, allowedStates);
  664. }
  665. return currentState;
  666. }
  667. /*
  668. * @dev Check if the proposer is authorized to submit a proposal with the given description.
  669. *
  670. * If the proposal description ends with `#proposer=0x???`, where `0x???` is an address written as a hex string
  671. * (case insensitive), then the submission of this proposal will only be authorized to said address.
  672. *
  673. * This is used for frontrunning protection. By adding this pattern at the end of their proposal, one can ensure
  674. * that no other address can submit the same proposal. An attacker would have to either remove or change that part,
  675. * which would result in a different proposal id.
  676. *
  677. * If the description does not match this pattern, it is unrestricted and anyone can submit it. This includes:
  678. * - If the `0x???` part is not a valid hex string.
  679. * - If the `0x???` part is a valid hex string, but does not contain exactly 40 hex digits.
  680. * - If it ends with the expected suffix followed by newlines or other whitespace.
  681. * - If it ends with some other similar suffix, e.g. `#other=abc`.
  682. * - If it does not end with any such suffix.
  683. */
  684. function _isValidDescriptionForProposer(
  685. address proposer,
  686. string memory description
  687. ) internal view virtual returns (bool) {
  688. unchecked {
  689. uint256 length = bytes(description).length;
  690. // Length is too short to contain a valid proposer suffix
  691. if (length < 52) {
  692. return true;
  693. }
  694. // Extract what would be the `#proposer=` marker beginning the suffix
  695. bytes10 marker = bytes10(_unsafeReadBytesOffset(bytes(description), length - 52));
  696. // If the marker is not found, there is no proposer suffix to check
  697. if (marker != bytes10("#proposer=")) {
  698. return true;
  699. }
  700. // Check that the last 42 characters (after the marker) are a properly formatted address.
  701. (bool success, address recovered) = Strings.tryParseAddress(description, length - 42, length);
  702. return !success || recovered == proposer;
  703. }
  704. }
  705. /**
  706. * @dev Check if the `caller` can cancel the proposal with the given `proposalId`.
  707. *
  708. * The default implementation allows the proposal proposer to cancel the proposal during the pending state.
  709. */
  710. function _validateCancel(uint256 proposalId, address caller) internal view virtual returns (bool) {
  711. return (state(proposalId) == ProposalState.Pending) && caller == proposalProposer(proposalId);
  712. }
  713. /**
  714. * @inheritdoc IERC6372
  715. */
  716. function clock() public view virtual returns (uint48);
  717. /**
  718. * @inheritdoc IERC6372
  719. */
  720. // solhint-disable-next-line func-name-mixedcase
  721. function CLOCK_MODE() public view virtual returns (string memory);
  722. /**
  723. * @inheritdoc IGovernor
  724. */
  725. function votingDelay() public view virtual returns (uint256);
  726. /**
  727. * @inheritdoc IGovernor
  728. */
  729. function votingPeriod() public view virtual returns (uint256);
  730. /**
  731. * @inheritdoc IGovernor
  732. */
  733. function quorum(uint256 timepoint) public view virtual returns (uint256);
  734. /**
  735. * @dev Reads a bytes32 from a bytes array without bounds checking.
  736. *
  737. * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
  738. * assembly block as such would prevent some optimizations.
  739. */
  740. function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
  741. // This is not memory safe in the general case, but all calls to this private function are within bounds.
  742. assembly ("memory-safe") {
  743. value := mload(add(buffer, add(0x20, offset)))
  744. }
  745. }
  746. }