Governor.sol 28 KB

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