123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734 |
- // SPDX-License-Identifier: MIT
- // OpenZeppelin Contracts (last updated v5.0.0) (access/manager/AccessManager.sol)
- pragma solidity ^0.8.20;
- import {IAccessManager} from "./IAccessManager.sol";
- import {IAccessManaged} from "./IAccessManaged.sol";
- import {Address} from "../../utils/Address.sol";
- import {Context} from "../../utils/Context.sol";
- import {Multicall} from "../../utils/Multicall.sol";
- import {StorageSlot} from "../../utils/StorageSlot.sol";
- import {Math} from "../../utils/math/Math.sol";
- import {Time} from "../../utils/types/Time.sol";
- /**
- * @dev AccessManager is a central contract to store the permissions of a system.
- *
- * A smart contract under the control of an AccessManager instance is known as a target, and will inherit from the
- * {AccessManaged} contract, be connected to this contract as its manager and implement the {AccessManaged-restricted}
- * modifier on a set of functions selected to be permissioned. Note that any function without this setup won't be
- * effectively restricted.
- *
- * The restriction rules for such functions are defined in terms of "roles" identified by an `uint64` and scoped
- * by target (`address`) and function selectors (`bytes4`). These roles are stored in this contract and can be
- * configured by admins (`ADMIN_ROLE` members) after a delay (see {getTargetAdminDelay}).
- *
- * For each target contract, admins can configure the following without any delay:
- *
- * * The target's {AccessManaged-authority} via {updateAuthority}.
- * * Close or open a target via {setTargetClosed} keeping the permissions intact.
- * * The roles that are allowed (or disallowed) to call a given function (identified by its selector) through {setTargetFunctionRole}.
- *
- * By default every address is member of the `PUBLIC_ROLE` and every target function is restricted to the `ADMIN_ROLE` until configured otherwise.
- * Additionally, each role has the following configuration options restricted to this manager's admins:
- *
- * * A role's admin role via {setRoleAdmin} who can grant or revoke roles.
- * * A role's guardian role via {setRoleGuardian} who's allowed to cancel operations.
- * * A delay in which a role takes effect after being granted through {setGrantDelay}.
- * * A delay of any target's admin action via {setTargetAdminDelay}.
- * * A role label for discoverability purposes with {labelRole}.
- *
- * Any account can be added and removed into any number of these roles by using the {grantRole} and {revokeRole} functions
- * restricted to each role's admin (see {getRoleAdmin}).
- *
- * Since all the permissions of the managed system can be modified by the admins of this instance, it is expected that
- * they will be highly secured (e.g., a multisig or a well-configured DAO).
- *
- * NOTE: This contract implements a form of the {IAuthority} interface, but {canCall} has additional return data so it
- * doesn't inherit `IAuthority`. It is however compatible with the `IAuthority` interface since the first 32 bytes of
- * the return data are a boolean as expected by that interface.
- *
- * NOTE: Systems that implement other access control mechanisms (for example using {Ownable}) can be paired with an
- * {AccessManager} by transferring permissions (ownership in the case of {Ownable}) directly to the {AccessManager}.
- * Users will be able to interact with these contracts through the {execute} function, following the access rules
- * registered in the {AccessManager}. Keep in mind that in that context, the msg.sender seen by restricted functions
- * will be {AccessManager} itself.
- *
- * WARNING: When granting permissions over an {Ownable} or {AccessControl} contract to an {AccessManager}, be very
- * mindful of the danger associated with functions such as {Ownable-renounceOwnership} or
- * {AccessControl-renounceRole}.
- */
- contract AccessManager is Context, Multicall, IAccessManager {
- using StorageSlot for *;
- using Time for *;
- // Structure that stores the details for a target contract.
- struct TargetConfig {
- mapping(bytes4 selector => uint64 roleId) allowedRoles;
- Time.Delay adminDelay;
- bool closed;
- }
- // Structure that stores the details for a role/account pair. This structures fit into a single slot.
- struct Access {
- // Timepoint at which the user gets the permission.
- // If this is either 0 or in the future, then the role permission is not available.
- uint48 since;
- // Delay for execution. Only applies to restricted() / execute() calls.
- Time.Delay delay;
- }
- // Structure that stores the details of a role.
- struct Role {
- // Members of the role.
- mapping(address user => Access access) members;
- // Admin who can grant or revoke permissions.
- uint64 admin;
- // Guardian who can cancel operations targeting functions that need this role.
- uint64 guardian;
- // Delay in which the role takes effect after being granted.
- Time.Delay grantDelay;
- }
- // Structure that stores the details for a scheduled operation. This structure fits into a single slot.
- struct Schedule {
- // Moment at which the operation can be executed.
- uint48 timepoint;
- // Operation nonce to allow third-party contracts to identify the operation.
- uint32 nonce;
- }
- uint64 public constant ADMIN_ROLE = type(uint64).min; // 0
- uint64 public constant PUBLIC_ROLE = type(uint64).max; // 2**64-1
- mapping(address target => TargetConfig mode) private _targets;
- mapping(uint64 roleId => Role) private _roles;
- mapping(bytes32 operationId => Schedule) private _schedules;
- // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessManager.executionId")) - 1)) & ~bytes32(uint256(0xff))
- bytes32 private constant ACCESS_MANAGER_EXECUTION_ID_STORAGE =
- 0xcd345b53ed666c7ef33210216f8d27ceee269613372bda4998fd5fcd86a8b100;
- /**
- * @dev Check that the caller is authorized to perform the operation.
- * See {AccessManager} description for a detailed breakdown of the authorization logic.
- */
- modifier onlyAuthorized() {
- _checkAuthorized();
- _;
- }
- constructor(address initialAdmin) {
- if (initialAdmin == address(0)) {
- revert AccessManagerInvalidInitialAdmin(address(0));
- }
- // admin is active immediately and without any execution delay.
- _grantRole(ADMIN_ROLE, initialAdmin, 0, 0);
- }
- // =================================================== GETTERS ====================================================
- /// @inheritdoc IAccessManager
- function canCall(
- address caller,
- address target,
- bytes4 selector
- ) public view virtual returns (bool immediate, uint32 delay) {
- if (isTargetClosed(target)) {
- return (false, 0);
- } else if (caller == address(this)) {
- // Caller is AccessManager, this means the call was sent through {execute} and it already checked
- // permissions. We verify that the call "identifier", which is set during {execute}, is correct.
- return (_isExecuting(target, selector), 0);
- } else {
- uint64 roleId = getTargetFunctionRole(target, selector);
- (bool isMember, uint32 currentDelay) = hasRole(roleId, caller);
- return isMember ? (currentDelay == 0, currentDelay) : (false, 0);
- }
- }
- /// @inheritdoc IAccessManager
- function expiration() public view virtual returns (uint32) {
- return 1 weeks;
- }
- /// @inheritdoc IAccessManager
- function minSetback() public view virtual returns (uint32) {
- return 5 days;
- }
- /// @inheritdoc IAccessManager
- function isTargetClosed(address target) public view virtual returns (bool) {
- return _targets[target].closed;
- }
- /// @inheritdoc IAccessManager
- function getTargetFunctionRole(address target, bytes4 selector) public view virtual returns (uint64) {
- return _targets[target].allowedRoles[selector];
- }
- /// @inheritdoc IAccessManager
- function getTargetAdminDelay(address target) public view virtual returns (uint32) {
- return _targets[target].adminDelay.get();
- }
- /// @inheritdoc IAccessManager
- function getRoleAdmin(uint64 roleId) public view virtual returns (uint64) {
- return _roles[roleId].admin;
- }
- /// @inheritdoc IAccessManager
- function getRoleGuardian(uint64 roleId) public view virtual returns (uint64) {
- return _roles[roleId].guardian;
- }
- /// @inheritdoc IAccessManager
- function getRoleGrantDelay(uint64 roleId) public view virtual returns (uint32) {
- return _roles[roleId].grantDelay.get();
- }
- /// @inheritdoc IAccessManager
- function getAccess(
- uint64 roleId,
- address account
- ) public view virtual returns (uint48 since, uint32 currentDelay, uint32 pendingDelay, uint48 effect) {
- Access storage access = _roles[roleId].members[account];
- since = access.since;
- (currentDelay, pendingDelay, effect) = access.delay.getFull();
- return (since, currentDelay, pendingDelay, effect);
- }
- /// @inheritdoc IAccessManager
- function hasRole(
- uint64 roleId,
- address account
- ) public view virtual returns (bool isMember, uint32 executionDelay) {
- if (roleId == PUBLIC_ROLE) {
- return (true, 0);
- } else {
- (uint48 hasRoleSince, uint32 currentDelay, , ) = getAccess(roleId, account);
- return (hasRoleSince != 0 && hasRoleSince <= Time.timestamp(), currentDelay);
- }
- }
- // =============================================== ROLE MANAGEMENT ===============================================
- /// @inheritdoc IAccessManager
- function labelRole(uint64 roleId, string calldata label) public virtual onlyAuthorized {
- if (roleId == ADMIN_ROLE || roleId == PUBLIC_ROLE) {
- revert AccessManagerLockedRole(roleId);
- }
- emit RoleLabel(roleId, label);
- }
- /// @inheritdoc IAccessManager
- function grantRole(uint64 roleId, address account, uint32 executionDelay) public virtual onlyAuthorized {
- _grantRole(roleId, account, getRoleGrantDelay(roleId), executionDelay);
- }
- /// @inheritdoc IAccessManager
- function revokeRole(uint64 roleId, address account) public virtual onlyAuthorized {
- _revokeRole(roleId, account);
- }
- /// @inheritdoc IAccessManager
- function renounceRole(uint64 roleId, address callerConfirmation) public virtual {
- if (callerConfirmation != _msgSender()) {
- revert AccessManagerBadConfirmation();
- }
- _revokeRole(roleId, callerConfirmation);
- }
- /// @inheritdoc IAccessManager
- function setRoleAdmin(uint64 roleId, uint64 admin) public virtual onlyAuthorized {
- _setRoleAdmin(roleId, admin);
- }
- /// @inheritdoc IAccessManager
- function setRoleGuardian(uint64 roleId, uint64 guardian) public virtual onlyAuthorized {
- _setRoleGuardian(roleId, guardian);
- }
- /// @inheritdoc IAccessManager
- function setGrantDelay(uint64 roleId, uint32 newDelay) public virtual onlyAuthorized {
- _setGrantDelay(roleId, newDelay);
- }
- /**
- * @dev Internal version of {grantRole} without access control. Returns true if the role was newly granted.
- *
- * Emits a {RoleGranted} event.
- */
- function _grantRole(
- uint64 roleId,
- address account,
- uint32 grantDelay,
- uint32 executionDelay
- ) internal virtual returns (bool) {
- if (roleId == PUBLIC_ROLE) {
- revert AccessManagerLockedRole(roleId);
- }
- bool newMember = _roles[roleId].members[account].since == 0;
- uint48 since;
- if (newMember) {
- since = Time.timestamp() + grantDelay;
- _roles[roleId].members[account] = Access({since: since, delay: executionDelay.toDelay()});
- } else {
- // No setback here. Value can be reset by doing revoke + grant, effectively allowing the admin to perform
- // any change to the execution delay within the duration of the role admin delay.
- (_roles[roleId].members[account].delay, since) = _roles[roleId].members[account].delay.withUpdate(
- executionDelay,
- 0
- );
- }
- emit RoleGranted(roleId, account, executionDelay, since, newMember);
- return newMember;
- }
- /**
- * @dev Internal version of {revokeRole} without access control. This logic is also used by {renounceRole}.
- * Returns true if the role was previously granted.
- *
- * Emits a {RoleRevoked} event if the account had the role.
- */
- function _revokeRole(uint64 roleId, address account) internal virtual returns (bool) {
- if (roleId == PUBLIC_ROLE) {
- revert AccessManagerLockedRole(roleId);
- }
- if (_roles[roleId].members[account].since == 0) {
- return false;
- }
- delete _roles[roleId].members[account];
- emit RoleRevoked(roleId, account);
- return true;
- }
- /**
- * @dev Internal version of {setRoleAdmin} without access control.
- *
- * Emits a {RoleAdminChanged} event.
- *
- * NOTE: Setting the admin role as the `PUBLIC_ROLE` is allowed, but it will effectively allow
- * anyone to set grant or revoke such role.
- */
- function _setRoleAdmin(uint64 roleId, uint64 admin) internal virtual {
- if (roleId == ADMIN_ROLE || roleId == PUBLIC_ROLE) {
- revert AccessManagerLockedRole(roleId);
- }
- _roles[roleId].admin = admin;
- emit RoleAdminChanged(roleId, admin);
- }
- /**
- * @dev Internal version of {setRoleGuardian} without access control.
- *
- * Emits a {RoleGuardianChanged} event.
- *
- * NOTE: Setting the guardian role as the `PUBLIC_ROLE` is allowed, but it will effectively allow
- * anyone to cancel any scheduled operation for such role.
- */
- function _setRoleGuardian(uint64 roleId, uint64 guardian) internal virtual {
- if (roleId == ADMIN_ROLE || roleId == PUBLIC_ROLE) {
- revert AccessManagerLockedRole(roleId);
- }
- _roles[roleId].guardian = guardian;
- emit RoleGuardianChanged(roleId, guardian);
- }
- /**
- * @dev Internal version of {setGrantDelay} without access control.
- *
- * Emits a {RoleGrantDelayChanged} event.
- */
- function _setGrantDelay(uint64 roleId, uint32 newDelay) internal virtual {
- if (roleId == PUBLIC_ROLE) {
- revert AccessManagerLockedRole(roleId);
- }
- uint48 effect;
- (_roles[roleId].grantDelay, effect) = _roles[roleId].grantDelay.withUpdate(newDelay, minSetback());
- emit RoleGrantDelayChanged(roleId, newDelay, effect);
- }
- // ============================================= FUNCTION MANAGEMENT ==============================================
- /// @inheritdoc IAccessManager
- function setTargetFunctionRole(
- address target,
- bytes4[] calldata selectors,
- uint64 roleId
- ) public virtual onlyAuthorized {
- for (uint256 i = 0; i < selectors.length; ++i) {
- _setTargetFunctionRole(target, selectors[i], roleId);
- }
- }
- /**
- * @dev Internal version of {setTargetFunctionRole} without access control.
- *
- * Emits a {TargetFunctionRoleUpdated} event.
- */
- function _setTargetFunctionRole(address target, bytes4 selector, uint64 roleId) internal virtual {
- _targets[target].allowedRoles[selector] = roleId;
- emit TargetFunctionRoleUpdated(target, selector, roleId);
- }
- /// @inheritdoc IAccessManager
- function setTargetAdminDelay(address target, uint32 newDelay) public virtual onlyAuthorized {
- _setTargetAdminDelay(target, newDelay);
- }
- /**
- * @dev Internal version of {setTargetAdminDelay} without access control.
- *
- * Emits a {TargetAdminDelayUpdated} event.
- */
- function _setTargetAdminDelay(address target, uint32 newDelay) internal virtual {
- uint48 effect;
- (_targets[target].adminDelay, effect) = _targets[target].adminDelay.withUpdate(newDelay, minSetback());
- emit TargetAdminDelayUpdated(target, newDelay, effect);
- }
- // =============================================== MODE MANAGEMENT ================================================
- /// @inheritdoc IAccessManager
- function setTargetClosed(address target, bool closed) public virtual onlyAuthorized {
- _setTargetClosed(target, closed);
- }
- /**
- * @dev Set the closed flag for a contract. This is an internal setter with no access restrictions.
- *
- * Emits a {TargetClosed} event.
- */
- function _setTargetClosed(address target, bool closed) internal virtual {
- _targets[target].closed = closed;
- emit TargetClosed(target, closed);
- }
- // ============================================== DELAYED OPERATIONS ==============================================
- /// @inheritdoc IAccessManager
- function getSchedule(bytes32 id) public view virtual returns (uint48) {
- uint48 timepoint = _schedules[id].timepoint;
- return _isExpired(timepoint) ? 0 : timepoint;
- }
- /// @inheritdoc IAccessManager
- function getNonce(bytes32 id) public view virtual returns (uint32) {
- return _schedules[id].nonce;
- }
- /// @inheritdoc IAccessManager
- function schedule(
- address target,
- bytes calldata data,
- uint48 when
- ) public virtual returns (bytes32 operationId, uint32 nonce) {
- address caller = _msgSender();
- // Fetch restrictions that apply to the caller on the targeted function
- (, uint32 setback) = _canCallExtended(caller, target, data);
- uint48 minWhen = Time.timestamp() + setback;
- // If call with delay is not authorized, or if requested timing is too soon, revert
- if (setback == 0 || (when > 0 && when < minWhen)) {
- revert AccessManagerUnauthorizedCall(caller, target, _checkSelector(data));
- }
- // Reuse variable due to stack too deep
- when = uint48(Math.max(when, minWhen)); // cast is safe: both inputs are uint48
- // If caller is authorised, schedule operation
- operationId = hashOperation(caller, target, data);
- _checkNotScheduled(operationId);
- unchecked {
- // It's not feasible to overflow the nonce in less than 1000 years
- nonce = _schedules[operationId].nonce + 1;
- }
- _schedules[operationId].timepoint = when;
- _schedules[operationId].nonce = nonce;
- emit OperationScheduled(operationId, nonce, when, caller, target, data);
- // Using named return values because otherwise we get stack too deep
- }
- /**
- * @dev Reverts if the operation is currently scheduled and has not expired.
- *
- * NOTE: This function was introduced due to stack too deep errors in schedule.
- */
- function _checkNotScheduled(bytes32 operationId) private view {
- uint48 prevTimepoint = _schedules[operationId].timepoint;
- if (prevTimepoint != 0 && !_isExpired(prevTimepoint)) {
- revert AccessManagerAlreadyScheduled(operationId);
- }
- }
- /// @inheritdoc IAccessManager
- // Reentrancy is not an issue because permissions are checked on msg.sender. Additionally,
- // _consumeScheduledOp guarantees a scheduled operation is only executed once.
- // slither-disable-next-line reentrancy-no-eth
- function execute(address target, bytes calldata data) public payable virtual returns (uint32) {
- address caller = _msgSender();
- // Fetch restrictions that apply to the caller on the targeted function
- (bool immediate, uint32 setback) = _canCallExtended(caller, target, data);
- // If call is not authorized, revert
- if (!immediate && setback == 0) {
- revert AccessManagerUnauthorizedCall(caller, target, _checkSelector(data));
- }
- bytes32 operationId = hashOperation(caller, target, data);
- uint32 nonce;
- // If caller is authorised, check operation was scheduled early enough
- // Consume an available schedule even if there is no currently enforced delay
- if (setback != 0 || getSchedule(operationId) != 0) {
- nonce = _consumeScheduledOp(operationId);
- }
- // Mark the target and selector as authorised
- bytes32 executionIdBefore = ACCESS_MANAGER_EXECUTION_ID_STORAGE.asBytes32().tload();
- ACCESS_MANAGER_EXECUTION_ID_STORAGE.asBytes32().tstore(_hashExecutionId(target, _checkSelector(data)));
- // Perform call
- Address.functionCallWithValue(target, data, msg.value);
- // Reset execute identifier
- ACCESS_MANAGER_EXECUTION_ID_STORAGE.asBytes32().tstore(executionIdBefore);
- return nonce;
- }
- /// @inheritdoc IAccessManager
- function cancel(address caller, address target, bytes calldata data) public virtual returns (uint32) {
- address msgsender = _msgSender();
- bytes4 selector = _checkSelector(data);
- bytes32 operationId = hashOperation(caller, target, data);
- if (_schedules[operationId].timepoint == 0) {
- revert AccessManagerNotScheduled(operationId);
- } else if (caller != msgsender) {
- // calls can only be canceled by the account that scheduled them, a global admin, or by a guardian of the required role.
- (bool isAdmin, ) = hasRole(ADMIN_ROLE, msgsender);
- (bool isGuardian, ) = hasRole(getRoleGuardian(getTargetFunctionRole(target, selector)), msgsender);
- if (!isAdmin && !isGuardian) {
- revert AccessManagerUnauthorizedCancel(msgsender, caller, target, selector);
- }
- }
- delete _schedules[operationId].timepoint; // reset the timepoint, keep the nonce
- uint32 nonce = _schedules[operationId].nonce;
- emit OperationCanceled(operationId, nonce);
- return nonce;
- }
- /// @inheritdoc IAccessManager
- function consumeScheduledOp(address caller, bytes calldata data) public virtual {
- address target = _msgSender();
- if (IAccessManaged(target).isConsumingScheduledOp() != IAccessManaged.isConsumingScheduledOp.selector) {
- revert AccessManagerUnauthorizedConsume(target);
- }
- _consumeScheduledOp(hashOperation(caller, target, data));
- }
- /**
- * @dev Internal variant of {consumeScheduledOp} that operates on bytes32 operationId.
- *
- * Returns the nonce of the scheduled operation that is consumed.
- */
- function _consumeScheduledOp(bytes32 operationId) internal virtual returns (uint32) {
- uint48 timepoint = _schedules[operationId].timepoint;
- uint32 nonce = _schedules[operationId].nonce;
- if (timepoint == 0) {
- revert AccessManagerNotScheduled(operationId);
- } else if (timepoint > Time.timestamp()) {
- revert AccessManagerNotReady(operationId);
- } else if (_isExpired(timepoint)) {
- revert AccessManagerExpired(operationId);
- }
- delete _schedules[operationId].timepoint; // reset the timepoint, keep the nonce
- emit OperationExecuted(operationId, nonce);
- return nonce;
- }
- /// @inheritdoc IAccessManager
- function hashOperation(address caller, address target, bytes calldata data) public view virtual returns (bytes32) {
- return keccak256(abi.encode(caller, target, data));
- }
- // ==================================================== OTHERS ====================================================
- /// @inheritdoc IAccessManager
- function updateAuthority(address target, address newAuthority) public virtual onlyAuthorized {
- IAccessManaged(target).setAuthority(newAuthority);
- }
- // ================================================= ADMIN LOGIC ==================================================
- /**
- * @dev Check if the current call is authorized according to admin and roles logic.
- *
- * WARNING: Carefully review the considerations of {AccessManaged-restricted} since they apply to this modifier.
- */
- function _checkAuthorized() private {
- address caller = _msgSender();
- (bool immediate, uint32 delay) = _canCallSelf(caller, _msgData());
- if (!immediate) {
- if (delay == 0) {
- (, uint64 requiredRole, ) = _getAdminRestrictions(_msgData());
- revert AccessManagerUnauthorizedAccount(caller, requiredRole);
- } else {
- _consumeScheduledOp(hashOperation(caller, address(this), _msgData()));
- }
- }
- }
- /**
- * @dev Get the admin restrictions of a given function call based on the function and arguments involved.
- *
- * Returns:
- * - bool restricted: does this data match a restricted operation
- * - uint64: which role is this operation restricted to
- * - uint32: minimum delay to enforce for that operation (max between operation's delay and admin's execution delay)
- */
- function _getAdminRestrictions(
- bytes calldata data
- ) private view returns (bool adminRestricted, uint64 roleAdminId, uint32 executionDelay) {
- if (data.length < 4) {
- return (false, 0, 0);
- }
- bytes4 selector = _checkSelector(data);
- // Restricted to ADMIN with no delay beside any execution delay the caller may have
- if (
- selector == this.labelRole.selector ||
- selector == this.setRoleAdmin.selector ||
- selector == this.setRoleGuardian.selector ||
- selector == this.setGrantDelay.selector ||
- selector == this.setTargetAdminDelay.selector
- ) {
- return (true, ADMIN_ROLE, 0);
- }
- // Restricted to ADMIN with the admin delay corresponding to the target
- if (
- selector == this.updateAuthority.selector ||
- selector == this.setTargetClosed.selector ||
- selector == this.setTargetFunctionRole.selector
- ) {
- // First argument is a target.
- address target = abi.decode(data[0x04:0x24], (address));
- uint32 delay = getTargetAdminDelay(target);
- return (true, ADMIN_ROLE, delay);
- }
- // Restricted to that role's admin with no delay beside any execution delay the caller may have.
- if (selector == this.grantRole.selector || selector == this.revokeRole.selector) {
- // First argument is a roleId.
- uint64 roleId = abi.decode(data[0x04:0x24], (uint64));
- return (true, getRoleAdmin(roleId), 0);
- }
- return (false, getTargetFunctionRole(address(this), selector), 0);
- }
- // =================================================== HELPERS ====================================================
- /**
- * @dev An extended version of {canCall} for internal usage that checks {_canCallSelf}
- * when the target is this contract.
- *
- * Returns:
- * - bool immediate: whether the operation can be executed immediately (with no delay)
- * - uint32 delay: the execution delay
- */
- function _canCallExtended(
- address caller,
- address target,
- bytes calldata data
- ) private view returns (bool immediate, uint32 delay) {
- if (target == address(this)) {
- return _canCallSelf(caller, data);
- } else {
- return data.length < 4 ? (false, 0) : canCall(caller, target, _checkSelector(data));
- }
- }
- /**
- * @dev A version of {canCall} that checks for restrictions in this contract.
- */
- function _canCallSelf(address caller, bytes calldata data) private view returns (bool immediate, uint32 delay) {
- if (data.length < 4) {
- return (false, 0);
- }
- if (caller == address(this)) {
- // Caller is AccessManager, this means the call was sent through {execute} and it already checked
- // permissions. We verify that the call "identifier", which is set during {execute}, is correct.
- return (_isExecuting(address(this), _checkSelector(data)), 0);
- }
- (bool adminRestricted, uint64 roleId, uint32 operationDelay) = _getAdminRestrictions(data);
- // isTragetClosed apply to non-admin-restricted function
- if (!adminRestricted && isTargetClosed(address(this))) {
- return (false, 0);
- }
- (bool inRole, uint32 executionDelay) = hasRole(roleId, caller);
- if (!inRole) {
- return (false, 0);
- }
- // downcast is safe because both options are uint32
- delay = uint32(Math.max(operationDelay, executionDelay));
- return (delay == 0, delay);
- }
- /**
- * @dev Returns true if a call with `target` and `selector` is being executed via {executed}.
- */
- function _isExecuting(address target, bytes4 selector) private view returns (bool) {
- return ACCESS_MANAGER_EXECUTION_ID_STORAGE.asBytes32().tload() == _hashExecutionId(target, selector);
- }
- /**
- * @dev Returns true if a schedule timepoint is past its expiration deadline.
- */
- function _isExpired(uint48 timepoint) private view returns (bool) {
- return timepoint + expiration() <= Time.timestamp();
- }
- /**
- * @dev Extracts the selector from calldata. Panics if data is not at least 4 bytes
- */
- function _checkSelector(bytes calldata data) private pure returns (bytes4) {
- return bytes4(data[0:4]);
- }
- /**
- * @dev Hashing function for execute protection
- */
- function _hashExecutionId(address target, bytes4 selector) private pure returns (bytes32) {
- return keccak256(abi.encode(target, selector));
- }
- }
|