TimelockController.sol 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.4.0-rc.0) (governance/TimelockController.sol)
  3. pragma solidity ^0.8.20;
  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 {Address} from "../utils/Address.sol";
  8. import {IERC165} from "../utils/introspection/ERC165.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 id => 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 in seconds 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 virtual {}
  135. /// @inheritdoc IERC165
  136. function supportsInterface(
  137. bytes4 interfaceId
  138. ) public view virtual override(AccessControl, ERC1155Holder) returns (bool) {
  139. return super.supportsInterface(interfaceId);
  140. }
  141. /**
  142. * @dev Returns whether an id corresponds to a registered operation. This
  143. * includes both Waiting, Ready, and Done operations.
  144. */
  145. function isOperation(bytes32 id) public view returns (bool) {
  146. return getOperationState(id) != OperationState.Unset;
  147. }
  148. /**
  149. * @dev Returns whether an operation is pending or not. Note that a "pending" operation may also be "ready".
  150. */
  151. function isOperationPending(bytes32 id) public view returns (bool) {
  152. OperationState state = getOperationState(id);
  153. return state == OperationState.Waiting || state == OperationState.Ready;
  154. }
  155. /**
  156. * @dev Returns whether an operation is ready for execution. Note that a "ready" operation is also "pending".
  157. */
  158. function isOperationReady(bytes32 id) public view returns (bool) {
  159. return getOperationState(id) == OperationState.Ready;
  160. }
  161. /**
  162. * @dev Returns whether an operation is done or not.
  163. */
  164. function isOperationDone(bytes32 id) public view returns (bool) {
  165. return getOperationState(id) == OperationState.Done;
  166. }
  167. /**
  168. * @dev Returns the timestamp at which an operation becomes ready (0 for
  169. * unset operations, 1 for done operations).
  170. */
  171. function getTimestamp(bytes32 id) public view virtual returns (uint256) {
  172. return _timestamps[id];
  173. }
  174. /**
  175. * @dev Returns operation state.
  176. */
  177. function getOperationState(bytes32 id) public view virtual returns (OperationState) {
  178. uint256 timestamp = getTimestamp(id);
  179. if (timestamp == 0) {
  180. return OperationState.Unset;
  181. } else if (timestamp == _DONE_TIMESTAMP) {
  182. return OperationState.Done;
  183. } else if (timestamp > block.timestamp) {
  184. return OperationState.Waiting;
  185. } else {
  186. return OperationState.Ready;
  187. }
  188. }
  189. /**
  190. * @dev Returns the minimum delay in seconds for an operation to become valid.
  191. *
  192. * This value can be changed by executing an operation that calls `updateDelay`.
  193. */
  194. function getMinDelay() public view virtual returns (uint256) {
  195. return _minDelay;
  196. }
  197. /**
  198. * @dev Returns the identifier of an operation containing a single
  199. * transaction.
  200. */
  201. function hashOperation(
  202. address target,
  203. uint256 value,
  204. bytes calldata data,
  205. bytes32 predecessor,
  206. bytes32 salt
  207. ) public pure virtual returns (bytes32) {
  208. return keccak256(abi.encode(target, value, data, predecessor, salt));
  209. }
  210. /**
  211. * @dev Returns the identifier of an operation containing a batch of
  212. * transactions.
  213. */
  214. function hashOperationBatch(
  215. address[] calldata targets,
  216. uint256[] calldata values,
  217. bytes[] calldata payloads,
  218. bytes32 predecessor,
  219. bytes32 salt
  220. ) public pure virtual returns (bytes32) {
  221. return keccak256(abi.encode(targets, values, payloads, predecessor, salt));
  222. }
  223. /**
  224. * @dev Schedule an operation containing a single transaction.
  225. *
  226. * Emits {CallSalt} if salt is nonzero, and {CallScheduled}.
  227. *
  228. * Requirements:
  229. *
  230. * - the caller must have the 'proposer' role.
  231. */
  232. function schedule(
  233. address target,
  234. uint256 value,
  235. bytes calldata data,
  236. bytes32 predecessor,
  237. bytes32 salt,
  238. uint256 delay
  239. ) public virtual onlyRole(PROPOSER_ROLE) {
  240. bytes32 id = hashOperation(target, value, data, predecessor, salt);
  241. _schedule(id, delay);
  242. emit CallScheduled(id, 0, target, value, data, predecessor, delay);
  243. if (salt != bytes32(0)) {
  244. emit CallSalt(id, salt);
  245. }
  246. }
  247. /**
  248. * @dev Schedule an operation containing a batch of transactions.
  249. *
  250. * Emits {CallSalt} if salt is nonzero, and one {CallScheduled} event per transaction in the batch.
  251. *
  252. * Requirements:
  253. *
  254. * - the caller must have the 'proposer' role.
  255. */
  256. function scheduleBatch(
  257. address[] calldata targets,
  258. uint256[] calldata values,
  259. bytes[] calldata payloads,
  260. bytes32 predecessor,
  261. bytes32 salt,
  262. uint256 delay
  263. ) public virtual onlyRole(PROPOSER_ROLE) {
  264. if (targets.length != values.length || targets.length != payloads.length) {
  265. revert TimelockInvalidOperationLength(targets.length, payloads.length, values.length);
  266. }
  267. bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt);
  268. _schedule(id, delay);
  269. for (uint256 i = 0; i < targets.length; ++i) {
  270. emit CallScheduled(id, i, targets[i], values[i], payloads[i], predecessor, delay);
  271. }
  272. if (salt != bytes32(0)) {
  273. emit CallSalt(id, salt);
  274. }
  275. }
  276. /**
  277. * @dev Schedule an operation that is to become valid after a given delay.
  278. */
  279. function _schedule(bytes32 id, uint256 delay) private {
  280. if (isOperation(id)) {
  281. revert TimelockUnexpectedOperationState(id, _encodeStateBitmap(OperationState.Unset));
  282. }
  283. uint256 minDelay = getMinDelay();
  284. if (delay < minDelay) {
  285. revert TimelockInsufficientDelay(delay, minDelay);
  286. }
  287. _timestamps[id] = block.timestamp + delay;
  288. }
  289. /**
  290. * @dev Cancel an operation.
  291. *
  292. * Requirements:
  293. *
  294. * - the caller must have the 'canceller' role.
  295. */
  296. function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) {
  297. if (!isOperationPending(id)) {
  298. revert TimelockUnexpectedOperationState(
  299. id,
  300. _encodeStateBitmap(OperationState.Waiting) | _encodeStateBitmap(OperationState.Ready)
  301. );
  302. }
  303. delete _timestamps[id];
  304. emit Cancelled(id);
  305. }
  306. /**
  307. * @dev Execute an (ready) operation containing a single transaction.
  308. *
  309. * Emits a {CallExecuted} event.
  310. *
  311. * Requirements:
  312. *
  313. * - the caller must have the 'executor' role.
  314. */
  315. // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,
  316. // thus any modifications to the operation during reentrancy should be caught.
  317. // slither-disable-next-line reentrancy-eth
  318. function execute(
  319. address target,
  320. uint256 value,
  321. bytes calldata payload,
  322. bytes32 predecessor,
  323. bytes32 salt
  324. ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
  325. bytes32 id = hashOperation(target, value, payload, predecessor, salt);
  326. _beforeCall(id, predecessor);
  327. _execute(target, value, payload);
  328. emit CallExecuted(id, 0, target, value, payload);
  329. _afterCall(id);
  330. }
  331. /**
  332. * @dev Execute an (ready) operation containing a batch of transactions.
  333. *
  334. * Emits one {CallExecuted} event per transaction in the batch.
  335. *
  336. * Requirements:
  337. *
  338. * - the caller must have the 'executor' role.
  339. */
  340. // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,
  341. // thus any modifications to the operation during reentrancy should be caught.
  342. // slither-disable-next-line reentrancy-eth
  343. function executeBatch(
  344. address[] calldata targets,
  345. uint256[] calldata values,
  346. bytes[] calldata payloads,
  347. bytes32 predecessor,
  348. bytes32 salt
  349. ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
  350. if (targets.length != values.length || targets.length != payloads.length) {
  351. revert TimelockInvalidOperationLength(targets.length, payloads.length, values.length);
  352. }
  353. bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt);
  354. _beforeCall(id, predecessor);
  355. for (uint256 i = 0; i < targets.length; ++i) {
  356. address target = targets[i];
  357. uint256 value = values[i];
  358. bytes calldata payload = payloads[i];
  359. _execute(target, value, payload);
  360. emit CallExecuted(id, i, target, value, payload);
  361. }
  362. _afterCall(id);
  363. }
  364. /**
  365. * @dev Execute an operation's call.
  366. */
  367. function _execute(address target, uint256 value, bytes calldata data) internal virtual {
  368. (bool success, bytes memory returndata) = target.call{value: value}(data);
  369. Address.verifyCallResult(success, returndata);
  370. }
  371. /**
  372. * @dev Checks before execution of an operation's calls.
  373. */
  374. function _beforeCall(bytes32 id, bytes32 predecessor) private view {
  375. if (!isOperationReady(id)) {
  376. revert TimelockUnexpectedOperationState(id, _encodeStateBitmap(OperationState.Ready));
  377. }
  378. if (predecessor != bytes32(0) && !isOperationDone(predecessor)) {
  379. revert TimelockUnexecutedPredecessor(predecessor);
  380. }
  381. }
  382. /**
  383. * @dev Checks after execution of an operation's calls.
  384. */
  385. function _afterCall(bytes32 id) private {
  386. if (!isOperationReady(id)) {
  387. revert TimelockUnexpectedOperationState(id, _encodeStateBitmap(OperationState.Ready));
  388. }
  389. _timestamps[id] = _DONE_TIMESTAMP;
  390. }
  391. /**
  392. * @dev Changes the minimum timelock duration for future operations.
  393. *
  394. * Emits a {MinDelayChange} event.
  395. *
  396. * Requirements:
  397. *
  398. * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing
  399. * an operation where the timelock is the target and the data is the ABI-encoded call to this function.
  400. */
  401. function updateDelay(uint256 newDelay) external virtual {
  402. address sender = _msgSender();
  403. if (sender != address(this)) {
  404. revert TimelockUnauthorizedCaller(sender);
  405. }
  406. emit MinDelayChange(_minDelay, newDelay);
  407. _minDelay = newDelay;
  408. }
  409. /**
  410. * @dev Encodes a `OperationState` into a `bytes32` representation where each bit enabled corresponds to
  411. * the underlying position in the `OperationState` enum. For example:
  412. *
  413. * 0x000...1000
  414. * ^^^^^^----- ...
  415. * ^---- Done
  416. * ^--- Ready
  417. * ^-- Waiting
  418. * ^- Unset
  419. */
  420. function _encodeStateBitmap(OperationState operationState) internal pure returns (bytes32) {
  421. return bytes32(1 << uint8(operationState));
  422. }
  423. }