Governor.sol 28 KB

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