Governor.sol 28 KB

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