Governor.sol 28 KB

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