TimelockController.sol 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.9.0) (governance/TimelockController.sol)
  3. pragma solidity ^0.8.19;
  4. import {AccessControl} from "../access/AccessControl.sol";
  5. import {ERC721Holder} from "../token/ERC721/utils/ERC721Holder.sol";
  6. import {ERC1155Holder} from "../token/ERC1155/utils/ERC1155Holder.sol";
  7. import {ERC1155Receiver} from "../token/ERC1155/utils/ERC1155Receiver.sol";
  8. import {Address} from "../utils/Address.sol";
  9. /**
  10. * @dev Contract module which acts as a timelocked controller. When set as the
  11. * owner of an `Ownable` smart contract, it enforces a timelock on all
  12. * `onlyOwner` maintenance operations. This gives time for users of the
  13. * controlled contract to exit before a potentially dangerous maintenance
  14. * operation is applied.
  15. *
  16. * By default, this contract is self administered, meaning administration tasks
  17. * have to go through the timelock process. The proposer (resp executor) role
  18. * is in charge of proposing (resp executing) operations. A common use case is
  19. * to position this {TimelockController} as the owner of a smart contract, with
  20. * a multisig or a DAO as the sole proposer.
  21. */
  22. contract TimelockController is AccessControl, ERC721Holder, ERC1155Holder {
  23. bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE");
  24. bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE");
  25. bytes32 public constant CANCELLER_ROLE = keccak256("CANCELLER_ROLE");
  26. uint256 internal constant _DONE_TIMESTAMP = uint256(1);
  27. mapping(bytes32 => uint256) private _timestamps;
  28. uint256 private _minDelay;
  29. enum OperationState {
  30. Unset,
  31. Waiting,
  32. Ready,
  33. Done
  34. }
  35. /**
  36. * @dev Mismatch between the parameters length for an operation call.
  37. */
  38. error TimelockInvalidOperationLength(uint256 targets, uint256 payloads, uint256 values);
  39. /**
  40. * @dev The schedule operation doesn't meet the minimum delay.
  41. */
  42. error TimelockInsufficientDelay(uint256 delay, uint256 minDelay);
  43. /**
  44. * @dev The current state of an operation is not as required.
  45. * The `expectedStates` is a bitmap with the bits enabled for each OperationState enum position
  46. * counting from right to left.
  47. *
  48. * See {_encodeStateBitmap}.
  49. */
  50. error TimelockUnexpectedOperationState(bytes32 operationId, bytes32 expectedStates);
  51. /**
  52. * @dev The predecessor to an operation not yet done.
  53. */
  54. error TimelockUnexecutedPredecessor(bytes32 predecessorId);
  55. /**
  56. * @dev The caller account is not authorized.
  57. */
  58. error TimelockUnauthorizedCaller(address caller);
  59. /**
  60. * @dev Emitted when a call is scheduled as part of operation `id`.
  61. */
  62. event CallScheduled(
  63. bytes32 indexed id,
  64. uint256 indexed index,
  65. address target,
  66. uint256 value,
  67. bytes data,
  68. bytes32 predecessor,
  69. uint256 delay
  70. );
  71. /**
  72. * @dev Emitted when a call is performed as part of operation `id`.
  73. */
  74. event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data);
  75. /**
  76. * @dev Emitted when new proposal is scheduled with non-zero salt.
  77. */
  78. event CallSalt(bytes32 indexed id, bytes32 salt);
  79. /**
  80. * @dev Emitted when operation `id` is cancelled.
  81. */
  82. event Cancelled(bytes32 indexed id);
  83. /**
  84. * @dev Emitted when the minimum delay for future operations is modified.
  85. */
  86. event MinDelayChange(uint256 oldDuration, uint256 newDuration);
  87. /**
  88. * @dev Initializes the contract with the following parameters:
  89. *
  90. * - `minDelay`: initial minimum delay for operations
  91. * - `proposers`: accounts to be granted proposer and canceller roles
  92. * - `executors`: accounts to be granted executor role
  93. * - `admin`: optional account to be granted admin role; disable with zero address
  94. *
  95. * IMPORTANT: The optional admin can aid with initial configuration of roles after deployment
  96. * without being subject to delay, but this role should be subsequently renounced in favor of
  97. * administration through timelocked proposals. Previous versions of this contract would assign
  98. * this admin to the deployer automatically and should be renounced as well.
  99. */
  100. constructor(uint256 minDelay, address[] memory proposers, address[] memory executors, address admin) {
  101. // self administration
  102. _grantRole(DEFAULT_ADMIN_ROLE, address(this));
  103. // optional admin
  104. if (admin != address(0)) {
  105. _grantRole(DEFAULT_ADMIN_ROLE, admin);
  106. }
  107. // register proposers and cancellers
  108. for (uint256 i = 0; i < proposers.length; ++i) {
  109. _grantRole(PROPOSER_ROLE, proposers[i]);
  110. _grantRole(CANCELLER_ROLE, proposers[i]);
  111. }
  112. // register executors
  113. for (uint256 i = 0; i < executors.length; ++i) {
  114. _grantRole(EXECUTOR_ROLE, executors[i]);
  115. }
  116. _minDelay = minDelay;
  117. emit MinDelayChange(0, minDelay);
  118. }
  119. /**
  120. * @dev Modifier to make a function callable only by a certain role. In
  121. * addition to checking the sender's role, `address(0)` 's role is also
  122. * considered. Granting a role to `address(0)` is equivalent to enabling
  123. * this role for everyone.
  124. */
  125. modifier onlyRoleOrOpenRole(bytes32 role) {
  126. if (!hasRole(role, address(0))) {
  127. _checkRole(role, _msgSender());
  128. }
  129. _;
  130. }
  131. /**
  132. * @dev Contract might receive/hold ETH as part of the maintenance process.
  133. */
  134. receive() external payable {}
  135. /**
  136. * @dev See {IERC165-supportsInterface}.
  137. */
  138. function supportsInterface(
  139. bytes4 interfaceId
  140. ) public view virtual override(AccessControl, ERC1155Receiver) returns (bool) {
  141. return super.supportsInterface(interfaceId);
  142. }
  143. /**
  144. * @dev Returns whether an id correspond to a registered operation. This
  145. * includes both Pending, Ready and Done operations.
  146. */
  147. function isOperation(bytes32 id) public view returns (bool) {
  148. return getOperationState(id) != OperationState.Unset;
  149. }
  150. /**
  151. * @dev Returns whether an operation is pending or not. Note that a "pending" operation may also be "ready".
  152. */
  153. function isOperationPending(bytes32 id) public view returns (bool) {
  154. OperationState state = getOperationState(id);
  155. return state == OperationState.Waiting || state == OperationState.Ready;
  156. }
  157. /**
  158. * @dev Returns whether an operation is ready for execution. Note that a "ready" operation is also "pending".
  159. */
  160. function isOperationReady(bytes32 id) public view returns (bool) {
  161. return getOperationState(id) == OperationState.Ready;
  162. }
  163. /**
  164. * @dev Returns whether an operation is done or not.
  165. */
  166. function isOperationDone(bytes32 id) public view returns (bool) {
  167. return getOperationState(id) == OperationState.Done;
  168. }
  169. /**
  170. * @dev Returns the timestamp at which an operation becomes ready (0 for
  171. * unset operations, 1 for done operations).
  172. */
  173. function getTimestamp(bytes32 id) public view virtual returns (uint256) {
  174. return _timestamps[id];
  175. }
  176. /**
  177. * @dev Returns operation state.
  178. */
  179. function getOperationState(bytes32 id) public view virtual returns (OperationState) {
  180. uint256 timestamp = getTimestamp(id);
  181. if (timestamp == 0) {
  182. return OperationState.Unset;
  183. } else if (timestamp == _DONE_TIMESTAMP) {
  184. return OperationState.Done;
  185. } else if (timestamp > block.timestamp) {
  186. return OperationState.Waiting;
  187. } else {
  188. return OperationState.Ready;
  189. }
  190. }
  191. /**
  192. * @dev Returns the minimum delay for an operation to become valid.
  193. *
  194. * This value can be changed by executing an operation that calls `updateDelay`.
  195. */
  196. function getMinDelay() public view virtual returns (uint256) {
  197. return _minDelay;
  198. }
  199. /**
  200. * @dev Returns the identifier of an operation containing a single
  201. * transaction.
  202. */
  203. function hashOperation(
  204. address target,
  205. uint256 value,
  206. bytes calldata data,
  207. bytes32 predecessor,
  208. bytes32 salt
  209. ) public pure virtual returns (bytes32) {
  210. return keccak256(abi.encode(target, value, data, predecessor, salt));
  211. }
  212. /**
  213. * @dev Returns the identifier of an operation containing a batch of
  214. * transactions.
  215. */
  216. function hashOperationBatch(
  217. address[] calldata targets,
  218. uint256[] calldata values,
  219. bytes[] calldata payloads,
  220. bytes32 predecessor,
  221. bytes32 salt
  222. ) public pure virtual returns (bytes32) {
  223. return keccak256(abi.encode(targets, values, payloads, predecessor, salt));
  224. }
  225. /**
  226. * @dev Schedule an operation containing a single transaction.
  227. *
  228. * Emits {CallSalt} if salt is nonzero, and {CallScheduled}.
  229. *
  230. * Requirements:
  231. *
  232. * - the caller must have the 'proposer' role.
  233. */
  234. function schedule(
  235. address target,
  236. uint256 value,
  237. bytes calldata data,
  238. bytes32 predecessor,
  239. bytes32 salt,
  240. uint256 delay
  241. ) public virtual onlyRole(PROPOSER_ROLE) {
  242. bytes32 id = hashOperation(target, value, data, predecessor, salt);
  243. _schedule(id, delay);
  244. emit CallScheduled(id, 0, target, value, data, predecessor, delay);
  245. if (salt != bytes32(0)) {
  246. emit CallSalt(id, salt);
  247. }
  248. }
  249. /**
  250. * @dev Schedule an operation containing a batch of transactions.
  251. *
  252. * Emits {CallSalt} if salt is nonzero, and one {CallScheduled} event per transaction in the batch.
  253. *
  254. * Requirements:
  255. *
  256. * - the caller must have the 'proposer' role.
  257. */
  258. function scheduleBatch(
  259. address[] calldata targets,
  260. uint256[] calldata values,
  261. bytes[] calldata payloads,
  262. bytes32 predecessor,
  263. bytes32 salt,
  264. uint256 delay
  265. ) public virtual onlyRole(PROPOSER_ROLE) {
  266. if (targets.length != values.length || targets.length != payloads.length) {
  267. revert TimelockInvalidOperationLength(targets.length, payloads.length, values.length);
  268. }
  269. bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt);
  270. _schedule(id, delay);
  271. for (uint256 i = 0; i < targets.length; ++i) {
  272. emit CallScheduled(id, i, targets[i], values[i], payloads[i], predecessor, delay);
  273. }
  274. if (salt != bytes32(0)) {
  275. emit CallSalt(id, salt);
  276. }
  277. }
  278. /**
  279. * @dev Schedule an operation that is to become valid after a given delay.
  280. */
  281. function _schedule(bytes32 id, uint256 delay) private {
  282. if (isOperation(id)) {
  283. revert TimelockUnexpectedOperationState(id, _encodeStateBitmap(OperationState.Unset));
  284. }
  285. uint256 minDelay = getMinDelay();
  286. if (delay < minDelay) {
  287. revert TimelockInsufficientDelay(delay, minDelay);
  288. }
  289. _timestamps[id] = block.timestamp + delay;
  290. }
  291. /**
  292. * @dev Cancel an operation.
  293. *
  294. * Requirements:
  295. *
  296. * - the caller must have the 'canceller' role.
  297. */
  298. function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) {
  299. if (!isOperationPending(id)) {
  300. revert TimelockUnexpectedOperationState(
  301. id,
  302. _encodeStateBitmap(OperationState.Waiting) | _encodeStateBitmap(OperationState.Ready)
  303. );
  304. }
  305. delete _timestamps[id];
  306. emit Cancelled(id);
  307. }
  308. /**
  309. * @dev Execute an (ready) operation containing a single transaction.
  310. *
  311. * Emits a {CallExecuted} event.
  312. *
  313. * Requirements:
  314. *
  315. * - the caller must have the 'executor' role.
  316. */
  317. // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,
  318. // thus any modifications to the operation during reentrancy should be caught.
  319. // slither-disable-next-line reentrancy-eth
  320. function execute(
  321. address target,
  322. uint256 value,
  323. bytes calldata payload,
  324. bytes32 predecessor,
  325. bytes32 salt
  326. ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
  327. bytes32 id = hashOperation(target, value, payload, predecessor, salt);
  328. _beforeCall(id, predecessor);
  329. _execute(target, value, payload);
  330. emit CallExecuted(id, 0, target, value, payload);
  331. _afterCall(id);
  332. }
  333. /**
  334. * @dev Execute an (ready) operation containing a batch of transactions.
  335. *
  336. * Emits one {CallExecuted} event per transaction in the batch.
  337. *
  338. * Requirements:
  339. *
  340. * - the caller must have the 'executor' role.
  341. */
  342. // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,
  343. // thus any modifications to the operation during reentrancy should be caught.
  344. // slither-disable-next-line reentrancy-eth
  345. function executeBatch(
  346. address[] calldata targets,
  347. uint256[] calldata values,
  348. bytes[] calldata payloads,
  349. bytes32 predecessor,
  350. bytes32 salt
  351. ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
  352. if (targets.length != values.length || targets.length != payloads.length) {
  353. revert TimelockInvalidOperationLength(targets.length, payloads.length, values.length);
  354. }
  355. bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt);
  356. _beforeCall(id, predecessor);
  357. for (uint256 i = 0; i < targets.length; ++i) {
  358. address target = targets[i];
  359. uint256 value = values[i];
  360. bytes calldata payload = payloads[i];
  361. _execute(target, value, payload);
  362. emit CallExecuted(id, i, target, value, payload);
  363. }
  364. _afterCall(id);
  365. }
  366. /**
  367. * @dev Execute an operation's call.
  368. */
  369. function _execute(address target, uint256 value, bytes calldata data) internal virtual {
  370. (bool success, bytes memory returndata) = target.call{value: value}(data);
  371. Address.verifyCallResult(success, returndata);
  372. }
  373. /**
  374. * @dev Checks before execution of an operation's calls.
  375. */
  376. function _beforeCall(bytes32 id, bytes32 predecessor) private view {
  377. if (!isOperationReady(id)) {
  378. revert TimelockUnexpectedOperationState(id, _encodeStateBitmap(OperationState.Ready));
  379. }
  380. if (predecessor != bytes32(0) && !isOperationDone(predecessor)) {
  381. revert TimelockUnexecutedPredecessor(predecessor);
  382. }
  383. }
  384. /**
  385. * @dev Checks after execution of an operation's calls.
  386. */
  387. function _afterCall(bytes32 id) private {
  388. if (!isOperationReady(id)) {
  389. revert TimelockUnexpectedOperationState(id, _encodeStateBitmap(OperationState.Ready));
  390. }
  391. _timestamps[id] = _DONE_TIMESTAMP;
  392. }
  393. /**
  394. * @dev Changes the minimum timelock duration for future operations.
  395. *
  396. * Emits a {MinDelayChange} event.
  397. *
  398. * Requirements:
  399. *
  400. * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing
  401. * an operation where the timelock is the target and the data is the ABI-encoded call to this function.
  402. */
  403. function updateDelay(uint256 newDelay) external virtual {
  404. address sender = _msgSender();
  405. if (sender != address(this)) {
  406. revert TimelockUnauthorizedCaller(sender);
  407. }
  408. emit MinDelayChange(_minDelay, newDelay);
  409. _minDelay = newDelay;
  410. }
  411. /**
  412. * @dev Encodes a `OperationState` into a `bytes32` representation where each bit enabled corresponds to
  413. * the underlying position in the `OperationState` enum. For example:
  414. *
  415. * 0x000...1000
  416. * ^^^^^^----- ...
  417. * ^---- Done
  418. * ^--- Ready
  419. * ^-- Waiting
  420. * ^- Unset
  421. */
  422. function _encodeStateBitmap(OperationState operationState) internal pure returns (bytes32) {
  423. return bytes32(1 << uint8(operationState));
  424. }
  425. }