TimelockController.sol 16 KB

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