// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/manager/AccessManaged.sol)
pragma solidity ^0.8.20;
import {IAuthority} from "./IAuthority.sol";
import {AuthorityUtils} from "./AuthorityUtils.sol";
import {IAccessManager} from "./IAccessManager.sol";
import {IAccessManaged} from "./IAccessManaged.sol";
import {Context} from "../../utils/Context.sol";
/**
* @dev This contract module makes available a {restricted} modifier. Functions decorated with this modifier will be
* permissioned according to an "authority": a contract like {AccessManager} that follows the {IAuthority} interface,
* implementing a policy that allows certain callers to access certain functions.
*
* IMPORTANT: The `restricted` modifier should never be used on `internal` functions, judiciously used in `public`
* functions, and ideally only used in `external` functions. See {restricted}.
*/
abstract contract AccessManaged is Context, IAccessManaged {
address private _authority;
bool private _consumingSchedule;
/**
* @dev Initializes the contract connected to an initial authority.
*/
constructor(address initialAuthority) {
_setAuthority(initialAuthority);
}
/**
* @dev Restricts access to a function as defined by the connected Authority for this contract and the
* caller and selector of the function that entered the contract.
*
* [IMPORTANT]
* ====
* In general, this modifier should only be used on `external` functions. It is okay to use it on `public`
* functions that are used as external entry points and are not called internally. Unless you know what you're
* doing, it should never be used on `internal` functions. Failure to follow these rules can have critical security
* implications! This is because the permissions are determined by the function that entered the contract, i.e. the
* function at the bottom of the call stack, and not the function where the modifier is visible in the source code.
* ====
*
* [WARNING]
* ====
* Avoid adding this modifier to the https://docs.soliditylang.org/en/v0.8.20/contracts.html#receive-ether-function[`receive()`]
* function or the https://docs.soliditylang.org/en/v0.8.20/contracts.html#fallback-function[`fallback()`]. These
* functions are the only execution paths where a function selector cannot be unambiguosly determined from the calldata
* since the selector defaults to `0x00000000` in the `receive()` function and similarly in the `fallback()` function
* if no calldata is provided. (See {_checkCanCall}).
*
* The `receive()` function will always panic whereas the `fallback()` may panic depending on the calldata length.
* ====
*/
modifier restricted() {
_checkCanCall(_msgSender(), _msgData());
_;
}
/// @inheritdoc IAccessManaged
function authority() public view virtual returns (address) {
return _authority;
}
/// @inheritdoc IAccessManaged
function setAuthority(address newAuthority) public virtual {
address caller = _msgSender();
if (caller != authority()) {
revert AccessManagedUnauthorized(caller);
}
if (newAuthority.code.length == 0) {
revert AccessManagedInvalidAuthority(newAuthority);
}
_setAuthority(newAuthority);
}
/// @inheritdoc IAccessManaged
function isConsumingScheduledOp() public view returns (bytes4) {
return _consumingSchedule ? this.isConsumingScheduledOp.selector : bytes4(0);
}
/**
* @dev Transfers control to a new authority. Internal function with no access restriction. Allows bypassing the
* permissions set by the current authority.
*/
function _setAuthority(address newAuthority) internal virtual {
_authority = newAuthority;
emit AuthorityUpdated(newAuthority);
}
/**
* @dev Reverts if the caller is not allowed to call the function identified by a selector. Panics if the calldata
* is less than 4 bytes long.
*/
function _checkCanCall(address caller, bytes calldata data) internal virtual {
(bool immediate, uint32 delay) = AuthorityUtils.canCallWithDelay(
authority(),
caller,
address(this),
bytes4(data[0:4])
);
if (!immediate) {
if (delay > 0) {
_consumingSchedule = true;
IAccessManager(authority()).consumeScheduledOp(caller, data);
_consumingSchedule = false;
} else {
revert AccessManagedUnauthorized(caller);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/manager/AccessManaged.sol)
pragma solidity ^0.8.20;
import {AuthorityUtils} from "@openzeppelin/contracts/access/manager/AuthorityUtils.sol";
import {IAccessManager} from "@openzeppelin/contracts/access/manager/IAccessManager.sol";
import {IAccessManaged} from "@openzeppelin/contracts/access/manager/IAccessManaged.sol";
import {ContextUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/**
* @dev This contract module makes available a {restricted} modifier. Functions decorated with this modifier will be
* permissioned according to an "authority": a contract like {AccessManager} that follows the {IAuthority} interface,
* implementing a policy that allows certain callers to access certain functions.
*
* IMPORTANT: The `restricted` modifier should never be used on `internal` functions, judiciously used in `public`
* functions, and ideally only used in `external` functions. See {restricted}.
*/
abstract contract AccessManagedUpgradeable is Initializable, ContextUpgradeable, IAccessManaged {
/// @custom:storage-location erc7201:openzeppelin.storage.AccessManaged
struct AccessManagedStorage {
address _authority;
bool _consumingSchedule;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessManaged")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ACCESS_MANAGED_STORAGE_LOCATION =
0xf3177357ab46d8af007ab3fdb9af81da189e1068fefdc0073dca88a2cab40a00;
function _getAccessManagedStorage() internal pure returns (AccessManagedStorage storage $) {
assembly {
$.slot := ACCESS_MANAGED_STORAGE_LOCATION
}
}
/**
* @dev Initializes the contract connected to an initial authority.
*/
function __AccessManaged_init(address initialAuthority) internal onlyInitializing {
// solhint-disable-previous-line func-name-mixedcase
__AccessManaged_init_unchained(initialAuthority);
}
function __AccessManaged_init_unchained(address initialAuthority) internal onlyInitializing {
// solhint-disable-previous-line func-name-mixedcase
_setAuthority(initialAuthority);
}
/**
* @dev Restricts access to a function as defined by the connected Authority for this contract and the
* caller and selector of the function that entered the contract.
*
* [IMPORTANT]
* ====
* In general, this modifier should only be used on `external` functions. It is okay to use it on `public`
* functions that are used as external entry points and are not called internally. Unless you know what you're
* doing, it should never be used on `internal` functions. Failure to follow these rules can have critical security
* implications! This is because the permissions are determined by the function that entered the contract, i.e. the
* function at the bottom of the call stack, and not the function where the modifier is visible in the source code.
* ====
*
* [WARNING]
* ====
* Avoid adding this modifier to the https://docs.soliditylang.org/en/v0.8.20/contracts.html#receive-ether-function[`receive()`]
* function or the https://docs.soliditylang.org/en/v0.8.20/contracts.html#fallback-function[`fallback()`]. These
* functions are the only execution paths where a function selector cannot be unambiguosly determined from the calldata
* since the selector defaults to `0x00000000` in the `receive()` function and similarly in the `fallback()` function
* if no calldata is provided. (See {_checkCanCall}).
*
* The `receive()` function will always panic whereas the `fallback()` may panic depending on the calldata length.
* ====
*/
modifier restricted() {
_checkCanCall(_msgSender(), _msgData());
_;
}
/// @inheritdoc IAccessManaged
function authority() public view virtual returns (address) {
AccessManagedStorage storage $ = _getAccessManagedStorage();
return $._authority;
}
/// @inheritdoc IAccessManaged
function setAuthority(address newAuthority) public virtual {
address caller = _msgSender();
if (caller != authority()) {
revert AccessManagedUnauthorized(caller);
}
if (newAuthority.code.length == 0) {
revert AccessManagedInvalidAuthority(newAuthority);
}
_setAuthority(newAuthority);
}
/// @inheritdoc IAccessManaged
function isConsumingScheduledOp() public view virtual returns (bytes4) {
AccessManagedStorage storage $ = _getAccessManagedStorage();
return $._consumingSchedule ? this.isConsumingScheduledOp.selector : bytes4(0);
}
/**
* @dev Transfers control to a new authority. Internal function with no access restriction. Allows bypassing the
* permissions set by the current authority.
*/
function _setAuthority(address newAuthority) internal virtual {
AccessManagedStorage storage $ = _getAccessManagedStorage();
$._authority = newAuthority;
emit AuthorityUpdated(newAuthority);
}
/**
* @dev Reverts if the caller is not allowed to call the function identified by a selector. Panics if the calldata
* is less than 4 bytes long.
*/
function _checkCanCall(address caller, bytes calldata data) internal virtual {
AccessManagedStorage storage $ = _getAccessManagedStorage();
(bool immediate, uint32 delay) = AuthorityUtils.canCallWithDelay(
authority(),
caller,
address(this),
bytes4(data[0:4])
);
if (!immediate) {
if (delay > 0) {
$._consumingSchedule = true;
IAccessManager(authority()).consumeScheduledOp(caller, data);
$._consumingSchedule = false;
} else {
revert AccessManagedUnauthorized(caller);
}
}
}
}
// 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 {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 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;
// Used to identify operations that are currently being executed via {execute}.
// This should be transient storage when supported by the EVM.
bytes32 private _executionId;
/**
* @dev Check that the caller is authorized to perform the operation, following the restrictions encoded in
* {_getAdminRestrictions}.
*/
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 {
if (target == address(this)) {
revert AccessManagerLockedAccount(target);
}
_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
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 caller is not authorised, 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 = _executionId;
_executionId = _hashExecutionId(target, _checkSelector(data));
// Perform call
Address.functionCallWithValue(target, data, msg.value);
// Reset execute identifier
_executionId = 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 logic.
*/
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 restricted, 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, 0, 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 admin 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 enabled, uint64 roleId, uint32 operationDelay) = _getAdminRestrictions(data);
if (!enabled) {
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 _executionId == _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));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {PlasmaVaultStorageLib} from "./PlasmaVaultStorageLib.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
/// @notice MarketToCheck struct for the markets limits protection
struct MarketToCheck {
/// @param marketId The market id
uint256 marketId;
/// @param balanceInMarket The balance in the market, represented in 18 decimals
uint256 balanceInMarket;
}
/// @notice DataToCheck struct for the markets limits protection
struct DataToCheck {
/// @param totalBalanceInVault The total balance in the Plasma Vault, represented in 18 decimals
uint256 totalBalanceInVault;
/// @param marketsToCheck The array of MarketToCheck structs
MarketToCheck[] marketsToCheck;
}
/// @notice Market limit struct
struct MarketLimit {
/// @dev MarketId: the same value as used in fuse
uint256 marketId;
/// @dev Limit in percentage of the total balance in the vault, use 1e18 as 100%
uint256 limitInPercentage;
}
/// @title Asset Distribution Protection Library responsible for the markets limits protection in the Plasma Vault
library AssetDistributionProtectionLib {
uint256 private constant ONE_HUNDRED_PERCENT = 1e18;
event MarketsLimitsActivated();
event MarketsLimitsDeactivated();
event MarketLimitUpdated(uint256 marketId, uint256 newLimit);
error MarketLimitExceeded(uint256 marketId, uint256 balanceInMarket, uint256 limit);
error MarketLimitSetupInPercentageIsTooHigh(uint256 limit);
error WrongMarketId(uint256 marketId);
/// @notice Activates the markets limits protection, by default it is deactivated. After activation the limits
/// is setup for each market separately.
function activateMarketsLimits() internal {
PlasmaVaultStorageLib.getMarketsLimits().limitInPercentage[0] = 1;
emit MarketsLimitsActivated();
}
/// @notice Deactivates the markets limits protection.
function deactivateMarketsLimits() internal {
PlasmaVaultStorageLib.getMarketsLimits().limitInPercentage[0] = 0;
emit MarketsLimitsDeactivated();
}
/// @notice Sets up the limits for each market separately.
/// @param marketsLimits_ The array of MarketLimit structs
function setupMarketsLimits(MarketLimit[] calldata marketsLimits_) internal {
uint256 len = marketsLimits_.length;
for (uint256 i; i < len; ++i) {
if (marketsLimits_[i].marketId == 0) {
revert WrongMarketId(marketsLimits_[i].marketId);
}
if (marketsLimits_[i].limitInPercentage > ONE_HUNDRED_PERCENT) {
revert MarketLimitSetupInPercentageIsTooHigh(marketsLimits_[i].limitInPercentage);
}
PlasmaVaultStorageLib.getMarketsLimits().limitInPercentage[marketsLimits_[i].marketId] = marketsLimits_[i]
.limitInPercentage;
emit MarketLimitUpdated(marketsLimits_[i].marketId, marketsLimits_[i].limitInPercentage);
}
}
/// @notice Checks if the limits are exceeded for the markets.
/// @param data_ The DataToCheck struct
/// @dev revert if the limit is exceeded
function checkLimits(DataToCheck memory data_) internal view {
if (!isMarketsLimitsActivated()) {
return;
}
uint256 len = data_.marketsToCheck.length;
for (uint256 i; i < len; ++i) {
uint256 limit = Math.mulDiv(
PlasmaVaultStorageLib.getMarketsLimits().limitInPercentage[data_.marketsToCheck[i].marketId],
data_.totalBalanceInVault,
ONE_HUNDRED_PERCENT
);
if (limit < data_.marketsToCheck[i].balanceInMarket) {
revert MarketLimitExceeded(
data_.marketsToCheck[i].marketId,
data_.marketsToCheck[i].balanceInMarket,
limit
);
}
}
}
/// @notice Checks if the markets limits protection is activated.
/// @return bool true if the markets limits protection is activated
function isMarketsLimitsActivated() internal view returns (bool) {
return PlasmaVaultStorageLib.getMarketsLimits().limitInPercentage[0] != 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/manager/AuthorityUtils.sol)
pragma solidity ^0.8.20;
import {IAuthority} from "./IAuthority.sol";
library AuthorityUtils {
/**
* @dev Since `AccessManager` implements an extended IAuthority interface, invoking `canCall` with backwards compatibility
* for the preexisting `IAuthority` interface requires special care to avoid reverting on insufficient return data.
* This helper function takes care of invoking `canCall` in a backwards compatible way without reverting.
*/
function canCallWithDelay(
address authority,
address caller,
address target,
bytes4 selector
) internal view returns (bool immediate, uint32 delay) {
(bool success, bytes memory data) = authority.staticcall(
abi.encodeCall(IAuthority.canCall, (caller, target, selector))
);
if (success) {
if (data.length >= 0x40) {
(immediate, delay) = abi.decode(data, (bool, uint32));
} else if (data.length >= 0x20) {
immediate = abi.decode(data, (bool));
}
}
return (immediate, delay);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {FuseAction} from "../interfaces/IPlasmaVault.sol";
import {PlasmaVaultStorageLib} from "./PlasmaVaultStorageLib.sol";
import {PlasmaVault} from "../vaults/PlasmaVault.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
struct CallbackData {
address asset;
address addressToApprove;
uint256 amountToApprove;
bytes actionData;
}
/// @title Callback Handler Library responsible for handling callbacks in the Plasma Vault
library CallbackHandlerLib {
using Address for address;
using SafeERC20 for ERC20;
event CallbackHandlerUpdated(address indexed handler, address indexed sender, bytes4 indexed sig);
error HandlerNotFound();
/// @notice Handles the callback from the contract
function handleCallback() internal {
address handler = PlasmaVaultStorageLib.getCallbackHandler().callbackHandler[
/// @dev msg.sender - is the address of a contract which execute callback, msg.sig - is the signature of the function
keccak256(abi.encodePacked(msg.sender, msg.sig))
];
if (handler == address(0)) {
revert HandlerNotFound();
}
bytes memory data = handler.functionCall(msg.data);
if (data.length == 0) {
return;
}
CallbackData memory calls = abi.decode(data, (CallbackData));
PlasmaVault(address(this)).executeInternal(abi.decode(calls.actionData, (FuseAction[])));
ERC20(calls.asset).forceApprove(calls.addressToApprove, calls.amountToApprove);
}
/// @notice Updates the callback handler for the contract
/// @param handler_ The address of the handler
/// @param sender_ The address of the sender
/// @param sig_ The signature of the function which will be called from msg.sender
function updateCallbackHandler(address handler_, address sender_, bytes4 sig_) internal {
PlasmaVaultStorageLib.getCallbackHandler().callbackHandler[
/// @dev msg.sender - is the address of a contract which execute callback, msg.sig - is the signature of the function
keccak256(abi.encodePacked(sender_, sig_))
] = handler_;
emit CallbackHandlerUpdated(handler_, sender_, sig_);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
* ```
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*/
abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {
/// @custom:storage-location erc7201:openzeppelin.storage.ERC20
struct ERC20Storage {
mapping(address account => uint256) _balances;
mapping(address account => mapping(address spender => uint256)) _allowances;
uint256 _totalSupply;
string _name;
string _symbol;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;
function _getERC20Storage() private pure returns (ERC20Storage storage $) {
assembly {
$.slot := ERC20StorageLocation
}
}
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
ERC20Storage storage $ = _getERC20Storage();
$._name = name_;
$._symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
ERC20Storage storage $ = _getERC20Storage();
return $._name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
ERC20Storage storage $ = _getERC20Storage();
return $._symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
ERC20Storage storage $ = _getERC20Storage();
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
$._totalSupply += value;
} else {
uint256 fromBalance = $._balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
$._balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
$._totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
$._balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
* ```
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
ERC20Storage storage $ = _getERC20Storage();
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
$._allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC4626.sol)
pragma solidity ^0.8.20;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ERC20Upgradeable} from "../ERC20Upgradeable.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {Initializable} from "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the ERC4626 "Tokenized Vault Standard" as defined in
* https://eips.ethereum.org/EIPS/eip-4626[EIP-4626].
*
* This extension allows the minting and burning of "shares" (represented using the ERC20 inheritance) in exchange for
* underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends
* the ERC20 standard. Any additional extensions included along it would affect the "shares" token represented by this
* contract and not the "assets" token which is an independent contract.
*
* [CAUTION]
* ====
* In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning
* with a "donation" to the vault that inflates the price of a share. This is variously known as a donation or inflation
* attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial
* deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may
* similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by
* verifying the amount received is as expected, using a wrapper that performs these checks such as
* https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].
*
* Since v4.9, this implementation uses virtual assets and shares to mitigate that risk. The `_decimalsOffset()`
* corresponds to an offset in the decimal representation between the underlying asset's decimals and the vault
* decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which itself
* determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default offset
* (0) makes it non-profitable, as a result of the value being captured by the virtual shares (out of the attacker's
* donation) matching the attacker's expected gains. With a larger offset, the attack becomes orders of magnitude more
* expensive than it is profitable. More details about the underlying math can be found
* xref:erc4626.adoc#inflation-attack[here].
*
* The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued
* to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets
* will cause the first user to exit to experience reduced losses in detriment to the last users that will experience
* bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the
* `_convertToShares` and `_convertToAssets` functions.
*
* To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].
* ====
*/
abstract contract ERC4626Upgradeable is Initializable, ERC20Upgradeable, IERC4626 {
using Math for uint256;
/// @custom:storage-location erc7201:openzeppelin.storage.ERC4626
struct ERC4626Storage {
IERC20 _asset;
uint8 _underlyingDecimals;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC4626")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ERC4626StorageLocation = 0x0773e532dfede91f04b12a73d3d2acd361424f41f76b4fb79f090161e36b4e00;
function _getERC4626Storage() private pure returns (ERC4626Storage storage $) {
assembly {
$.slot := ERC4626StorageLocation
}
}
/**
* @dev Attempted to deposit more assets than the max amount for `receiver`.
*/
error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);
/**
* @dev Attempted to mint more shares than the max amount for `receiver`.
*/
error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);
/**
* @dev Attempted to withdraw more assets than the max amount for `receiver`.
*/
error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);
/**
* @dev Attempted to redeem more shares than the max amount for `receiver`.
*/
error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);
/**
* @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).
*/
function __ERC4626_init(IERC20 asset_) internal onlyInitializing {
__ERC4626_init_unchained(asset_);
}
function __ERC4626_init_unchained(IERC20 asset_) internal onlyInitializing {
ERC4626Storage storage $ = _getERC4626Storage();
(bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);
$._underlyingDecimals = success ? assetDecimals : 18;
$._asset = asset_;
}
/**
* @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.
*/
function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool, uint8) {
(bool success, bytes memory encodedDecimals) = address(asset_).staticcall(
abi.encodeCall(IERC20Metadata.decimals, ())
);
if (success && encodedDecimals.length >= 32) {
uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));
if (returnedDecimals <= type(uint8).max) {
return (true, uint8(returnedDecimals));
}
}
return (false, 0);
}
/**
* @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This
* "original" value is cached during construction of the vault contract. If this read operation fails (e.g., the
* asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.
*
* See {IERC20Metadata-decimals}.
*/
function decimals() public view virtual override(IERC20Metadata, ERC20Upgradeable) returns (uint8) {
ERC4626Storage storage $ = _getERC4626Storage();
return $._underlyingDecimals + _decimalsOffset();
}
/** @dev See {IERC4626-asset}. */
function asset() public view virtual returns (address) {
ERC4626Storage storage $ = _getERC4626Storage();
return address($._asset);
}
/** @dev See {IERC4626-totalAssets}. */
function totalAssets() public view virtual returns (uint256) {
ERC4626Storage storage $ = _getERC4626Storage();
return $._asset.balanceOf(address(this));
}
/** @dev See {IERC4626-convertToShares}. */
function convertToShares(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Floor);
}
/** @dev See {IERC4626-convertToAssets}. */
function convertToAssets(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Floor);
}
/** @dev See {IERC4626-maxDeposit}. */
function maxDeposit(address) public view virtual returns (uint256) {
return type(uint256).max;
}
/** @dev See {IERC4626-maxMint}. */
function maxMint(address) public view virtual returns (uint256) {
return type(uint256).max;
}
/** @dev See {IERC4626-maxWithdraw}. */
function maxWithdraw(address owner) public view virtual returns (uint256) {
return _convertToAssets(balanceOf(owner), Math.Rounding.Floor);
}
/** @dev See {IERC4626-maxRedeem}. */
function maxRedeem(address owner) public view virtual returns (uint256) {
return balanceOf(owner);
}
/** @dev See {IERC4626-previewDeposit}. */
function previewDeposit(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Floor);
}
/** @dev See {IERC4626-previewMint}. */
function previewMint(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Ceil);
}
/** @dev See {IERC4626-previewWithdraw}. */
function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Ceil);
}
/** @dev See {IERC4626-previewRedeem}. */
function previewRedeem(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Floor);
}
/** @dev See {IERC4626-deposit}. */
function deposit(uint256 assets, address receiver) public virtual returns (uint256) {
uint256 maxAssets = maxDeposit(receiver);
if (assets > maxAssets) {
revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);
}
uint256 shares = previewDeposit(assets);
_deposit(_msgSender(), receiver, assets, shares);
return shares;
}
/** @dev See {IERC4626-mint}.
*
* As opposed to {deposit}, minting is allowed even if the vault is in a state where the price of a share is zero.
* In this case, the shares will be minted without requiring any assets to be deposited.
*/
function mint(uint256 shares, address receiver) public virtual returns (uint256) {
uint256 maxShares = maxMint(receiver);
if (shares > maxShares) {
revert ERC4626ExceededMaxMint(receiver, shares, maxShares);
}
uint256 assets = previewMint(shares);
_deposit(_msgSender(), receiver, assets, shares);
return assets;
}
/** @dev See {IERC4626-withdraw}. */
function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {
uint256 maxAssets = maxWithdraw(owner);
if (assets > maxAssets) {
revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);
}
uint256 shares = previewWithdraw(assets);
_withdraw(_msgSender(), receiver, owner, assets, shares);
return shares;
}
/** @dev See {IERC4626-redeem}. */
function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {
uint256 maxShares = maxRedeem(owner);
if (shares > maxShares) {
revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
}
uint256 assets = previewRedeem(shares);
_withdraw(_msgSender(), receiver, owner, assets, shares);
return assets;
}
/**
* @dev Internal conversion function (from assets to shares) with support for rounding direction.
*/
function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {
return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);
}
/**
* @dev Internal conversion function (from shares to assets) with support for rounding direction.
*/
function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {
return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);
}
/**
* @dev Deposit/mint common workflow.
*/
function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {
ERC4626Storage storage $ = _getERC4626Storage();
// If _asset is ERC777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the
// `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
// calls the vault, which is assumed not malicious.
//
// Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
// assets are transferred and before the shares are minted, which is a valid state.
// slither-disable-next-line reentrancy-no-eth
SafeERC20.safeTransferFrom($._asset, caller, address(this), assets);
_mint(receiver, shares);
emit Deposit(caller, receiver, assets, shares);
}
/**
* @dev Withdraw/redeem common workflow.
*/
function _withdraw(
address caller,
address receiver,
address owner,
uint256 assets,
uint256 shares
) internal virtual {
ERC4626Storage storage $ = _getERC4626Storage();
if (caller != owner) {
_spendAllowance(owner, caller, shares);
}
// If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
// `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
// calls the vault, which is assumed not malicious.
//
// Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
// shares are burned and after the assets are transferred, which is a valid state.
_burn(owner, shares);
SafeERC20.safeTransfer($._asset, receiver, assets);
emit Withdraw(caller, receiver, owner, assets, shares);
}
function _decimalsOffset() internal view virtual returns (uint8) {
return 0;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
/// @title Errors in Ipor Fusion
library Errors {
/// @notice Error when wrong address is used
error WrongAddress();
/// @notice Error when wrong value is used
error WrongValue();
/// @notice Error when wrong decimals are used
error WrongDecimals();
/// @notice Error when wrong array length is used
error WrongArrayLength();
/// @notice Error when wrong caller is used
error WrongCaller(address caller);
/// @notice Error when wrong quote currency is used
error UnsupportedQuoteCurrencyFromOracle();
/// @notice Error when unsupported price oracle middleware is used
error UnsupportedPriceOracleMiddleware();
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title FeeAccount
/// @notice Contract responsible for managing fee approvals for the Ipor protocol
contract FeeAccount {
using SafeERC20 for IERC20;
/// @notice Error thrown when a non-fee manager tries to approve
error OnlyFeeManagerCanApprove();
/// @notice Address of the Fee Manager contract
address public immutable FEE_MANAGER;
constructor(address feeManager_) {
FEE_MANAGER = feeManager_;
}
/// @notice Max approves the fee manager to spend tokens on behalf of the contract
/// @param plasmaVault Address of the plasma vault token
function approveMaxForFeeManager(address plasmaVault) external {
if (msg.sender != FEE_MANAGER) {
revert OnlyFeeManagerCanApprove();
}
IERC20(plasmaVault).forceApprove(FEE_MANAGER, type(uint256).max);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {AccessManaged} from "@openzeppelin/contracts/access/manager/AccessManaged.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {FeeAccount} from "./FeeAccount.sol";
import {PlasmaVaultGovernance} from "../../vaults/PlasmaVaultGovernance.sol";
import {Errors} from "../../libraries/errors/Errors.sol";
/// @notice Struct containing initialization data for the fee manager
/// @param iporDaoManagementFee Management fee percentage for the DAO (in percentage with 2 decimals, example 10000 is 100%, 100 is 1%)
/// @param iporDaoPerformanceFee Performance fee percentage for the DAO (in percentage with 2 decimals, example 10000 is 100%, 100 is 1%)
/// @param atomistManagementFee Management fee percentage for the atomist (in percentage with 2 decimals, example 10000 is 100%, 100 is 1%)
/// @param atomistPerformanceFee Performance fee percentage for the atomist (in percentage with 2 decimals, example 10000 is 100%, 100 is 1%)
/// @param initialAuthority Address of the initial authority
/// @param plasmaVault Address of the plasma vault
/// @param feeRecipientAddress Address of the fee recipient
/// @param iporDaoFeeRecipientAddress Address of the DAO fee recipient
struct FeeManagerInitData {
uint256 iporDaoManagementFee;
uint256 iporDaoPerformanceFee;
uint256 atomistManagementFee;
uint256 atomistPerformanceFee;
address initialAuthority;
address plasmaVault;
address feeRecipientAddress;
address iporDaoFeeRecipientAddress;
}
/// @title FeeManager
/// @notice Manages the fees for the IporFusion protocol, including management and performance fees.
/// @dev Inherits from AccessManaged for access control.
contract FeeManager is AccessManaged {
event HarvestManagementFee(address receiver, uint256 amount);
event HarvestPerformanceFee(address receiver, uint256 amount);
event PerformanceFeeUpdated(uint256 newPerformanceFee);
event ManagementFeeUpdated(uint256 newManagementFee);
error NotInitialized();
error AlreadyInitialized();
error InvalidFeeRecipientAddress();
address public immutable PERFORMANCE_FEE_ACCOUNT;
address public immutable MANAGEMENT_FEE_ACCOUNT;
/// @notice IPOR_DAO_MANAGEMENT_FEE is in percentage with 2 decimals, example 10000 is 100%, 100 is 1%
uint256 public immutable IPOR_DAO_MANAGEMENT_FEE;
/// @notice IPOR_DAO_PERFORMANCE_FEE is in percentage with 2 decimals, example 10000 is 100%, 100 is 1%
uint256 public immutable IPOR_DAO_PERFORMANCE_FEE;
address public immutable PLASMA_VAULT;
address public feeRecipientAddress;
address public iporDaoFeeRecipientAddress;
/// @notice plasmaVaultPerformanceFee is in percentage with 2 decimals, example 10000 is 100%, 100 is 1%
uint256 public plasmaVaultPerformanceFee;
/// @notice plasmaVaultManagementFee is in percentage with 2 decimals, example 10000 is 100%, 100 is 1%
uint256 public plasmaVaultManagementFee;
/// @notice The flag indicating whether the contract is initialized, if it is, the value is greater than 0
uint256 public initialized;
constructor(FeeManagerInitData memory initData_) AccessManaged(initData_.initialAuthority) {
PERFORMANCE_FEE_ACCOUNT = address(new FeeAccount(address(this)));
MANAGEMENT_FEE_ACCOUNT = address(new FeeAccount(address(this)));
IPOR_DAO_MANAGEMENT_FEE = initData_.iporDaoManagementFee;
IPOR_DAO_PERFORMANCE_FEE = initData_.iporDaoPerformanceFee;
plasmaVaultPerformanceFee = initData_.atomistPerformanceFee + IPOR_DAO_PERFORMANCE_FEE;
plasmaVaultManagementFee = initData_.atomistManagementFee + IPOR_DAO_MANAGEMENT_FEE;
feeRecipientAddress = initData_.feeRecipientAddress;
iporDaoFeeRecipientAddress = initData_.iporDaoFeeRecipientAddress;
PLASMA_VAULT = initData_.plasmaVault;
}
function initialize() external {
if (initialized != 0) {
revert AlreadyInitialized();
}
initialized = 1;
FeeAccount(PERFORMANCE_FEE_ACCOUNT).approveMaxForFeeManager(PLASMA_VAULT);
FeeAccount(MANAGEMENT_FEE_ACCOUNT).approveMaxForFeeManager(PLASMA_VAULT);
}
/// @notice Harvests the management fee and transfers it to the respective recipient addresses.
/// @dev This function can only be called if the contract is initialized.
/// It checks if the fee recipient addresses are valid and then calculates the amount to be transferred to the DAO
/// and the remaining amount to the fee recipient. The function emits events for each transfer.
/// @custom:modifier onlyInitialized Ensures the contract is initialized before executing the function.
function harvestManagementFee() public onlyInitialized {
if (feeRecipientAddress == address(0) || iporDaoFeeRecipientAddress == address(0)) {
revert InvalidFeeRecipientAddress();
}
if (plasmaVaultManagementFee == 0) {
return;
}
uint256 balance = IERC4626(PLASMA_VAULT).balanceOf(MANAGEMENT_FEE_ACCOUNT);
if (balance == 0) {
return;
}
uint256 decimals = IERC4626(PLASMA_VAULT).decimals();
uint256 numberOfDecimals = 10 ** (decimals);
uint256 percentageToTransferToDao = (IPOR_DAO_MANAGEMENT_FEE * numberOfDecimals) / plasmaVaultManagementFee;
uint256 transferAmountToDao = Math.mulDiv(balance, percentageToTransferToDao, numberOfDecimals);
IERC4626(PLASMA_VAULT).transferFrom(MANAGEMENT_FEE_ACCOUNT, iporDaoFeeRecipientAddress, transferAmountToDao);
emit HarvestManagementFee(iporDaoFeeRecipientAddress, transferAmountToDao);
if (balance <= transferAmountToDao) {
return;
}
uint256 transferAmount = balance - transferAmountToDao;
if (transferAmount == 0) {
return;
}
IERC4626(PLASMA_VAULT).transferFrom(MANAGEMENT_FEE_ACCOUNT, feeRecipientAddress, transferAmount);
emit HarvestManagementFee(feeRecipientAddress, balance - transferAmountToDao);
}
/// @notice Harvests the performance fee and transfers it to the respective recipient addresses.
/// @dev This function can only be called if the contract is initialized.
/// It checks if the fee recipient addresses are valid and then calculates the amount to be transferred to the DAO
/// and the remaining amount to the fee recipient. The function emits events for each transfer.
/// @custom:modifier onlyInitialized Ensures the contract is initialized before executing the function.
function harvestPerformanceFee() public onlyInitialized {
if (feeRecipientAddress == address(0) || iporDaoFeeRecipientAddress == address(0)) {
revert InvalidFeeRecipientAddress();
}
if (plasmaVaultPerformanceFee == 0) {
return;
}
uint256 balance = IERC4626(PLASMA_VAULT).balanceOf(PERFORMANCE_FEE_ACCOUNT);
if (balance == 0) {
return;
}
uint256 decimals = IERC4626(PLASMA_VAULT).decimals();
uint256 numberOfDecimals = 10 ** (decimals);
uint256 percentToTransferToDao = (IPOR_DAO_PERFORMANCE_FEE * numberOfDecimals) / plasmaVaultPerformanceFee;
uint256 transferAmountToDao = Math.mulDiv(balance, percentToTransferToDao, numberOfDecimals);
IERC4626(PLASMA_VAULT).transferFrom(PERFORMANCE_FEE_ACCOUNT, iporDaoFeeRecipientAddress, transferAmountToDao);
emit HarvestPerformanceFee(iporDaoFeeRecipientAddress, transferAmountToDao);
if (balance <= transferAmountToDao) {
return;
}
uint256 transferAmount = balance - transferAmountToDao;
if (transferAmount == 0) {
return;
}
IERC4626(PLASMA_VAULT).transferFrom(
PERFORMANCE_FEE_ACCOUNT,
feeRecipientAddress,
balance - transferAmountToDao
);
emit HarvestPerformanceFee(feeRecipientAddress, balance - transferAmountToDao);
}
/**
* @notice Updates the performance fee and reconfigures it in the PlasmaVaultGovernance contract.
* @param performanceFee_ The new performance fee to be added to the DAO performance fee.
*/
function updatePerformanceFee(uint256 performanceFee_) external restricted {
harvestPerformanceFee();
uint256 newPerformanceFee = performanceFee_ + IPOR_DAO_PERFORMANCE_FEE;
PlasmaVaultGovernance(PLASMA_VAULT).configurePerformanceFee(PERFORMANCE_FEE_ACCOUNT, newPerformanceFee);
plasmaVaultPerformanceFee = newPerformanceFee;
emit PerformanceFeeUpdated(newPerformanceFee);
}
/// @notice Updates the management fee and reconfigures it in the PlasmaVaultGovernance contract.
/// @param managementFee_ The new management fee to be added to the DAO management fee.
function updateManagementFee(uint256 managementFee_) external restricted {
harvestManagementFee();
uint256 newManagementFee = managementFee_ + IPOR_DAO_MANAGEMENT_FEE;
PlasmaVaultGovernance(PLASMA_VAULT).configureManagementFee(MANAGEMENT_FEE_ACCOUNT, newManagementFee);
plasmaVaultManagementFee = newManagementFee;
emit ManagementFeeUpdated(newManagementFee);
}
/**
* @notice Sets the address of the fee recipient.
* @dev This function can only be called by an authorized account (ATOMIST_ROLE).
* @param feeRecipientAddress_ The address to set as the fee recipient.
* @custom:error WrongAddress Thrown if the provided address is the zero address.
*/
function setFeeRecipientAddress(address feeRecipientAddress_) external restricted {
if (feeRecipientAddress_ == address(0)) {
revert Errors.WrongAddress();
}
feeRecipientAddress = feeRecipientAddress_;
}
/**
* @notice Sets the address of the DAO fee recipient.
* @dev This function can only be called by an authorized account (TECH_IPOR_DAO_ROLE).
* @param iporDaoFeeRecipientAddress_ The address to set as the DAO fee recipient.
* @custom:error InvalidAddress Thrown if the provided address is the zero address.
*/
function setIporDaoFeeRecipientAddress(address iporDaoFeeRecipientAddress_) external restricted {
if (iporDaoFeeRecipientAddress_ == address(0)) {
revert Errors.WrongAddress();
}
iporDaoFeeRecipientAddress = iporDaoFeeRecipientAddress_;
}
modifier onlyInitialized() {
if (initialized == 0) {
revert NotInitialized();
}
_;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {FeeManager, FeeManagerInitData} from "./FeeManager.sol";
/// @notice Struct containing data related to the fee manager
/// @param feeManager Address of the fee manager
/// @param plasmaVault Address of the plasma vault
/// @param performanceFeeAccount Address of the performance fee account
/// @param managementFeeAccount Address of the management fee account
/// @param managementFee Management fee percentage (in percentage with 2 decimals, example 10000 is 100%, 100 is 1%)
/// @param performanceFee Performance fee percentage (in percentage with 2 decimals, example 10000 is 100%, 100 is 1%)
struct FeeManagerData {
address feeManager;
address plasmaVault;
address performanceFeeAccount;
address managementFeeAccount;
uint256 managementFee;
uint256 performanceFee;
}
/// @title FeeManagerFactory
/// @notice Factory contract for deploying FeeManager instances
contract FeeManagerFactory {
/// @notice Deploys a new FeeManager contract
/// @param initData Initialization data for the fee manager
/// @return FeeManagerData containing addresses and fee information of the deployed fee manager
function deployFeeManager(FeeManagerInitData memory initData) external returns (FeeManagerData memory) {
FeeManager feeManager = new FeeManager(initData);
return
FeeManagerData({
feeManager: address(feeManager),
plasmaVault: feeManager.PLASMA_VAULT(),
performanceFeeAccount: feeManager.PERFORMANCE_FEE_ACCOUNT(),
managementFeeAccount: feeManager.MANAGEMENT_FEE_ACCOUNT(),
managementFee: feeManager.plasmaVaultManagementFee(),
performanceFee: feeManager.plasmaVaultPerformanceFee()
});
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
/// @title Fuses storage library responsible for managing storage fuses in the Plasma Vault
library FuseStorageLib {
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.CfgFuses")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant CFG_FUSES = 0x48932b860eb451ad240d4fe2b46522e5a0ac079d201fe50d4e0be078c75b5400;
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.CfgFusesArray")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant CFG_FUSES_ARRAY = 0xad43e358bd6e59a5a0c80f6bf25fa771408af4d80f621cdc680c8dfbf607ab00;
/// @notice This memory is designed to use with Uniswap V3 fuses
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.UniswapV3TokenIds")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant UNISWAP_V3_TOKEN_IDS = 0x3651659bd419f7c37743f3e14a337c9f9d1cfc4d650d91508f44d1acbe960f00;
/// @notice This memory is designed to use with Ramses V2 fuses
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.RamsesV2TokenIds")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant RAMSES_V2_TOKEN_IDS = 0x1a3831a406f27d4d5d820158b29ce95a1e8e840bf416921917aa388e2461b700;
/// @custom:storage-location erc7201:io.ipor.CfgFuses
struct Fuses {
/// @dev fuse address => If index = 0 - is not granted, otherwise - granted
mapping(address fuse => uint256 index) value;
}
/// @custom:storage-location erc7201:io.ipor.CfgFusesArray
struct FusesArray {
/// @dev value is a fuse address
address[] value;
}
/// @custom:storage-location erc7201:io.ipor.UniswapV3TokenIds
struct UniswapV3TokenIds {
uint256[] tokenIds;
mapping(uint256 tokenId => uint256 index) indexes;
}
/// @custom:storage-location erc7201:io.ipor.RamsesV2TokenIds
struct RamsesV2TokenIds {
uint256[] tokenIds;
mapping(uint256 tokenId => uint256 index) indexes;
}
/// @notice Gets the fuses storage pointer
function getFuses() internal pure returns (Fuses storage fuses) {
assembly {
fuses.slot := CFG_FUSES
}
}
/// @notice Gets the fuses array storage pointer
function getFusesArray() internal pure returns (FusesArray storage fusesArray) {
assembly {
fusesArray.slot := CFG_FUSES_ARRAY
}
}
/// @notice Gets the UniswapV3TokenIds storage pointer
function getUniswapV3TokenIds() internal pure returns (UniswapV3TokenIds storage uniswapV3TokenIds) {
assembly {
uniswapV3TokenIds.slot := UNISWAP_V3_TOKEN_IDS
}
}
/// @notice Gets the UniswapV3TokenIds storage pointer
function getRamsesV2TokenIds() internal pure returns (RamsesV2TokenIds storage ramsesV2TokenIds) {
assembly {
ramsesV2TokenIds.slot := RAMSES_V2_TOKEN_IDS
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {FuseStorageLib} from "./FuseStorageLib.sol";
import {PlasmaVaultStorageLib} from "./PlasmaVaultStorageLib.sol";
/// @title Fuses Library responsible for managing fuses in the Plasma Vault
library FusesLib {
using Address for address;
event FuseAdded(address fuse);
event FuseRemoved(address fuse);
event BalanceFuseAdded(uint256 marketId, address fuse);
event BalanceFuseRemoved(uint256 marketId, address fuse);
error FuseAlreadyExists();
error FuseDoesNotExist();
error FuseUnsupported(address fuse);
error BalanceFuseAlreadyExists(uint256 marketId, address fuse);
error BalanceFuseDoesNotExist(uint256 marketId, address fuse);
error BalanceFuseNotReadyToRemove(uint256 marketId, address fuse, uint256 currentBalance);
/// @notice Checks if the fuse is supported
/// @param fuse_ The address of the fuse
/// @return true if the fuse is supported
function isFuseSupported(address fuse_) internal view returns (bool) {
return FuseStorageLib.getFuses().value[fuse_] != 0;
}
/// @notice Checks if the balance fuse is supported
/// @param marketId_ The market id
/// @param fuse_ The address of the fuse
/// @return true if the balance fuse is supported
function isBalanceFuseSupported(uint256 marketId_, address fuse_) internal view returns (bool) {
return PlasmaVaultStorageLib.getBalanceFuses().value[marketId_] == fuse_;
}
/// @notice Gets the balance fuse for the market
/// @param marketId_ The market id
/// @return The address of the balance fuse
function getBalanceFuse(uint256 marketId_) internal view returns (address) {
return PlasmaVaultStorageLib.getBalanceFuses().value[marketId_];
}
/// @notice Gets the array of stored and supported Fuses
/// @return The array of Fuses
function getFusesArray() internal view returns (address[] memory) {
return FuseStorageLib.getFusesArray().value;
}
/// @notice Gets the index of the fuse in the fuses array
/// @param fuse_ The address of the fuse
/// @return The index of the fuse in the fuses array stored in Plasma Vault
function getFuseArrayIndex(address fuse_) internal view returns (uint256) {
return FuseStorageLib.getFuses().value[fuse_];
}
/// @notice Adds a fuse to supported fuses
/// @param fuse_ The address of the fuse
function addFuse(address fuse_) internal {
FuseStorageLib.Fuses storage fuses = FuseStorageLib.getFuses();
uint256 keyIndexValue = fuses.value[fuse_];
if (keyIndexValue != 0) {
revert FuseAlreadyExists();
}
uint256 newLastFuseId = FuseStorageLib.getFusesArray().value.length + 1;
/// @dev for balance fuses, value is a index + 1 in the fusesArray
fuses.value[fuse_] = newLastFuseId;
FuseStorageLib.getFusesArray().value.push(fuse_);
emit FuseAdded(fuse_);
}
/// @notice Removes a fuse from supported fuses
/// @param fuse_ The address of the fuse
function removeFuse(address fuse_) internal {
FuseStorageLib.Fuses storage fuses = FuseStorageLib.getFuses();
uint256 indexToRemove = fuses.value[fuse_];
if (indexToRemove == 0) {
revert FuseDoesNotExist();
}
address lastKeyInArray = FuseStorageLib.getFusesArray().value[FuseStorageLib.getFusesArray().value.length - 1];
fuses.value[lastKeyInArray] = indexToRemove;
fuses.value[fuse_] = 0;
/// @dev balanceFuses mapping contains values as index + 1
FuseStorageLib.getFusesArray().value[indexToRemove - 1] = lastKeyInArray;
FuseStorageLib.getFusesArray().value.pop();
emit FuseRemoved(fuse_);
}
/// @notice Adds a balance fuse to the market
/// @param marketId_ The market id
/// @param fuse_ The address of the fuse
/// @dev Every market can have one dedicated balance fuse
function addBalanceFuse(uint256 marketId_, address fuse_) internal {
address currentFuse = PlasmaVaultStorageLib.getBalanceFuses().value[marketId_];
if (currentFuse == fuse_) {
revert BalanceFuseAlreadyExists(marketId_, fuse_);
}
PlasmaVaultStorageLib.getBalanceFuses().value[marketId_] = fuse_;
emit BalanceFuseAdded(marketId_, fuse_);
}
/// @notice Removes a balance fuse from the market
/// @param marketId_ The market id
/// @param fuse_ The address of the fuse
/// @dev Every market can have one dedicated balance fuse
function removeBalanceFuse(uint256 marketId_, address fuse_) internal {
address currentBalanceFuse = PlasmaVaultStorageLib.getBalanceFuses().value[marketId_];
if (currentBalanceFuse != fuse_) {
revert BalanceFuseDoesNotExist(marketId_, fuse_);
}
uint256 wadBalanceAmountInUSD = abi.decode(
currentBalanceFuse.functionDelegateCall(abi.encodeWithSignature("balanceOf()")),
(uint256)
);
if (wadBalanceAmountInUSD > calculateAllowedDustInBalanceFuse()) {
revert BalanceFuseNotReadyToRemove(marketId_, fuse_, wadBalanceAmountInUSD);
}
PlasmaVaultStorageLib.getBalanceFuses().value[marketId_] = address(0);
emit BalanceFuseRemoved(marketId_, fuse_);
}
function calculateAllowedDustInBalanceFuse() private view returns (uint256) {
return 10 ** (PlasmaVaultStorageLib.getERC4626Storage().underlyingDecimals / 2);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/manager/IAccessManaged.sol)
pragma solidity ^0.8.20;
interface IAccessManaged {
/**
* @dev Authority that manages this contract was updated.
*/
event AuthorityUpdated(address authority);
error AccessManagedUnauthorized(address caller);
error AccessManagedRequiredDelay(address caller, uint32 delay);
error AccessManagedInvalidAuthority(address authority);
/**
* @dev Returns the current authority.
*/
function authority() external view returns (address);
/**
* @dev Transfers control to a new authority. The caller must be the current authority.
*/
function setAuthority(address) external;
/**
* @dev Returns true only in the context of a delayed restricted call, at the moment that the scheduled operation is
* being consumed. Prevents denial of service for delayed restricted calls in the case that the contract performs
* attacker controlled calls.
*/
function isConsumingScheduledOp() external view returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/manager/IAccessManager.sol)
pragma solidity ^0.8.20;
import {IAccessManaged} from "./IAccessManaged.sol";
import {Time} from "../../utils/types/Time.sol";
interface IAccessManager {
/**
* @dev A delayed operation was scheduled.
*/
event OperationScheduled(
bytes32 indexed operationId,
uint32 indexed nonce,
uint48 schedule,
address caller,
address target,
bytes data
);
/**
* @dev A scheduled operation was executed.
*/
event OperationExecuted(bytes32 indexed operationId, uint32 indexed nonce);
/**
* @dev A scheduled operation was canceled.
*/
event OperationCanceled(bytes32 indexed operationId, uint32 indexed nonce);
/**
* @dev Informational labelling for a roleId.
*/
event RoleLabel(uint64 indexed roleId, string label);
/**
* @dev Emitted when `account` is granted `roleId`.
*
* NOTE: The meaning of the `since` argument depends on the `newMember` argument.
* If the role is granted to a new member, the `since` argument indicates when the account becomes a member of the role,
* otherwise it indicates the execution delay for this account and roleId is updated.
*/
event RoleGranted(uint64 indexed roleId, address indexed account, uint32 delay, uint48 since, bool newMember);
/**
* @dev Emitted when `account` membership or `roleId` is revoked. Unlike granting, revoking is instantaneous.
*/
event RoleRevoked(uint64 indexed roleId, address indexed account);
/**
* @dev Role acting as admin over a given `roleId` is updated.
*/
event RoleAdminChanged(uint64 indexed roleId, uint64 indexed admin);
/**
* @dev Role acting as guardian over a given `roleId` is updated.
*/
event RoleGuardianChanged(uint64 indexed roleId, uint64 indexed guardian);
/**
* @dev Grant delay for a given `roleId` will be updated to `delay` when `since` is reached.
*/
event RoleGrantDelayChanged(uint64 indexed roleId, uint32 delay, uint48 since);
/**
* @dev Target mode is updated (true = closed, false = open).
*/
event TargetClosed(address indexed target, bool closed);
/**
* @dev Role required to invoke `selector` on `target` is updated to `roleId`.
*/
event TargetFunctionRoleUpdated(address indexed target, bytes4 selector, uint64 indexed roleId);
/**
* @dev Admin delay for a given `target` will be updated to `delay` when `since` is reached.
*/
event TargetAdminDelayUpdated(address indexed target, uint32 delay, uint48 since);
error AccessManagerAlreadyScheduled(bytes32 operationId);
error AccessManagerNotScheduled(bytes32 operationId);
error AccessManagerNotReady(bytes32 operationId);
error AccessManagerExpired(bytes32 operationId);
error AccessManagerLockedAccount(address account);
error AccessManagerLockedRole(uint64 roleId);
error AccessManagerBadConfirmation();
error AccessManagerUnauthorizedAccount(address msgsender, uint64 roleId);
error AccessManagerUnauthorizedCall(address caller, address target, bytes4 selector);
error AccessManagerUnauthorizedConsume(address target);
error AccessManagerUnauthorizedCancel(address msgsender, address caller, address target, bytes4 selector);
error AccessManagerInvalidInitialAdmin(address initialAdmin);
/**
* @dev Check if an address (`caller`) is authorised to call a given function on a given contract directly (with
* no restriction). Additionally, it returns the delay needed to perform the call indirectly through the {schedule}
* & {execute} workflow.
*
* This function is usually called by the targeted contract to control immediate execution of restricted functions.
* Therefore we only return true if the call can be performed without any delay. If the call is subject to a
* previously set delay (not zero), then the function should return false and the caller should schedule the operation
* for future execution.
*
* If `immediate` is true, the delay can be disregarded and the operation can be immediately executed, otherwise
* the operation can be executed if and only if delay is greater than 0.
*
* NOTE: The IAuthority interface does not include the `uint32` delay. This is an extension of that interface that
* is backward compatible. Some contracts may thus ignore the second return argument. In that case they will fail
* to identify the indirect workflow, and will consider calls that require a delay to be forbidden.
*
* NOTE: This function does not report the permissions of this manager itself. These are defined by the
* {_canCallSelf} function instead.
*/
function canCall(
address caller,
address target,
bytes4 selector
) external view returns (bool allowed, uint32 delay);
/**
* @dev Expiration delay for scheduled proposals. Defaults to 1 week.
*
* IMPORTANT: Avoid overriding the expiration with 0. Otherwise every contract proposal will be expired immediately,
* disabling any scheduling usage.
*/
function expiration() external view returns (uint32);
/**
* @dev Minimum setback for all delay updates, with the exception of execution delays. It
* can be increased without setback (and reset via {revokeRole} in the case event of an
* accidental increase). Defaults to 5 days.
*/
function minSetback() external view returns (uint32);
/**
* @dev Get whether the contract is closed disabling any access. Otherwise role permissions are applied.
*/
function isTargetClosed(address target) external view returns (bool);
/**
* @dev Get the role required to call a function.
*/
function getTargetFunctionRole(address target, bytes4 selector) external view returns (uint64);
/**
* @dev Get the admin delay for a target contract. Changes to contract configuration are subject to this delay.
*/
function getTargetAdminDelay(address target) external view returns (uint32);
/**
* @dev Get the id of the role that acts as an admin for the given role.
*
* The admin permission is required to grant the role, revoke the role and update the execution delay to execute
* an operation that is restricted to this role.
*/
function getRoleAdmin(uint64 roleId) external view returns (uint64);
/**
* @dev Get the role that acts as a guardian for a given role.
*
* The guardian permission allows canceling operations that have been scheduled under the role.
*/
function getRoleGuardian(uint64 roleId) external view returns (uint64);
/**
* @dev Get the role current grant delay.
*
* Its value may change at any point without an event emitted following a call to {setGrantDelay}.
* Changes to this value, including effect timepoint are notified in advance by the {RoleGrantDelayChanged} event.
*/
function getRoleGrantDelay(uint64 roleId) external view returns (uint32);
/**
* @dev Get the access details for a given account for a given role. These details include the timepoint at which
* membership becomes active, and the delay applied to all operation by this user that requires this permission
* level.
*
* Returns:
* [0] Timestamp at which the account membership becomes valid. 0 means role is not granted.
* [1] Current execution delay for the account.
* [2] Pending execution delay for the account.
* [3] Timestamp at which the pending execution delay will become active. 0 means no delay update is scheduled.
*/
function getAccess(uint64 roleId, address account) external view returns (uint48, uint32, uint32, uint48);
/**
* @dev Check if a given account currently has the permission level corresponding to a given role. Note that this
* permission might be associated with an execution delay. {getAccess} can provide more details.
*/
function hasRole(uint64 roleId, address account) external view returns (bool, uint32);
/**
* @dev Give a label to a role, for improved role discoverability by UIs.
*
* Requirements:
*
* - the caller must be a global admin
*
* Emits a {RoleLabel} event.
*/
function labelRole(uint64 roleId, string calldata label) external;
/**
* @dev Add `account` to `roleId`, or change its execution delay.
*
* This gives the account the authorization to call any function that is restricted to this role. An optional
* execution delay (in seconds) can be set. If that delay is non 0, the user is required to schedule any operation
* that is restricted to members of this role. The user will only be able to execute the operation after the delay has
* passed, before it has expired. During this period, admin and guardians can cancel the operation (see {cancel}).
*
* If the account has already been granted this role, the execution delay will be updated. This update is not
* immediate and follows the delay rules. For example, if a user currently has a delay of 3 hours, and this is
* called to reduce that delay to 1 hour, the new delay will take some time to take effect, enforcing that any
* operation executed in the 3 hours that follows this update was indeed scheduled before this update.
*
* Requirements:
*
* - the caller must be an admin for the role (see {getRoleAdmin})
* - granted role must not be the `PUBLIC_ROLE`
*
* Emits a {RoleGranted} event.
*/
function grantRole(uint64 roleId, address account, uint32 executionDelay) external;
/**
* @dev Remove an account from a role, with immediate effect. If the account does not have the role, this call has
* no effect.
*
* Requirements:
*
* - the caller must be an admin for the role (see {getRoleAdmin})
* - revoked role must not be the `PUBLIC_ROLE`
*
* Emits a {RoleRevoked} event if the account had the role.
*/
function revokeRole(uint64 roleId, address account) external;
/**
* @dev Renounce role permissions for the calling account with immediate effect. If the sender is not in
* the role this call has no effect.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* Emits a {RoleRevoked} event if the account had the role.
*/
function renounceRole(uint64 roleId, address callerConfirmation) external;
/**
* @dev Change admin role for a given role.
*
* Requirements:
*
* - the caller must be a global admin
*
* Emits a {RoleAdminChanged} event
*/
function setRoleAdmin(uint64 roleId, uint64 admin) external;
/**
* @dev Change guardian role for a given role.
*
* Requirements:
*
* - the caller must be a global admin
*
* Emits a {RoleGuardianChanged} event
*/
function setRoleGuardian(uint64 roleId, uint64 guardian) external;
/**
* @dev Update the delay for granting a `roleId`.
*
* Requirements:
*
* - the caller must be a global admin
*
* Emits a {RoleGrantDelayChanged} event.
*/
function setGrantDelay(uint64 roleId, uint32 newDelay) external;
/**
* @dev Set the role required to call functions identified by the `selectors` in the `target` contract.
*
* Requirements:
*
* - the caller must be a global admin
*
* Emits a {TargetFunctionRoleUpdated} event per selector.
*/
function setTargetFunctionRole(address target, bytes4[] calldata selectors, uint64 roleId) external;
/**
* @dev Set the delay for changing the configuration of a given target contract.
*
* Requirements:
*
* - the caller must be a global admin
*
* Emits a {TargetAdminDelayUpdated} event.
*/
function setTargetAdminDelay(address target, uint32 newDelay) external;
/**
* @dev Set the closed flag for a contract.
*
* Requirements:
*
* - the caller must be a global admin
*
* Emits a {TargetClosed} event.
*/
function setTargetClosed(address target, bool closed) external;
/**
* @dev Return the timepoint at which a scheduled operation will be ready for execution. This returns 0 if the
* operation is not yet scheduled, has expired, was executed, or was canceled.
*/
function getSchedule(bytes32 id) external view returns (uint48);
/**
* @dev Return the nonce for the latest scheduled operation with a given id. Returns 0 if the operation has never
* been scheduled.
*/
function getNonce(bytes32 id) external view returns (uint32);
/**
* @dev Schedule a delayed operation for future execution, and return the operation identifier. It is possible to
* choose the timestamp at which the operation becomes executable as long as it satisfies the execution delays
* required for the caller. The special value zero will automatically set the earliest possible time.
*
* Returns the `operationId` that was scheduled. Since this value is a hash of the parameters, it can reoccur when
* the same parameters are used; if this is relevant, the returned `nonce` can be used to uniquely identify this
* scheduled operation from other occurrences of the same `operationId` in invocations of {execute} and {cancel}.
*
* Emits a {OperationScheduled} event.
*
* NOTE: It is not possible to concurrently schedule more than one operation with the same `target` and `data`. If
* this is necessary, a random byte can be appended to `data` to act as a salt that will be ignored by the target
* contract if it is using standard Solidity ABI encoding.
*/
function schedule(address target, bytes calldata data, uint48 when) external returns (bytes32, uint32);
/**
* @dev Execute a function that is delay restricted, provided it was properly scheduled beforehand, or the
* execution delay is 0.
*
* Returns the nonce that identifies the previously scheduled operation that is executed, or 0 if the
* operation wasn't previously scheduled (if the caller doesn't have an execution delay).
*
* Emits an {OperationExecuted} event only if the call was scheduled and delayed.
*/
function execute(address target, bytes calldata data) external payable returns (uint32);
/**
* @dev Cancel a scheduled (delayed) operation. Returns the nonce that identifies the previously scheduled
* operation that is cancelled.
*
* Requirements:
*
* - the caller must be the proposer, a guardian of the targeted function, or a global admin
*
* Emits a {OperationCanceled} event.
*/
function cancel(address caller, address target, bytes calldata data) external returns (uint32);
/**
* @dev Consume a scheduled operation targeting the caller. If such an operation exists, mark it as consumed
* (emit an {OperationExecuted} event and clean the state). Otherwise, throw an error.
*
* This is useful for contract that want to enforce that calls targeting them were scheduled on the manager,
* with all the verifications that it implies.
*
* Emit a {OperationExecuted} event.
*/
function consumeScheduledOp(address caller, bytes calldata data) external;
/**
* @dev Hashing function for delayed operations.
*/
function hashOperation(address caller, address target, bytes calldata data) external view returns (bytes32);
/**
* @dev Changes the authority of a target managed by this manager instance.
*
* Requirements:
*
* - the caller must be a global admin
*/
function updateAuthority(address target, address newAuthority) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/manager/IAuthority.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard interface for permissioning originally defined in Dappsys.
*/
interface IAuthority {
/**
* @dev Returns true if the caller can invoke on a target the function identified by a function selector.
*/
function canCall(address caller, address target, bytes4 selector) external view returns (bool allowed);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4626.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*/
interface IERC4626 is IERC20, IERC20Metadata {
event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed sender,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/**
* @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
*
* - MUST be an ERC-20 token contract.
* - MUST NOT revert.
*/
function asset() external view returns (address assetTokenAddress);
/**
* @dev Returns the total amount of the underlying asset that is “managed” by Vault.
*
* - SHOULD include any compounding that occurs from yield.
* - MUST be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT revert.
*/
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToShares(uint256 assets) external view returns (uint256 shares);
/**
* @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
* through a deposit call.
*
* - MUST return a limited value if receiver is subject to some deposit limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
* - MUST NOT revert.
*/
function maxDeposit(address receiver) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
* call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
* in the same transaction.
* - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
* deposit would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewDeposit(uint256 assets) external view returns (uint256 shares);
/**
* @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* deposit execution, and are accounted for during deposit.
* - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
* - MUST return a limited value if receiver is subject to some mint limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
* - MUST NOT revert.
*/
function maxMint(address receiver) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
* in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
* same transaction.
* - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
* would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by minting.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
* execution, and are accounted for during mint.
* - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
* Vault, through a withdraw call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
* call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
* called
* in the same transaction.
* - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
* the withdrawal would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* withdraw execution, and are accounted for during withdraw.
* - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
* through a redeem call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxRedeem(address owner) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
* in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
* same transaction.
* - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
* redemption would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by redeeming.
*/
function previewRedeem(uint256 shares) external view returns (uint256 assets);
/**
* @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* redeem execution, and are accounted for during redeem.
* - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
/// @title Interface for Fuses Common functions
interface IFuseCommon {
/// @notice Market ID associated with the Fuse
//solhint-disable-next-line
function MARKET_ID() external view returns (uint256);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {IAccessManager} from "@openzeppelin/contracts/access/manager/IAccessManager.sol";
/// @title Interface for the IporFusionAccessManager contract that manages access control for the IporFusion contract and its contract satellites
interface IIporFusionAccessManager is IAccessManager {
/// @notice The minimal delay required for the timelocked functions, value is set in the constructor, cannot be changed
/// @return The minimal delay in seconds
// solhint-disable-next-line func-name-mixedcase
function REDEMPTION_DELAY_IN_SECONDS() external view returns (uint256);
/// @notice Check if the caller can call the target with the given selector. Update the account lock time.
/// @dev canCall cannot be a view function because it updates the account lock time.
function canCallAndUpdate(
address caller,
address target,
bytes4 selector
) external returns (bool immediate, uint32 delay);
/// @notice Close or open given target to interact with methods with restricted modifiers.
/// @dev In most cases when Vault is bootstrapping the ADMIN_ROLE is revoked so custom method is needed to grant roles for a GUARDIAN_ROLE.
function updateTargetClosed(address target, bool closed) external;
/// @notice Converts the specified vault to a public vault - mint and deposit functions are allowed for everyone.
/// @dev Notice! Can convert to public but cannot convert back to private.
/// @param vault The address of the vault
function convertToPublicVault(address vault) external;
/// @notice Enables transfer shares, transfer and transferFrom functions are allowed for everyone.
/// @param vault The address of the vault
function enableTransferShares(address vault) external;
/// @notice Sets the minimal execution delay required for the specified roles.
/// @param rolesIds The roles for which the minimal execution delay is set
/// @param delays The minimal execution delays for the specified roles
function setMinimalExecutionDelaysForRoles(uint64[] calldata rolesIds, uint256[] calldata delays) external;
/// @notice Returns the minimal execution delay required for the specified role.
/// @param roleId The role for which the minimal execution delay is returned
/// @return The minimal execution delay in seconds
function getMinimalExecutionDelayForRole(uint64 roleId) external view returns (uint256);
/// @notice Returns the account lock time for the specified account.
/// @param account The account for which the account lock time is returned
/// @return The account lock time in seconds
function getAccountLockTime(address account) external view returns (uint256);
/// @notice Returns the function selector for the scheduled operation that is currently being consumed.
/// @return The function selector
function isConsumingScheduledOp() external view returns (bytes4);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
/// @notice FuseAction is a struct that represents a single action that can be executed by an Alpha
struct FuseAction {
/// @notice fuse is an address of the Fuse contract
address fuse;
/// @notice data is a bytes data that is passed to the Fuse contract
bytes data;
}
/// @title Plasma Vault interface with business methods
interface IPlasmaVault {
/// @notice Returns the total assets in the market with the given marketId
/// @param marketId_ The marketId of the market
/// @return The total assets in the market represented in underlying token decimals
function totalAssetsInMarket(uint256 marketId_) external view returns (uint256);
/**
* @notice Updates the balances of the specified markets.
* @param marketIds_ The array of market IDs to update balances for.
* @return The total assets in the Plasma Vault after updating the market balances.
* @dev If the `marketIds_` array is empty, it returns the total assets without updating any market balances.
* This function first records the total assets before updating the market balances, then updates the balances,
* adds the performance fee based on the assets before the update, and finally returns the new total assets.
*/
function updateMarketsBalances(uint256[] calldata marketIds_) external returns (uint256);
/// @notice Gets unrealized management fee
/// @return The unrealized management fee represented in underlying token decimals
function getUnrealizedManagementFee() external view returns (uint256);
/// @notice Execute fuse actions on the Plasma Vault via Fuses, by Alpha to perform actions which improve the performance earnings of the Plasma Vault
/// @param calls_ The array of FuseActions to execute
/// @dev Method is granted only to the Alpha
function execute(FuseAction[] calldata calls_) external;
/// @notice Claim rewards from the Plasma Vault via Rewards Fuses to claim rewards from connected protocols with the Plasma Vault
/// @param calls_ The array of FuseActions to claim rewards
/// @dev Method is granted only to the RewardsManager
function claimRewards(FuseAction[] calldata calls_) external;
/// @notice Deposit assets to the Plasma Vault with permit function
/// @param assets_ The amount of underlying assets to deposit
/// @param owner_ The owner of the assets
/// @param receiver_ The receiver of the assets
/// @param deadline_ The deadline for the permit function
/// @param v_ The v value of the signature
/// @param r_ The r value of the signature
/// @param s_ The s value of the signature
/// @return The amount of shares minted
function depositWithPermit(
uint256 assets_,
address owner_,
address receiver_,
uint256 deadline_,
uint8 v_,
bytes32 r_,
bytes32 s_
) external returns (uint256);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
/// @title Plasma Vault Base interface
interface IPlasmaVaultBase {
/// @notice Initializes the Plasma Vault
/// @dev Method is executed only once during the Plasma Vault construction in context of Plasma Vault (delegatecall used)
/// @param assetName_ The name of the asset
/// @param accessManager_ The address of the Ipor Fusion Access Manager
/// @param totalSupplyCap_ The total supply cap of the shares
function init(string memory assetName_, address accessManager_, uint256 totalSupplyCap_) external;
/// @notice When token are transferring, updates data in storage required for functionalities included in PlasmaVaultBase but in context of Plasma Vault (delegatecall used)
/// @param from_ The address from which the tokens are transferred
/// @param to_ The address to which the tokens are transferred
/// @param value_ The amount of tokens transferred
function updateInternal(address from_, address to_, uint256 value_) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {PlasmaVaultStorageLib} from "../libraries/PlasmaVaultStorageLib.sol";
import {InstantWithdrawalFusesParamsStruct} from "../libraries/PlasmaVaultLib.sol";
import {MarketLimit} from "../libraries/AssetDistributionProtectionLib.sol";
/// @title Plasma Vault Governance interface
interface IPlasmaVaultGovernance {
/// @notice Checks if the market has granted the substrate
/// @param marketId_ The marketId of the market
/// @param substrate_ The substrate to check
/// @return True if the market has granted the substrate
function isMarketSubstrateGranted(uint256 marketId_, bytes32 substrate_) external view returns (bool);
/// @notice Checks if fuse is supported
/// @param fuse_ The address of the fuse
/// @return True if the fuse is supported
function isFuseSupported(address fuse_) external view returns (bool);
/// @notice Checks if balance fuse is supported in a given market
/// @param marketId_ The marketId of the market
/// @param fuse_ The address of the fuse
/// @return True if the balance fuse is supported
function isBalanceFuseSupported(uint256 marketId_, address fuse_) external view returns (bool);
/// @notice Checks if the markets limits protection is activated
/// @return True if the markets limits protection is activated
function isMarketsLimitsActivated() external view returns (bool);
/// @notice Returns the array of market substrates granted in the market
/// @param marketId_ The marketId of the market
/// @return The array of substrates granted in the market
/// @dev Substrates can be assets, vault, markets or any other parameter specific for the market and associated with market external protocol
function getMarketSubstrates(uint256 marketId_) external view returns (bytes32[] memory);
/// @notice Returns the array of fuses supported by the Plasma Vault
/// @return The array of fuses
function getFuses() external view returns (address[] memory);
/// @notice Returns the address of the Price Oracle Middleware
/// @return The address of the Price Oracle Middleware
function getPriceOracleMiddleware() external view returns (address);
/// @notice Returns the performance fee configuration data of the Plasma Vault
/// @return feeData The performance fee configuration data, see PerformanceFeeData struct
function getPerformanceFeeData() external view returns (PlasmaVaultStorageLib.PerformanceFeeData memory feeData);
/// @notice Returns the management fee configuration data of the Plasma Vault
/// @return feeData The management fee configuration data, see ManagementFeeData struct
function getManagementFeeData() external view returns (PlasmaVaultStorageLib.ManagementFeeData memory feeData);
/// @notice Returns the address of the Ipor Fusion Access Manager
/// @return The address of the Ipor Fusion Access Manager
function getAccessManagerAddress() external view returns (address);
/// @notice Returns the address of the Rewards Claim Manager
/// @return The address of the Rewards Claim Manager
function getRewardsClaimManagerAddress() external view returns (address);
/// @notice Returns the array of fuses used during the instant withdrawal process, order of the fuses is important
/// @return The array of fuses, the order of the fuses is important
function getInstantWithdrawalFuses() external view returns (address[] memory);
/// @notice Returns the parameters used by the instant withdrawal fuses
/// @param fuse_ The address of the fuse
/// @param index_ The index of the fuse in the ordered array of fuses
/// @return The array of parameters used by the fuse
function getInstantWithdrawalFusesParams(address fuse_, uint256 index_) external view returns (bytes32[] memory);
/// @notice Returns the market limit for the given market in percentage represented in 1e18
/// @param marketId_ The marketId of the market
/// @return The market limit in percentage represented in 1e18
/// @dev This is percentage of the total balance in the Plasma Vault
function getMarketLimit(uint256 marketId_) external view returns (uint256);
/// @notice Gets the dependency balance graph for the given market, meaning the markets that are dependent on the given market and should be considered in the balance calculation
/// @param marketId_ The marketId of the market
/// @return Dependency balance graph is required because exists external protocols where interaction with the market can affect the balance of other markets
function getDependencyBalanceGraph(uint256 marketId_) external view returns (uint256[] memory);
/// @notice Returns the total supply cap
/// @return The total supply cap, the values is represented in underlying decimals
function getTotalSupplyCap() external view returns (uint256);
/// @notice Adds the balance fuse to the market
/// @param marketId_ The marketId of the market
/// @param fuse_ The address of the balance fuse
function addBalanceFuse(uint256 marketId_, address fuse_) external;
/// @notice Removes the balance fuse from the market
/// @param marketId_ The marketId of the market
/// @param fuse_ The address of the balance fuse
function removeBalanceFuse(uint256 marketId_, address fuse_) external;
/// @notice Grants the substrates to the market
/// @param marketId_ The marketId of the market
/// @param substrates_ The substrates to grant
/// @dev Substrates can be assets, vault, markets or any other parameter specific for the market and associated with market external protocol
function grantMarketSubstrates(uint256 marketId_, bytes32[] calldata substrates_) external;
/// @notice Updates the dependency balance graphs for the markets
/// @param marketIds_ The array of marketIds
/// @param dependencies_ dependency graph of markets
function updateDependencyBalanceGraphs(uint256[] memory marketIds_, uint256[][] memory dependencies_) external;
/// @notice Configures the instant withdrawal fuses. Order of the fuse is important, as it will be used in the same order during the instant withdrawal process
/// @param fuses_ The array of InstantWithdrawalFusesParamsStruct to configure
/// @dev Order of the fuses is important, the same fuse can be used multiple times with different parameters (for example different assets, markets or any other substrate specific for the fuse)
function configureInstantWithdrawalFuses(InstantWithdrawalFusesParamsStruct[] calldata fuses_) external;
/// @notice Adds the fuses supported by the Plasma Vault
/// @param fuses_ The array of fuses to add
function addFuses(address[] calldata fuses_) external;
/// @notice Removes the fuses supported by the Plasma Vault
/// @param fuses_ The array of fuses to remove
function removeFuses(address[] calldata fuses_) external;
/// @notice Sets the Price Oracle Middleware address
/// @param priceOracleMiddleware_ The address of the Price Oracle Middleware
function setPriceOracleMiddleware(address priceOracleMiddleware_) external;
/// @notice Configures the performance fee
/// @param feeAccount_ The address of the fee manager
/// @param feeInPercentage_ The fee in percentage represented in 18 decimals, example 1e18 is 100%, 1e17 is 10% etc.
function configurePerformanceFee(address feeAccount_, uint256 feeInPercentage_) external;
/// @notice Configures the management fee
/// @param feeAccount_ The address of the fee manager
/// @param feeInPercentage_ The fee in percentage represented in 18 decimals, example 1e18 is 100%, 1e17 is 10% etc.
function configureManagementFee(address feeAccount_, uint256 feeInPercentage_) external;
/// @notice Sets the Rewards Claim Manager address
/// @param rewardsClaimManagerAddress_ The address of the Rewards Claim Manager
function setRewardsClaimManagerAddress(address rewardsClaimManagerAddress_) external;
/// @notice Sets the market limit for the given market in percentage represented in 18 decimals
/// @param marketsLimits_ The array of MarketLimit to setup, see MarketLimit struct
function setupMarketsLimits(MarketLimit[] calldata marketsLimits_) external;
/// @notice Activates the markets limits protection, by default it is deactivated. After activation the limits is setup for each market separately.
function activateMarketsLimits() external;
/// @notice Deactivates the markets limits protection.
function deactivateMarketsLimits() external;
/// @notice Updates the callback handler
/// @param handler_ The address of the handler
/// @param sender_ The address of the sender
/// @param sig_ The signature of the function
function updateCallbackHandler(address handler_, address sender_, bytes4 sig_) external;
/// @notice Sets the total supply cap
/// @param cap_ The total supply cap, the values is represented in underlying decimals
function setTotalSupplyCap(uint256 cap_) external;
/// @notice Converts the specified vault to a public vault - mint and deposit functions are allowed for everyone.
/// @dev Notice! Can convert to public but cannot convert back to private.
function convertToPublicVault() external;
/// @notice Enables transfer shares, transfer and transferFrom functions are allowed for everyone.
function enableTransferShares() external;
/// @notice Sets the minimal execution delay required for the specified roles.
/// @param rolesIds_ The roles for which the minimal execution delay is set
/// @param delays_ The minimal execution delays for the specified roles
function setMinimalExecutionDelaysForRoles(uint64[] calldata rolesIds_, uint256[] calldata delays_) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
/// @title Interface to an aggregator of price feeds for assets, responsible for providing the prices of assets in a given quote currency
interface IPriceOracleMiddleware {
error EmptyArrayNotSupported();
error ArrayLengthMismatch();
error UnexpectedPriceResult();
error UnsupportedAsset();
error ZeroAddress(string variableName);
error WrongDecimals();
error WrongDecimalsInPriceFeed();
/// @notice Returns the price of the given asset in given decimals
/// @return assetPrice price in QUOTE_CURRENCY of the asset
/// @return decimals number of decimals of the asset price
function getAssetPrice(address asset) external view returns (uint256 assetPrice, uint256 decimals);
/// @notice Returns the prices of the given assets in given decimals
/// @return assetPrices prices in QUOTE_CURRENCY of the assets represented in given decimals
/// @return decimalsList number of decimals of the asset prices
function getAssetsPrices(
address[] calldata assets
) external view returns (uint256[] memory assetPrices, uint256[] memory decimalsList);
/// @notice Returns address of source of the asset price - it could be IPOR Price Feed or Chainlink Aggregator or any other source of price for a given asset
/// @param asset address of the asset
/// @return address of the source of the asset price
function getSourceOfAssetPrice(address asset) external view returns (address);
/// @notice Sets the sources of the asset prices
/// @param assets array of addresses of the assets
function setAssetsPricesSources(address[] calldata assets, address[] calldata sources) external;
/// @notice Returns the address of the quote currency to which all the prices are relative, in IPOR Fusion it is the USD
//solhint-disable-next-line
function QUOTE_CURRENCY() external view returns (address);
/// @notice Returns the number of decimals of the quote currency, by default it is 8 for USD, but can be different for other types of Price Oracles Middlewares
//solhint-disable-next-line
function QUOTE_CURRENCY_DECIMALS() external view returns (uint256);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {FuseAction} from "../interfaces/IPlasmaVault.sol";
/// @notice Vesting data struct
/// @custom:storage-location erc7201:io.ipor.managers.rewards.VestingData
struct VestingData {
/// @notice vestingTime The time when the vesting is pending
uint32 vestingTime;
/// @notice updateBalanceTimestamp The timestamp of the last balance update
uint32 updateBalanceTimestamp;
/// @notice transferredTokens The number of tokens that have been transferred from RewardsClaimManager to the Plasma Vault
uint128 transferredTokens;
/// @notice lastUpdateBalance The balance of the last update
uint128 lastUpdateBalance;
}
/// @title Rewards Claim Manager interface
interface IRewardsClaimManager {
/// @notice Retrieves the balance of linear vested underlying tokens owned by RewardsClaimManager.sol contract
/// @return balance The balance of the vesting data in uint256.
/// @dev This method calculates the current balance based on the vesting schedule.
/// If the `updateBalanceTimestamp` is zero, it returns zero. Otherwise, it calculates
/// the ratio of the elapsed time to the total vesting time to determine the proportion
/// of the balance that is currently available. The balance is adjusted by the number
/// of tokens that have already been transferred. Thr result is in underlying token decimals.
function balanceOf() external view returns (uint256);
/// @notice Checks if the specified reward fuse is supported.
/// @param fuse The address of the fuse to be checked.
/// @return supported A boolean value indicating whether the reward fuse is supported.
/// @dev This method checks the internal configuration to determine if the provided fuse address
/// is supported for reward management.
function isRewardFuseSupported(address fuse) external view returns (bool);
/// @notice Retrieves the vesting data.
/// @return vestingData A struct containing the vesting data.
/// @dev This method returns the current state of the vesting data, including details such as
/// the last update balance, the transferred tokens, and the timestamp of the last update.
function getVestingData() external view returns (VestingData memory);
/// @notice Transfers a specified amount of an asset to a given address.
/// @param asset The address of the asset to be transferred.
/// @param to The address of the recipient.
/// @param amount The amount of the asset to be transferred, represented in the asset's decimals.
/// @dev This method facilitates the transfer of a specified amount of the given asset from the contract to the recipient's address.
function transfer(address asset, address to, uint256 amount) external;
/// @notice Adds multiple reward fuses.
/// @param fuses An array of addresses representing the fuses to be added.
/// @dev This method adds the provided list of fuse addresses to the contract's configuration.
/// It allows the inclusion of multiple fuses in a single transaction for reward management purposes.
function addRewardFuses(address[] calldata fuses) external;
/// @notice Removes a specified reward fuse.
/// @param fuses The addresses of the fuse to be removed.
/// @dev This method removes the provided fuse address from the contract's configuration.
/// It is used to manage and update the list of supported reward fuses.
function removeRewardFuses(address[] calldata fuses) external;
/// @notice Claims rewards based on the provided fuse actions.
/// @param calls An array of FuseAction structs representing the actions for claiming rewards.
/// @dev This method processes the provided fuse actions to claim the corresponding rewards.
/// Each FuseAction in the array is executed to facilitate the reward claim process.
function claimRewards(FuseAction[] calldata calls) external;
/// @notice Sets up the vesting schedule with a specified delay for token release.
/// @param releaseTokensDelay The delay in seconds before the tokens are released.
/// @dev This method configures the vesting schedule by setting the delay time for token release.
/// The delay defines the period that must pass before the tokens can be released to the beneficiary.
// @dev setting up this to zero will stopped vesting and freeze underling token on the contract
function setupVestingTime(uint256 releaseTokensDelay) external;
/// @notice Updates the balance based on the current vesting schedule and transferred tokens.
/// @dev This method recalculates the balance considering the elapsed time, vesting schedule,
/// and the number of tokens that have already been transferred. It updates the internal
/// state to reflect the latest balance.
function updateBalance() external;
/// @notice Transfers vested underlying tokens to the Plasma Vault.
/// @dev This method transfers the underlying tokens that have vested according to the vesting schedule
/// to the designated Plasma Vault. It ensures that only the vested portion of the underlying tokens
/// is transferred.
function transferVestedTokensToVault() external;
/// @notice Retrieves the list of reward fuses.
/// @return An array of addresses representing the reward fuses.
function getRewardsFuses() external view returns (address[] memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {AccessManager} from "@openzeppelin/contracts/access/manager/AccessManager.sol";
import {IAccessManager} from "@openzeppelin/contracts/access/manager/IAccessManager.sol";
import {IIporFusionAccessManager} from "../../interfaces/IIporFusionAccessManager.sol";
import {RedemptionDelayLib} from "./RedemptionDelayLib.sol";
import {PlasmaVault} from "../../vaults/PlasmaVault.sol";
import {RoleExecutionTimelockLib} from "./RoleExecutionTimelockLib.sol";
import {IporFusionAccessManagerInitializationLib, InitializationData} from "./IporFusionAccessManagerInitializationLib.sol";
import {Roles} from "../../libraries/Roles.sol";
/// @title IporFusionAccessManager contract responsible for managing access control to the IporFusion contract
contract IporFusionAccessManager is IIporFusionAccessManager, AccessManager {
error AccessManagedUnauthorized(address caller);
error TooShortExecutionDelayForRole(uint64 roleId, uint32 executionDelay);
error TooLongRedemptionDelay(uint256 redemptionDelayInSeconds);
uint256 public constant MAX_REDEMPTION_DELAY_IN_SECONDS = 7 days;
uint256 public immutable override REDEMPTION_DELAY_IN_SECONDS;
bool private _customConsumingSchedule;
modifier restricted() {
_checkCanCall(_msgSender(), _msgData());
_;
}
constructor(address initialAdmin_, uint256 redemptionDelayInSeconds_) AccessManager(initialAdmin_) {
if (redemptionDelayInSeconds_ > MAX_REDEMPTION_DELAY_IN_SECONDS) {
revert TooLongRedemptionDelay(redemptionDelayInSeconds_);
}
REDEMPTION_DELAY_IN_SECONDS = redemptionDelayInSeconds_;
}
/// @notice Initializes the IporFusionAccessManager with the specified initial data.
/// @param initialData_ A struct containing the initial configuration data, including role-to-function mappings and execution delays.
/// @dev This method sets up the initial roles, functions, and minimal execution delays. It uses the IporFusionAccessManagerInitializationLib
/// to ensure that the contract is not already initialized, it can be done only once. The function is restricted to authorized callers.
function initialize(InitializationData calldata initialData_) external restricted {
IporFusionAccessManagerInitializationLib.isInitialized();
_revokeRole(ADMIN_ROLE, msg.sender);
uint256 roleToFunctionsLength = initialData_.roleToFunctions.length;
uint64[] memory roleIds = new uint64[](roleToFunctionsLength);
uint256[] memory minimalDelays = new uint256[](roleToFunctionsLength);
if (roleToFunctionsLength > 0) {
for (uint256 i; i < roleToFunctionsLength; ++i) {
_setTargetFunctionRole(
initialData_.roleToFunctions[i].target,
initialData_.roleToFunctions[i].functionSelector,
initialData_.roleToFunctions[i].roleId
);
roleIds[i] = initialData_.roleToFunctions[i].roleId;
minimalDelays[i] = initialData_.roleToFunctions[i].minimalExecutionDelay;
if (
initialData_.roleToFunctions[i].roleId != Roles.ADMIN_ROLE &&
initialData_.roleToFunctions[i].roleId != Roles.GUARDIAN_ROLE &&
initialData_.roleToFunctions[i].roleId != Roles.PUBLIC_ROLE
) {
_setRoleGuardian(initialData_.roleToFunctions[i].roleId, Roles.GUARDIAN_ROLE);
}
}
}
RoleExecutionTimelockLib.setMinimalExecutionDelaysForRoles(roleIds, minimalDelays);
uint256 adminRolesLength = initialData_.adminRoles.length;
if (adminRolesLength > 0) {
for (uint256 i; i < adminRolesLength; ++i) {
_setRoleAdmin(initialData_.adminRoles[i].roleId, initialData_.adminRoles[i].adminRoleId);
}
}
uint256 accountToRolesLength = initialData_.accountToRoles.length;
if (accountToRolesLength > 0) {
for (uint256 i; i < accountToRolesLength; ++i) {
_grantRoleInternal(
initialData_.accountToRoles[i].roleId,
initialData_.accountToRoles[i].account,
initialData_.accountToRoles[i].executionDelay
);
}
}
}
function canCallAndUpdate(
address caller_,
address target_,
bytes4 selector_
) external override returns (bool immediate, uint32 delay) {
RedemptionDelayLib.lockChecks(caller_, selector_);
return super.canCall(caller_, target_, selector_);
}
function updateTargetClosed(address target_, bool closed_) external override restricted {
_setTargetClosed(target_, closed_);
}
function convertToPublicVault(address vault_) external override restricted {
_setTargetFunctionRole(vault_, PlasmaVault.mint.selector, PUBLIC_ROLE);
_setTargetFunctionRole(vault_, PlasmaVault.deposit.selector, PUBLIC_ROLE);
_setTargetFunctionRole(vault_, PlasmaVault.depositWithPermit.selector, PUBLIC_ROLE);
}
function enableTransferShares(address vault_) external override restricted {
_setTargetFunctionRole(vault_, PlasmaVault.transfer.selector, PUBLIC_ROLE);
_setTargetFunctionRole(vault_, PlasmaVault.transferFrom.selector, PUBLIC_ROLE);
}
function setMinimalExecutionDelaysForRoles(
uint64[] calldata rolesIds_,
uint256[] calldata delays_
) external override restricted {
RoleExecutionTimelockLib.setMinimalExecutionDelaysForRoles(rolesIds_, delays_);
}
function grantRole(
uint64 roleId_,
address account_,
uint32 executionDelay_
) public override(IAccessManager, AccessManager) onlyAuthorized {
_grantRoleInternal(roleId_, account_, executionDelay_);
}
function getMinimalExecutionDelayForRole(uint64 roleId_) external view override returns (uint256) {
return RoleExecutionTimelockLib.getMinimalExecutionDelayForRole(roleId_);
}
function getAccountLockTime(address account_) external view override returns (uint256) {
return RedemptionDelayLib.getAccountLockTime(account_);
}
function isConsumingScheduledOp() external view override returns (bytes4) {
return _customConsumingSchedule ? this.isConsumingScheduledOp.selector : bytes4(0);
}
function _grantRoleInternal(uint64 roleId_, address account_, uint32 executionDelay_) internal {
if (executionDelay_ < RoleExecutionTimelockLib.getMinimalExecutionDelayForRole(roleId_)) {
revert TooShortExecutionDelayForRole(roleId_, executionDelay_);
}
_grantRole(roleId_, account_, getRoleGrantDelay(roleId_), executionDelay_);
}
function _checkCanCall(address caller_, bytes calldata data_) internal virtual {
(bool immediate, uint32 delay) = canCall(caller_, address(this), bytes4(data_[0:4]));
if (!immediate) {
if (delay > 0) {
_customConsumingSchedule = true;
IAccessManager(address(this)).consumeScheduledOp(caller_, data_);
_customConsumingSchedule = false;
} else {
revert AccessManagedUnauthorized(caller_);
}
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {IporFusionAccessManagersStorageLib, InitializationFlag} from "./IporFusionAccessManagersStorageLib.sol";
/// @notice Struct for the role-to-function mapping
struct RoleToFunction {
/// @notice The target contract address
address target;
/// @notice The role ID
uint64 roleId;
/// @notice The function selector
bytes4 functionSelector;
/// @notice The minimal execution delay, if greater than 0 then the function is timelocked
uint256 minimalExecutionDelay;
}
/// @notice Struct for the admin role mapping
struct AdminRole {
/// @notice The role ID
uint64 roleId;
/// @notice The admin role ID
uint64 adminRoleId;
}
/// @notice Struct for the account-to-role mapping
struct AccountToRole {
/// @notice The role ID
uint64 roleId;
/// @notice The account address
address account;
/// @notice The account lock time, if greater than 0 then the execution is timelocked for a given account
uint32 executionDelay;
}
/// @notice Struct for the initialization data for the IporFusionAccessManager contract
struct InitializationData {
/// @notice The role-to-function mappings
RoleToFunction[] roleToFunctions;
/// @notice The account-to-role mappings
AccountToRole[] accountToRoles;
/// @notice The admin role mappings
AdminRole[] adminRoles;
}
/// @title Library for initializing the IporFusionAccessManager contract, initializing the contract can only be done once
library IporFusionAccessManagerInitializationLib {
event IporFusionAccessManagerInitialized();
error AlreadyInitialized();
/// @notice Checks if the contract is already initialized
/// @dev The function checks if the contract is already initialized, if it is, it reverts with an error
function isInitialized() internal {
InitializationFlag storage initializationFlag = IporFusionAccessManagersStorageLib.getInitializationFlag();
if (initializationFlag.initialized > 0) {
revert AlreadyInitialized();
}
initializationFlag.initialized = 1;
emit IporFusionAccessManagerInitialized();
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {IIporFusionAccessManager} from "../../interfaces/IIporFusionAccessManager.sol";
/// @notice RedemptionLocks storage structure
/// @custom:storage-location erc7201:io.ipor.managers.access.RedemptionLocks
struct RedemptionLocks {
mapping(address acount => uint256 depositTime) redemptionLock;
}
/// @custom:storage-location erc7201:io.ipor.managers.access.MinimalExecutionDelayForRole
struct MinimalExecutionDelayForRole {
mapping(uint64 roleId => uint256 delay) delays;
}
/// @custom:storage-location erc7201:io.ipor.managers.access.InitializationFlag
struct InitializationFlag {
// @dev if greater than 0 then initialized
uint256 initialized;
}
/// @title Storage library for Managers contracts
library IporFusionAccessManagersStorageLib {
using SafeCast for uint256;
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.managers.access.RedemptionLocks")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant REDEMPTION_LOCKS = 0x5e07febb5bd598f6b55406c9bf939d497fd39a2dbc2b5891f20f6640c3f32500;
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.managers.access.MinimalExecutionDelayForRole")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant MINIMAL_EXECUTION_DELAY_FOR_ROLE =
0x2e44a6c6f75b62bc581bae68fca3a6629eb7343eef230a6702d4acd6389fd600;
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.managers.access.InitializationFlag")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant INITIALIZATION_FLAG = 0x25e922da7c41a5d012dbc2479dd6a7bd57760f359ea3a3be13608d287fc89400;
event RedemptionDelayForAccountUpdated(address account, uint256 redemptionDelay);
/// @notice gets the Ipor Fusion Access Manager initialization flag storage pointer
/// @return initializationFlag the storage pointer to the Ipor Fusion Access Manager initialization flag
function getInitializationFlag() internal view returns (InitializationFlag storage initializationFlag) {
assembly {
initializationFlag.slot := INITIALIZATION_FLAG
}
}
/// @notice gets the minimal execution delay for role storage pointer
/// @return minimalExecutionDelayForRole the storage pointer to the minimal execution delay for role
function getMinimalExecutionDelayForRole()
internal
pure
returns (MinimalExecutionDelayForRole storage minimalExecutionDelayForRole)
{
assembly {
minimalExecutionDelayForRole.slot := MINIMAL_EXECUTION_DELAY_FOR_ROLE
}
}
/// @notice gets the redemption locks storage pointer
/// @return redemptionLocks the storage pointer to the redemption locks
function getRedemptionLocks() internal view returns (RedemptionLocks storage redemptionLocks) {
assembly {
redemptionLocks.slot := REDEMPTION_LOCKS
}
}
/// @notice sets the redemption locks for an account
/// @param account_ the account to set the redemption locks for
/// @dev When deposit or mint functions are called, the account is locked for withdraw and redeem functions for a specific time defined by the redemption delay
function setRedemptionLocks(address account_) internal {
uint256 redemptionDelay = IIporFusionAccessManager(address(this)).REDEMPTION_DELAY_IN_SECONDS();
if (redemptionDelay == 0) {
return;
}
RedemptionLocks storage redemptionLocks = getRedemptionLocks();
uint256 redemptionLock = uint256(block.timestamp) + redemptionDelay;
redemptionLocks.redemptionLock[account_] = redemptionLock;
emit RedemptionDelayForAccountUpdated(account_, redemptionLock);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
/// @title Ipor Math library with math functions
library IporMath {
uint256 private constant WAD_DECIMALS = 18;
uint256 public constant BASIS_OF_POWER = 10;
/// @dev The index of the most significant bit in a 256-bit signed integer
uint256 private constant MSB = 255;
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/// @notice Converts the value to WAD decimals, WAD decimals are 18
/// @param value The value to convert
/// @param assetDecimals The decimals of the asset
/// @return The value in WAD decimals
function convertToWad(uint256 value, uint256 assetDecimals) internal pure returns (uint256) {
if (value > 0) {
if (assetDecimals == WAD_DECIMALS) {
return value;
} else if (assetDecimals > WAD_DECIMALS) {
return division(value, BASIS_OF_POWER ** (assetDecimals - WAD_DECIMALS));
} else {
return value * BASIS_OF_POWER ** (WAD_DECIMALS - assetDecimals);
}
} else {
return value;
}
}
/// @notice Converts the value to WAD decimals, WAD decimals are 18
/// @param value The value to convert
/// @param assetDecimals The decimals of the asset
/// @return The value in WAD decimals
function convertWadToAssetDecimals(uint256 value, uint256 assetDecimals) internal pure returns (uint256) {
if (assetDecimals == WAD_DECIMALS) {
return value;
} else if (assetDecimals > WAD_DECIMALS) {
return value * WAD_DECIMALS ** (assetDecimals - WAD_DECIMALS);
} else {
return division(value, BASIS_OF_POWER ** (WAD_DECIMALS - assetDecimals));
}
}
/// @notice Converts the int value to WAD decimals, WAD decimals are 18
/// @param value The int value to convert
/// @param assetDecimals The decimals of the asset
/// @return The value in WAD decimals, int
function convertToWadInt(int256 value, uint256 assetDecimals) internal pure returns (int256) {
if (value == 0) {
return 0;
}
if (assetDecimals == WAD_DECIMALS) {
return value;
} else if (assetDecimals > WAD_DECIMALS) {
return divisionInt(value, int256(BASIS_OF_POWER ** (assetDecimals - WAD_DECIMALS)));
} else {
return value * int256(BASIS_OF_POWER ** (WAD_DECIMALS - assetDecimals));
}
}
/// @notice Divides two int256 numbers and rounds the result to the nearest integer
/// @param x The numerator
/// @param y The denominator
/// @return z The result of the division
function divisionInt(int256 x, int256 y) internal pure returns (int256 z) {
uint256 absX = uint256(x < 0 ? -x : x);
uint256 absY = uint256(y < 0 ? -y : y);
// Use bitwise XOR to get the sign on MBS bit then shift to LSB
// sign == 0x0000...0000 == 0 if the number is non-negative
// sign == 0xFFFF...FFFF == -1 if the number is negative
int256 sign = (x ^ y) >> MSB;
uint256 divAbs;
uint256 remainder;
unchecked {
divAbs = absX / absY;
remainder = absX % absY;
}
// Check if we need to round
if (sign < 0) {
// remainder << 1 left shift is equivalent to multiplying by 2
if (remainder << 1 > absY) {
++divAbs;
}
} else {
if (remainder << 1 >= absY) {
++divAbs;
}
}
// (sign | 1) is cheaper than (sign < 0) ? -1 : 1;
unchecked {
z = int256(divAbs) * (sign | 1);
}
}
/// @notice Divides two uint256 numbers and rounds the result to the nearest integer
/// @param x The numerator
/// @param y The denominator
/// @return z The result of the division
function division(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x / y;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Multicall.sol)
pragma solidity ^0.8.20;
import {Address} from "./Address.sol";
import {Context} from "./Context.sol";
/**
* @dev Provides a function to batch together multiple calls in a single external call.
*
* Consider any assumption about calldata validation performed by the sender may be violated if it's not especially
* careful about sending transactions invoking {multicall}. For example, a relay address that filters function
* selectors won't filter calls nested within a {multicall} operation.
*
* NOTE: Since 5.0.1 and 4.9.4, this contract identifies non-canonical contexts (i.e. `msg.sender` is not {_msgSender}).
* If a non-canonical context is identified, the following self `delegatecall` appends the last bytes of `msg.data`
* to the subcall. This makes it safe to use with {ERC2771Context}. Contexts that don't affect the resolution of
* {_msgSender} are not propagated to subcalls.
*/
abstract contract Multicall is Context {
/**
* @dev Receives and executes a batch of function calls on this contract.
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {
bytes memory context = msg.sender == _msgSender()
? new bytes(0)
: msg.data[msg.data.length - _contextSuffixLength():];
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
results[i] = Address.functionDelegateCall(address(this), bytes.concat(data[i], context));
}
return results;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IAccessManager} from "@openzeppelin/contracts/access/manager/IAccessManager.sol";
import {AuthorityUtils} from "@openzeppelin/contracts/access/manager/AuthorityUtils.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {ERC4626Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC4626Upgradeable.sol";
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import {Errors} from "../libraries/errors/Errors.sol";
import {IporMath} from "../libraries/math/IporMath.sol";
import {IPlasmaVault, FuseAction} from "../interfaces/IPlasmaVault.sol";
import {IFuseCommon} from "../fuses/IFuseCommon.sol";
import {IPlasmaVaultBase} from "../interfaces/IPlasmaVaultBase.sol";
import {IPlasmaVaultGovernance} from "../interfaces/IPlasmaVaultGovernance.sol";
import {IPriceOracleMiddleware} from "../price_oracle/IPriceOracleMiddleware.sol";
import {IRewardsClaimManager} from "../interfaces/IRewardsClaimManager.sol";
import {AccessManagedUpgradeable} from "../managers/access/AccessManagedUpgradeable.sol";
import {PlasmaVaultStorageLib} from "../libraries/PlasmaVaultStorageLib.sol";
import {PlasmaVaultConfigLib} from "../libraries/PlasmaVaultConfigLib.sol";
import {IporFusionAccessManager} from "../managers/access/IporFusionAccessManager.sol";
import {PlasmaVaultGovernance} from "./PlasmaVaultGovernance.sol";
import {AssetDistributionProtectionLib, DataToCheck, MarketToCheck} from "../libraries/AssetDistributionProtectionLib.sol";
import {CallbackHandlerLib} from "../libraries/CallbackHandlerLib.sol";
import {FusesLib} from "../libraries/FusesLib.sol";
import {PlasmaVaultLib} from "../libraries/PlasmaVaultLib.sol";
import {FeeManagerData, FeeManagerFactory} from "../managers/fee/FeeManagerFactory.sol";
import {FeeManagerInitData} from "../managers/fee/FeeManager.sol";
import {WithdrawManager} from "../managers/withdraw/WithdrawManager.sol";
/// @notice PlasmaVaultInitData is a struct that represents a configuration of a Plasma Vault during construction
struct PlasmaVaultInitData {
/// @notice assetName is a name of the asset shares in Plasma Vault
string assetName;
/// @notice assetSymbol is a symbol of the asset shares in Plasma Vault
string assetSymbol;
/// @notice underlyingToken is a address of the underlying token in Plasma Vault
address underlyingToken;
/// @notice priceOracleMiddleware is an address of the Price Oracle Middleware from Ipor Fusion
address priceOracleMiddleware;
/// @notice marketSubstratesConfigs is a list of MarketSubstratesConfig structs, which define substrates for specific markets
MarketSubstratesConfig[] marketSubstratesConfigs;
/// @notice fuses is a list of addresses of the Fuses
address[] fuses;
/// @notice balanceFuses is a list of MarketBalanceFuseConfig structs, which define balance fuses for specific markets
MarketBalanceFuseConfig[] balanceFuses;
/// @notice feeConfig is a FeeConfig struct, which defines performance, management fees and their managers
FeeConfig feeConfig;
/// @notice accessManager is a address of the Ipor Fusion Access Manager
address accessManager;
/// @notice plasmaVaultBase is a address of the Plasma Vault Base - contract that is responsible for the common logic of the Plasma Vault
address plasmaVaultBase;
/// @notice totalSupplyCap is a initial total supply cap of the Plasma Vault, represented in underlying token decimals
uint256 totalSupplyCap;
// @notice Address of the Withdraw Manager contract
address withdrawManager;
}
/// @notice MarketBalanceFuseConfig is a struct that represents a configuration of a balance fuse for a specific market
struct MarketBalanceFuseConfig {
/// @notice When marketId is 0, then fuse is independent to a market - example flashloan fuse
uint256 marketId;
/// @notice address of the balance fuse
address fuse;
}
/// @notice MarketSubstratesConfig is a struct that represents a configuration of substrates for a specific market
/// @notice substrates are assets or sub markets in a specific protocol or any other ids required to calculate balance in the market (external protocol)
struct MarketSubstratesConfig {
/// @notice marketId is a id of the market
uint256 marketId;
/// @notice substrates is a list of substrates for the market
/// @dev it could be list of assets or sub markets in a specific protocol or any other ids required to calculate balance in the market (external protocol)
bytes32[] substrates;
}
/// @notice FeeConfig is a struct that represents the configuration of fees in the Plasma Vault
struct FeeConfig {
/// @notice The management fee for the DAO (percentage with 2 decimals, e.g., 10000 is 100%, 100 is 1%)
uint256 iporDaoManagementFee;
/// @notice The performance fee for the DAO (percentage with 2 decimals, e.g., 10000 is 100%, 100 is 1%)
uint256 iporDaoPerformanceFee;
/// @notice The management fee for the Atomist (percentage with 2 decimals, e.g., 10000 is 100%, 100 is 1%)
uint256 atomistManagementFee;
/// @notice The performance fee for the Atomist (percentage with 2 decimals, e.g., 10000 is 100%, 100 is 1%)
uint256 atomistPerformanceFee;
/// @notice The address of the fee factory
address feeFactory;
/// @notice The address of the fee recipient
address feeRecipientAddress;
/// @notice The address of the DAO fee recipient
address iporDaoFeeRecipientAddress;
}
/// @title Main contract of the Plasma Vault in ERC4626 standard - responsible for managing assets and shares by the Alphas via Fuses.
contract PlasmaVault is
ERC20Upgradeable,
ERC4626Upgradeable,
ReentrancyGuardUpgradeable,
AccessManagedUpgradeable,
IPlasmaVault
{
using Address for address;
using SafeCast for int256;
address private constant USD = address(0x0000000000000000000000000000000000000348);
/// @dev Additional offset to withdraw from markets in case of rounding issues
uint256 private constant WITHDRAW_FROM_MARKETS_OFFSET = 10;
/// @dev 10 attempts to withdraw from markets in case of rounding issues
uint256 private constant REDEEM_ATTEMPTS = 10;
uint256 public constant DEFAULT_SLIPPAGE_IN_PERCENTAGE = 2;
error NoSharesToRedeem();
error NoSharesToMint();
error NoAssetsToWithdraw();
error NoAssetsToDeposit();
error UnsupportedFuse();
error UnsupportedMethod();
error WithdrawIsNotAllowed(address caller, uint256 requested);
event ManagementFeeRealized(uint256 unrealizedFeeInUnderlying, uint256 unrealizedFeeInShares);
event MarketBalancesUpdated(uint256[] marketIds, int256 deltaInUnderlying);
address public immutable PLASMA_VAULT_BASE;
constructor(PlasmaVaultInitData memory initData_) ERC20Upgradeable() ERC4626Upgradeable() initializer {
super.__ERC20_init(initData_.assetName, initData_.assetSymbol);
super.__ERC4626_init(IERC20(initData_.underlyingToken));
PLASMA_VAULT_BASE = initData_.plasmaVaultBase;
PLASMA_VAULT_BASE.functionDelegateCall(
abi.encodeWithSelector(
IPlasmaVaultBase.init.selector,
initData_.assetName,
initData_.accessManager,
initData_.totalSupplyCap
)
);
IPriceOracleMiddleware priceOracleMiddleware = IPriceOracleMiddleware(initData_.priceOracleMiddleware);
if (priceOracleMiddleware.QUOTE_CURRENCY() != USD) {
revert Errors.UnsupportedQuoteCurrencyFromOracle();
}
PlasmaVaultLib.setPriceOracleMiddleware(initData_.priceOracleMiddleware);
PLASMA_VAULT_BASE.functionDelegateCall(
abi.encodeWithSelector(PlasmaVaultGovernance.addFuses.selector, initData_.fuses)
);
for (uint256 i; i < initData_.balanceFuses.length; ++i) {
// @dev in the moment of construction deployer has rights to add balance fuses
PLASMA_VAULT_BASE.functionDelegateCall(
abi.encodeWithSelector(
IPlasmaVaultGovernance.addBalanceFuse.selector,
initData_.balanceFuses[i].marketId,
initData_.balanceFuses[i].fuse
)
);
}
for (uint256 i; i < initData_.marketSubstratesConfigs.length; ++i) {
PlasmaVaultConfigLib.grantMarketSubstrates(
initData_.marketSubstratesConfigs[i].marketId,
initData_.marketSubstratesConfigs[i].substrates
);
}
FeeManagerData memory feeManagerData = FeeManagerFactory(initData_.feeConfig.feeFactory).deployFeeManager(
FeeManagerInitData({
iporDaoManagementFee: initData_.feeConfig.iporDaoManagementFee,
iporDaoPerformanceFee: initData_.feeConfig.iporDaoPerformanceFee,
atomistManagementFee: initData_.feeConfig.atomistManagementFee,
atomistPerformanceFee: initData_.feeConfig.atomistPerformanceFee,
initialAuthority: initData_.accessManager,
plasmaVault: address(this),
feeRecipientAddress: initData_.feeConfig.feeRecipientAddress,
iporDaoFeeRecipientAddress: initData_.feeConfig.iporDaoFeeRecipientAddress
})
);
PlasmaVaultLib.configurePerformanceFee(feeManagerData.performanceFeeAccount, feeManagerData.performanceFee);
PlasmaVaultLib.configureManagementFee(feeManagerData.managementFeeAccount, feeManagerData.managementFee);
PlasmaVaultLib.updateManagementFeeData();
/// @dev If the address is zero, it means that scheduled withdrawals are turned off.
PlasmaVaultLib.updateWithdrawManager(initData_.withdrawManager);
}
fallback(bytes calldata) external returns (bytes memory) {
if (PlasmaVaultLib.isExecutionStarted()) {
/// @dev Handle callback can be done only during the execution of the FuseActions by Alpha
CallbackHandlerLib.handleCallback();
return "";
} else {
return PLASMA_VAULT_BASE.functionDelegateCall(msg.data);
}
}
/// @notice Execute multiple FuseActions by a granted Alphas. Any FuseAction is moving funds between markets and vault. Fuse Action not consider deposit and withdraw from Vault.
function execute(FuseAction[] calldata calls_) external override nonReentrant restricted {
uint256 callsCount = calls_.length;
uint256[] memory markets = new uint256[](callsCount);
uint256 marketIndex;
uint256 fuseMarketId;
uint256 totalAssetsBefore = totalAssets();
PlasmaVaultLib.executeStarted();
for (uint256 i; i < callsCount; ++i) {
if (!FusesLib.isFuseSupported(calls_[i].fuse)) {
revert UnsupportedFuse();
}
fuseMarketId = IFuseCommon(calls_[i].fuse).MARKET_ID();
if (_checkIfExistsMarket(markets, fuseMarketId) == false) {
markets[marketIndex] = fuseMarketId;
marketIndex++;
}
calls_[i].fuse.functionDelegateCall(calls_[i].data);
}
PlasmaVaultLib.executeFinished();
_updateMarketsBalances(markets);
_addPerformanceFee(totalAssetsBefore);
}
function updateMarketsBalances(uint256[] calldata marketIds_) external returns (uint256) {
if (marketIds_.length == 0) {
return totalAssets();
}
uint256 totalAssetsBefore = totalAssets();
_updateMarketsBalances(marketIds_);
_addPerformanceFee(totalAssetsBefore);
return totalAssets();
}
function decimals() public view virtual override(ERC20Upgradeable, ERC4626Upgradeable) returns (uint8) {
return super.decimals();
}
function transfer(
address to_,
uint256 value_
) public virtual override(IERC20, ERC20Upgradeable) restricted returns (bool) {
return super.transfer(to_, value_);
}
function transferFrom(
address from_,
address to_,
uint256 value_
) public virtual override(IERC20, ERC20Upgradeable) restricted returns (bool) {
return super.transferFrom(from_, to_, value_);
}
function deposit(uint256 assets_, address receiver_) public override nonReentrant restricted returns (uint256) {
return _deposit(assets_, receiver_);
}
function depositWithPermit(
uint256 assets_,
address owner_,
address receiver_,
uint256 deadline_,
uint8 v_,
bytes32 r_,
bytes32 s_
) external override nonReentrant restricted returns (uint256) {
IERC20Permit(asset()).permit(owner_, address(this), assets_, deadline_, v_, r_, s_);
return _deposit(assets_, receiver_);
}
function mint(uint256 shares_, address receiver_) public override nonReentrant restricted returns (uint256) {
if (shares_ == 0) {
revert NoSharesToMint();
}
if (receiver_ == address(0)) {
revert Errors.WrongAddress();
}
_realizeManagementFee();
return super.mint(shares_, receiver_);
}
function withdraw(
uint256 assets_,
address receiver_,
address owner_
) public override nonReentrant restricted returns (uint256) {
if (assets_ == 0) {
revert NoAssetsToWithdraw();
}
if (receiver_ == address(0)) {
revert Errors.WrongAddress();
}
/// @dev first realize management fee, then other actions
_realizeManagementFee();
uint256 totalAssetsBefore = totalAssets();
_withdrawFromMarkets(assets_ + WITHDRAW_FROM_MARKETS_OFFSET, IERC20(asset()).balanceOf(address(this)));
_addPerformanceFee(totalAssetsBefore);
return super.withdraw(assets_, receiver_, owner_);
}
function redeem(
uint256 shares_,
address receiver_,
address owner_
) public override nonReentrant restricted returns (uint256) {
if (shares_ == 0) {
revert NoSharesToRedeem();
}
if (receiver_ == address(0) || owner_ == address(0)) {
revert Errors.WrongAddress();
}
/// @dev first realize management fee, then other actions
_realizeManagementFee();
uint256 assets;
uint256 vaultCurrentBalanceUnderlying;
uint256 totalAssetsBefore = totalAssets();
for (uint256 i; i < REDEEM_ATTEMPTS; ++i) {
assets = convertToAssets(shares_);
vaultCurrentBalanceUnderlying = IERC20(asset()).balanceOf(address(this));
if (vaultCurrentBalanceUnderlying >= assets) {
break;
}
_withdrawFromMarkets(_includeSlippage(assets), vaultCurrentBalanceUnderlying);
}
_addPerformanceFee(totalAssetsBefore);
return super.redeem(shares_, receiver_, owner_);
}
function maxDeposit(address) public view virtual override returns (uint256) {
uint256 totalSupplyCap = PlasmaVaultLib.getTotalSupplyCap();
uint256 totalSupply = totalSupply();
if (totalSupply >= totalSupplyCap) {
return 0;
}
return convertToAssets(totalSupplyCap - totalSupply);
}
function maxMint(address) public view virtual override returns (uint256) {
uint256 totalSupplyCap = PlasmaVaultLib.getTotalSupplyCap();
uint256 totalSupply = totalSupply();
if (totalSupply >= totalSupplyCap) {
return 0;
}
return totalSupplyCap - totalSupply;
}
function claimRewards(FuseAction[] calldata calls_) external override nonReentrant restricted {
uint256 callsCount = calls_.length;
for (uint256 i; i < callsCount; ++i) {
calls_[i].fuse.functionDelegateCall(calls_[i].data);
}
}
/// @notice Returns the total assets in the vault
/// @dev value not take into account runtime accrued interest in the markets, and NOT take into account runtime accrued performance fee
/// @return total assets in the vault, represented in underlying token decimals
function totalAssets() public view virtual override returns (uint256) {
uint256 grossTotalAssets = _getGrossTotalAssets();
uint256 unrealizedManagementFee = _getUnrealizedManagementFee(grossTotalAssets);
if (unrealizedManagementFee >= grossTotalAssets) {
return 0;
} else {
return grossTotalAssets - unrealizedManagementFee;
}
}
/// @notice Returns the total assets in the vault for a specific market
/// @param marketId_ The market id
/// @return total assets in the Plasma Vault for given market, represented in underlying token decimals
function totalAssetsInMarket(uint256 marketId_) public view virtual returns (uint256) {
return PlasmaVaultLib.getTotalAssetsInMarket(marketId_);
}
/// @notice Returns the unrealized management fee in underlying token decimals
/// @dev Unrealized management fee is calculated based on the management fee in percentage and the time since the last update
/// @return unrealized management fee, represented in underlying token decimals
function getUnrealizedManagementFee() public view returns (uint256) {
return _getUnrealizedManagementFee(_getGrossTotalAssets());
}
/// @dev Mustn't use updateInternal, because is reserved for PlasmaVaultBase to call it as delegatecall in context of PlasmaVault
function updateInternal(address, address, uint256) public {
revert UnsupportedMethod();
}
function executeInternal(FuseAction[] calldata calls_) external {
if (address(this) != msg.sender) {
revert Errors.WrongCaller(msg.sender);
}
uint256 callsCount = calls_.length;
uint256[] memory markets = new uint256[](callsCount);
uint256 marketIndex;
uint256 fuseMarketId;
for (uint256 i; i < callsCount; ++i) {
if (!FusesLib.isFuseSupported(calls_[i].fuse)) {
revert UnsupportedFuse();
}
fuseMarketId = IFuseCommon(calls_[i].fuse).MARKET_ID();
if (_checkIfExistsMarket(markets, fuseMarketId) == false) {
markets[marketIndex] = fuseMarketId;
marketIndex++;
}
calls_[i].fuse.functionDelegateCall(calls_[i].data);
}
_updateMarketsBalances(markets);
}
function getUniqueElements(uint256[] memory inputArray) private pure returns (uint256[] memory) {
uint256[] memory tempArray = new uint256[](inputArray.length);
uint256 count = 0;
for (uint256 i = 0; i < inputArray.length; i++) {
if (inputArray[i] != 0 && !contains(tempArray, inputArray[i], count)) {
tempArray[count] = inputArray[i];
count++;
}
}
uint256[] memory uniqueArray = new uint256[](count);
for (uint256 i = 0; i < count; i++) {
uniqueArray[i] = tempArray[i];
}
return uniqueArray;
}
function contains(uint256[] memory array, uint256 element, uint256 count) private pure returns (bool) {
for (uint256 i = 0; i < count; i++) {
if (array[i] == element) {
return true;
}
}
return false;
}
function _deposit(uint256 assets_, address receiver_) internal returns (uint256) {
if (assets_ == 0) {
revert NoAssetsToDeposit();
}
if (receiver_ == address(0)) {
revert Errors.WrongAddress();
}
_realizeManagementFee();
return super.deposit(assets_, receiver_);
}
function _addPerformanceFee(uint256 totalAssetsBefore_) internal {
uint256 totalAssetsAfter = totalAssets();
if (totalAssetsAfter < totalAssetsBefore_) {
return;
}
PlasmaVaultStorageLib.PerformanceFeeData memory feeData = PlasmaVaultLib.getPerformanceFeeData();
uint256 fee = Math.mulDiv(totalAssetsAfter - totalAssetsBefore_, feeData.feeInPercentage, 1e4);
/// @dev total supply cap validation is disabled for fee minting
PlasmaVaultLib.setTotalSupplyCapValidation(1);
_mint(feeData.feeAccount, convertToShares(fee));
/// @dev total supply cap validation is enabled when fee minting is finished
PlasmaVaultLib.setTotalSupplyCapValidation(0);
}
function _realizeManagementFee() internal {
PlasmaVaultStorageLib.ManagementFeeData memory feeData = PlasmaVaultLib.getManagementFeeData();
uint256 unrealizedFeeInUnderlying = getUnrealizedManagementFee();
PlasmaVaultLib.updateManagementFeeData();
uint256 unrealizedFeeInShares = convertToShares(unrealizedFeeInUnderlying);
if (unrealizedFeeInShares == 0) {
return;
}
/// @dev minting is an act of management fee realization
/// @dev total supply cap validation is disabled for fee minting
PlasmaVaultLib.setTotalSupplyCapValidation(1);
_mint(feeData.feeAccount, unrealizedFeeInShares);
/// @dev total supply cap validation is enabled when fee minting is finished
PlasmaVaultLib.setTotalSupplyCapValidation(0);
emit ManagementFeeRealized(unrealizedFeeInUnderlying, unrealizedFeeInShares);
}
function _includeSlippage(uint256 value_) internal pure returns (uint256) {
/// @dev increase value by DEFAULT_SLIPPAGE_IN_PERCENTAGE to cover potential slippage
return value_ + IporMath.division(value_ * DEFAULT_SLIPPAGE_IN_PERCENTAGE, 100);
}
/// @notice Withdraw assets from the markets
/// @param assets_ Amount of assets to withdraw
/// @param vaultCurrentBalanceUnderlying_ Current balance of the vault in underlying token
function _withdrawFromMarkets(uint256 assets_, uint256 vaultCurrentBalanceUnderlying_) internal {
if (assets_ == 0) {
return;
}
uint256 left;
if (assets_ >= vaultCurrentBalanceUnderlying_) {
uint256 marketIndex;
uint256 fuseMarketId;
bytes32[] memory params;
/// @dev assume that the same fuse can be used multiple times
/// @dev assume that more than one fuse can be from the same market
address[] memory fuses = PlasmaVaultLib.getInstantWithdrawalFuses();
uint256[] memory markets = new uint256[](fuses.length);
left = assets_ - vaultCurrentBalanceUnderlying_;
uint256 i;
uint256 balanceOf;
uint256 fusesLength = fuses.length;
for (i; left != 0 && i < fusesLength; ++i) {
params = PlasmaVaultLib.getInstantWithdrawalFusesParams(fuses[i], i);
/// @dev always first param is amount, by default is 0 in storage, set to left
params[0] = bytes32(left);
fuses[i].functionDelegateCall(abi.encodeWithSignature("instantWithdraw(bytes32[])", params));
balanceOf = IERC20(asset()).balanceOf(address(this));
if (assets_ > balanceOf) {
left = assets_ - balanceOf;
} else {
left = 0;
}
fuseMarketId = IFuseCommon(fuses[i]).MARKET_ID();
if (_checkIfExistsMarket(markets, fuseMarketId) == false) {
markets[marketIndex] = fuseMarketId;
marketIndex++;
}
}
_updateMarketsBalances(markets);
}
}
/// @notice Update balances in the vault for markets touched by the fuses during the execution of all FuseActions
/// @param markets_ Array of market ids touched by the fuses in the FuseActions
function _updateMarketsBalances(uint256[] memory markets_) internal {
uint256 wadBalanceAmountInUSD;
DataToCheck memory dataToCheck;
address balanceFuse;
int256 deltasInUnderlying;
uint256[] memory markets = _checkBalanceFusesDependencies(markets_);
uint256 marketsLength = markets.length;
/// @dev USD price is represented in 8 decimals
(uint256 underlyingAssetPrice, uint256 underlyingAssePriceDecimals) = IPriceOracleMiddleware(
PlasmaVaultLib.getPriceOracleMiddleware()
).getAssetPrice(asset());
dataToCheck.marketsToCheck = new MarketToCheck[](marketsLength);
for (uint256 i; i < marketsLength; ++i) {
if (markets[i] == 0) {
break;
}
balanceFuse = FusesLib.getBalanceFuse(markets[i]);
wadBalanceAmountInUSD = abi.decode(
balanceFuse.functionDelegateCall(abi.encodeWithSignature("balanceOf()")),
(uint256)
);
dataToCheck.marketsToCheck[i].marketId = markets[i];
dataToCheck.marketsToCheck[i].balanceInMarket = IporMath.convertWadToAssetDecimals(
IporMath.division(
wadBalanceAmountInUSD * IporMath.BASIS_OF_POWER ** underlyingAssePriceDecimals,
underlyingAssetPrice
),
(decimals() - _decimalsOffset())
);
deltasInUnderlying =
deltasInUnderlying +
PlasmaVaultLib.updateTotalAssetsInMarket(markets[i], dataToCheck.marketsToCheck[i].balanceInMarket);
}
if (deltasInUnderlying != 0) {
PlasmaVaultLib.addToTotalAssetsInAllMarkets(deltasInUnderlying);
}
dataToCheck.totalBalanceInVault = _getGrossTotalAssets();
AssetDistributionProtectionLib.checkLimits(dataToCheck);
emit MarketBalancesUpdated(markets, deltasInUnderlying);
}
function _checkBalanceFusesDependencies(uint256[] memory markets_) internal view returns (uint256[] memory) {
uint256 marketsLength = markets_.length;
if (marketsLength == 0) {
return markets_;
}
uint256[] memory marketsChecked = new uint256[](marketsLength * 2);
uint256[] memory marketsToCheck = markets_;
uint256 index;
uint256[] memory tempMarketsToCheck;
while (marketsToCheck.length > 0) {
tempMarketsToCheck = new uint256[](marketsLength * 2);
uint256 tempIndex;
for (uint256 i; i < marketsToCheck.length; ++i) {
if (!_checkIfExistsMarket(marketsChecked, marketsToCheck[i])) {
if (marketsChecked.length == index) {
marketsChecked = _increaseArray(marketsChecked, marketsChecked.length * 2);
}
marketsChecked[index] = marketsToCheck[i];
++index;
uint256 dependentMarketsLength = PlasmaVaultLib.getDependencyBalanceGraph(marketsToCheck[i]).length;
if (dependentMarketsLength > 0) {
for (uint256 j; j < dependentMarketsLength; ++j) {
if (tempMarketsToCheck.length == tempIndex) {
tempMarketsToCheck = _increaseArray(tempMarketsToCheck, tempMarketsToCheck.length * 2);
}
tempMarketsToCheck[tempIndex] = PlasmaVaultLib.getDependencyBalanceGraph(marketsToCheck[i])[
j
];
++tempIndex;
}
}
}
}
marketsToCheck = getUniqueElements(tempMarketsToCheck);
}
return getUniqueElements(marketsChecked);
}
function _increaseArray(uint256[] memory arr_, uint256 newSize_) internal pure returns (uint256[] memory) {
uint256[] memory result = new uint256[](newSize_);
for (uint256 i; i < arr_.length; ++i) {
result[i] = arr_[i];
}
return result;
}
function _concatArrays(
uint256[] memory arr1_,
uint256[] memory arr2_,
uint256 lengthOfNewArray_
) internal pure returns (uint256[] memory) {
uint256[] memory result = new uint256[](lengthOfNewArray_);
uint256 i;
uint256 lengthOfArr1 = arr1_.length;
for (i; i < lengthOfArr1; ++i) {
result[i] = arr1_[i];
}
for (uint256 j; i < lengthOfNewArray_; ++j) {
result[i] = arr2_[j];
++i;
}
return result;
}
function _checkIfExistsMarket(uint256[] memory markets_, uint256 marketId_) internal pure returns (bool exists) {
for (uint256 i; i < markets_.length; ++i) {
if (markets_[i] == 0) {
break;
}
if (markets_[i] == marketId_) {
exists = true;
break;
}
}
}
function _getGrossTotalAssets() internal view returns (uint256) {
address rewardsClaimManagerAddress = PlasmaVaultLib.getRewardsClaimManagerAddress();
if (rewardsClaimManagerAddress != address(0)) {
return
IERC20(asset()).balanceOf(address(this)) +
PlasmaVaultLib.getTotalAssetsInAllMarkets() +
IRewardsClaimManager(rewardsClaimManagerAddress).balanceOf();
}
return IERC20(asset()).balanceOf(address(this)) + PlasmaVaultLib.getTotalAssetsInAllMarkets();
}
function _getUnrealizedManagementFee(uint256 totalAssets_) internal view returns (uint256) {
PlasmaVaultStorageLib.ManagementFeeData memory feeData = PlasmaVaultLib.getManagementFeeData();
uint256 blockTimestamp = block.timestamp;
if (
feeData.feeInPercentage == 0 ||
feeData.lastUpdateTimestamp == 0 ||
blockTimestamp <= feeData.lastUpdateTimestamp
) {
return 0;
}
return
Math.mulDiv(
Math.mulDiv(totalAssets_, blockTimestamp - feeData.lastUpdateTimestamp, 365 days),
feeData.feeInPercentage,
1e4 /// @dev feeInPercentage is in percentage with 2 decimals, example 10000 is 100%
);
}
/**
* @dev Reverts if the caller is not allowed to call the function identified by a selector. Panics if the calldata
* is less than 4 bytes long.
*/
function _checkCanCall(address caller_, bytes calldata data_) internal virtual override {
bytes4 sig = bytes4(data_[0:4]);
bool immediate;
uint32 delay;
address withdrawManager = PlasmaVaultStorageLib.getWithdrawManager().manager;
if (withdrawManager != address(0) && this.withdraw.selector == sig) {
(immediate, delay) = IporFusionAccessManager(authority()).canCallAndUpdate(caller_, address(this), sig);
uint256 amount = _extractAmountFromWithdrawAndRedeem();
if (!WithdrawManager(withdrawManager).canWithdrawAndUpdate(caller_, amount)) {
revert WithdrawIsNotAllowed(caller_, amount);
}
} else if (withdrawManager != address(0) && this.redeem.selector == sig) {
(immediate, delay) = IporFusionAccessManager(authority()).canCallAndUpdate(caller_, address(this), sig);
uint256 amount = convertToAssets(_extractAmountFromWithdrawAndRedeem());
if (!WithdrawManager(withdrawManager).canWithdrawAndUpdate(caller_, amount)) {
revert WithdrawIsNotAllowed(caller_, amount);
}
} else if (
this.deposit.selector == sig ||
this.mint.selector == sig ||
this.depositWithPermit.selector == sig ||
this.redeem.selector == sig ||
this.withdraw.selector == sig
) {
(immediate, delay) = IporFusionAccessManager(authority()).canCallAndUpdate(caller_, address(this), sig);
} else {
(immediate, delay) = AuthorityUtils.canCallWithDelay(authority(), caller_, address(this), sig);
}
if (!immediate) {
if (delay > 0) {
AccessManagedStorage storage $ = _getAccessManagedStorage();
$._consumingSchedule = true;
IAccessManager(authority()).consumeScheduledOp(caller_, data_);
$._consumingSchedule = false;
} else {
revert AccessManagedUnauthorized(caller_);
}
}
}
function _extractAmountFromWithdrawAndRedeem() private returns (uint256) {
(uint256 amount, , ) = abi.decode(_msgData()[4:], (uint256, address, address));
return amount;
}
function _update(address from_, address to_, uint256 value_) internal virtual override {
PLASMA_VAULT_BASE.functionDelegateCall(
abi.encodeWithSelector(IPlasmaVaultBase.updateInternal.selector, from_, to_, value_)
);
}
function _decimalsOffset() internal view virtual override returns (uint8) {
return PlasmaVaultLib.DECIMALS_OFFSET;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {PlasmaVaultStorageLib} from "./PlasmaVaultStorageLib.sol";
/// @title Plasma Vault Configuration Library responsible for managing the configuration of the Plasma Vault
library PlasmaVaultConfigLib {
event MarketSubstratesGranted(uint256 marketId, bytes32[] substrates);
/// @notice Checks if the substrate treated as an asset is granted for the market
/// @param marketId_ The market id
/// @param substrateAsAsset The address of the substrate treated as an asset
/// @return true if the substrate is granted for the market
/// @dev Substrates are stored as bytes32
function isSubstrateAsAssetGranted(uint256 marketId_, address substrateAsAsset) internal view returns (bool) {
PlasmaVaultStorageLib.MarketSubstratesStruct storage marketSubstrates = _getMarketSubstrates(marketId_);
return marketSubstrates.substrateAllowances[addressToBytes32(substrateAsAsset)] == 1;
}
/// @notice Checks if the substrate is granted for the market
/// @param marketId_ The market id
/// @param substrate_ The bytes32 of the substrate
/// @return true if the substrate is granted for the market
/// @dev Substrates can be asset, vault, or any other params
function isMarketSubstrateGranted(uint256 marketId_, bytes32 substrate_) internal view returns (bool) {
PlasmaVaultStorageLib.MarketSubstratesStruct storage marketSubstrates = _getMarketSubstrates(marketId_);
return marketSubstrates.substrateAllowances[substrate_] == 1;
}
/// @notice Gets the market substrates for the market
/// @param marketId_ The market id
/// @return The array of substrates
function getMarketSubstrates(uint256 marketId_) internal view returns (bytes32[] memory) {
return _getMarketSubstrates(marketId_).substrates;
}
/// @notice Grants the substrates for the market
/// @param marketId_ The market id
/// @param substrates_ The array of substrates
/// @dev Substrates can be asset, vault, or any other params, only granted substrates can be used by Fuses in interaction with a given market and external protocols.
function grantMarketSubstrates(uint256 marketId_, bytes32[] memory substrates_) internal {
PlasmaVaultStorageLib.MarketSubstratesStruct storage marketSubstrates = _getMarketSubstrates(marketId_);
_revokeMarketSubstrates(marketSubstrates);
bytes32[] memory list = new bytes32[](substrates_.length);
for (uint256 i; i < substrates_.length; ++i) {
marketSubstrates.substrateAllowances[substrates_[i]] = 1;
list[i] = substrates_[i];
}
marketSubstrates.substrates = list;
emit MarketSubstratesGranted(marketId_, substrates_);
}
/// @notice Grants the substrates treated as assets for the market
/// @param marketId_ The market id
/// @param substratesAsAssets_ The array of substrates treated as assets
/// @dev Substrates are stored as bytes32, only granted substrates can be used by Fuses in interaction with a given market and external protocols.
function grantSubstratesAsAssetsToMarket(uint256 marketId_, address[] calldata substratesAsAssets_) internal {
PlasmaVaultStorageLib.MarketSubstratesStruct storage marketSubstrates = _getMarketSubstrates(marketId_);
_revokeMarketSubstrates(marketSubstrates);
bytes32[] memory list = new bytes32[](substratesAsAssets_.length);
for (uint256 i; i < substratesAsAssets_.length; ++i) {
marketSubstrates.substrateAllowances[addressToBytes32(substratesAsAssets_[i])] = 1;
list[i] = addressToBytes32(substratesAsAssets_[i]);
}
marketSubstrates.substrates = list;
emit MarketSubstratesGranted(marketId_, list);
}
function _revokeMarketSubstrates(PlasmaVaultStorageLib.MarketSubstratesStruct storage marketSubstrates) private {
uint256 length = marketSubstrates.substrates.length;
for (uint256 i; i < length; ++i) {
marketSubstrates.substrateAllowances[marketSubstrates.substrates[i]] = 0;
}
}
/// @notice Converts the substrate as bytes32 to value address
/// @param substrate_ The bytes32 of the substrate
/// @return The address of the substrate
function bytes32ToAddress(bytes32 substrate_) internal pure returns (address) {
return address(uint160(uint256(substrate_)));
}
/// @notice Converts the address to bytes32
/// @param address_ The address of the substrate
/// @return The bytes32 of the substrate
function addressToBytes32(address address_) internal pure returns (bytes32) {
return bytes32(uint256(uint160(address_)));
}
/// @notice Gets the market substrates configuration for a specific market
function _getMarketSubstrates(
uint256 marketId_
) private view returns (PlasmaVaultStorageLib.MarketSubstratesStruct storage) {
return PlasmaVaultStorageLib.getMarketSubstrates().value[marketId_];
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {FusesLib} from "../libraries/FusesLib.sol";
import {PlasmaVaultConfigLib} from "../libraries/PlasmaVaultConfigLib.sol";
import {PlasmaVaultLib, InstantWithdrawalFusesParamsStruct} from "../libraries/PlasmaVaultLib.sol";
import {IPriceOracleMiddleware} from "../price_oracle/IPriceOracleMiddleware.sol";
import {Errors} from "../libraries/errors/Errors.sol";
import {PlasmaVaultStorageLib} from "../libraries/PlasmaVaultStorageLib.sol";
import {AssetDistributionProtectionLib, MarketLimit} from "../libraries/AssetDistributionProtectionLib.sol";
import {AccessManagedUpgradeable} from "../managers/access/AccessManagedUpgradeable.sol";
import {CallbackHandlerLib} from "../libraries/CallbackHandlerLib.sol";
import {IPlasmaVaultGovernance} from "../interfaces/IPlasmaVaultGovernance.sol";
import {IIporFusionAccessManager} from "../interfaces/IIporFusionAccessManager.sol";
/// @title Plasma Vault Governance part of the Plasma Vault including Access Manager. Allows to manage the vault configuration like fuses, price oracle, fees, etc.
abstract contract PlasmaVaultGovernance is IPlasmaVaultGovernance, AccessManagedUpgradeable {
function isMarketSubstrateGranted(uint256 marketId_, bytes32 substrate_) external view override returns (bool) {
return PlasmaVaultConfigLib.isMarketSubstrateGranted(marketId_, substrate_);
}
function isFuseSupported(address fuse_) external view override returns (bool) {
return FusesLib.isFuseSupported(fuse_);
}
function isBalanceFuseSupported(uint256 marketId_, address fuse_) external view override returns (bool) {
return FusesLib.isBalanceFuseSupported(marketId_, fuse_);
}
function isMarketsLimitsActivated() public view override returns (bool) {
return AssetDistributionProtectionLib.isMarketsLimitsActivated();
}
function getMarketSubstrates(uint256 marketId_) external view override returns (bytes32[] memory) {
return PlasmaVaultConfigLib.getMarketSubstrates(marketId_);
}
function getFuses() external view override returns (address[] memory) {
return FusesLib.getFusesArray();
}
function getPriceOracleMiddleware() external view override returns (address) {
return PlasmaVaultLib.getPriceOracleMiddleware();
}
function getPerformanceFeeData()
external
view
override
returns (PlasmaVaultStorageLib.PerformanceFeeData memory feeData)
{
feeData = PlasmaVaultLib.getPerformanceFeeData();
}
function getManagementFeeData()
external
view
override
returns (PlasmaVaultStorageLib.ManagementFeeData memory feeData)
{
feeData = PlasmaVaultLib.getManagementFeeData();
}
function getAccessManagerAddress() external view override returns (address) {
return authority();
}
function getRewardsClaimManagerAddress() external view override returns (address) {
return PlasmaVaultLib.getRewardsClaimManagerAddress();
}
function getInstantWithdrawalFuses() external view override returns (address[] memory) {
return PlasmaVaultLib.getInstantWithdrawalFuses();
}
function getInstantWithdrawalFusesParams(
address fuse_,
uint256 index_
) external view override returns (bytes32[] memory) {
return PlasmaVaultLib.getInstantWithdrawalFusesParams(fuse_, index_);
}
function getMarketLimit(uint256 marketId_) external view override returns (uint256) {
return PlasmaVaultStorageLib.getMarketsLimits().limitInPercentage[marketId_];
}
function getDependencyBalanceGraph(uint256 marketId_) external view override returns (uint256[] memory) {
return PlasmaVaultStorageLib.getDependencyBalanceGraph().dependencyGraph[marketId_];
}
function getTotalSupplyCap() external view override returns (uint256) {
return PlasmaVaultLib.getTotalSupplyCap();
}
function addBalanceFuse(uint256 marketId_, address fuse_) external override restricted {
_addBalanceFuse(marketId_, fuse_);
}
function removeBalanceFuse(uint256 marketId_, address fuse_) external override restricted {
FusesLib.removeBalanceFuse(marketId_, fuse_);
}
function grantMarketSubstrates(uint256 marketId_, bytes32[] calldata substrates_) external override restricted {
PlasmaVaultConfigLib.grantMarketSubstrates(marketId_, substrates_);
}
function updateDependencyBalanceGraphs(
uint256[] memory marketIds_,
uint256[][] memory dependencies_
) external override restricted {
uint256 marketIdsLength = marketIds_.length;
if (marketIdsLength != dependencies_.length) {
revert Errors.WrongArrayLength();
}
for (uint256 i; i < marketIdsLength; ++i) {
PlasmaVaultStorageLib.getDependencyBalanceGraph().dependencyGraph[marketIds_[i]] = dependencies_[i];
}
}
/// @notice Configures the instant withdrawal fuses. Order of the fuse is important, as it will be used in the same order during the instant withdrawal process
/// @dev Order of the fuses is important, the same fuse can be used multiple times with different parameters (for example different assets, markets or any other substrate specific for the fuse)
function configureInstantWithdrawalFuses(
InstantWithdrawalFusesParamsStruct[] calldata fuses_
) external override restricted {
PlasmaVaultLib.configureInstantWithdrawalFuses(fuses_);
}
function addFuses(address[] calldata fuses_) external override restricted {
for (uint256 i; i < fuses_.length; ++i) {
FusesLib.addFuse(fuses_[i]);
}
}
function removeFuses(address[] calldata fuses_) external override restricted {
for (uint256 i; i < fuses_.length; ++i) {
FusesLib.removeFuse(fuses_[i]);
}
}
function setPriceOracleMiddleware(address priceOracleMiddleware_) external override restricted {
IPriceOracleMiddleware oldPriceOracleMiddleware = IPriceOracleMiddleware(
PlasmaVaultLib.getPriceOracleMiddleware()
);
IPriceOracleMiddleware newPriceOracleMiddleware = IPriceOracleMiddleware(priceOracleMiddleware_);
if (
oldPriceOracleMiddleware.QUOTE_CURRENCY() != newPriceOracleMiddleware.QUOTE_CURRENCY() ||
oldPriceOracleMiddleware.QUOTE_CURRENCY_DECIMALS() != newPriceOracleMiddleware.QUOTE_CURRENCY_DECIMALS()
) {
revert Errors.UnsupportedPriceOracleMiddleware();
}
PlasmaVaultLib.setPriceOracleMiddleware(priceOracleMiddleware_);
}
function configurePerformanceFee(address feeAccount_, uint256 feeInPercentage_) external override restricted {
PlasmaVaultLib.configurePerformanceFee(feeAccount_, feeInPercentage_);
}
function configureManagementFee(address feeAccount_, uint256 feeInPercentage_) external override restricted {
PlasmaVaultLib.configureManagementFee(feeAccount_, feeInPercentage_);
}
function setRewardsClaimManagerAddress(address rewardsClaimManagerAddress_) public override restricted {
PlasmaVaultLib.setRewardsClaimManagerAddress(rewardsClaimManagerAddress_);
}
function setupMarketsLimits(MarketLimit[] calldata marketsLimits_) external override restricted {
AssetDistributionProtectionLib.setupMarketsLimits(marketsLimits_);
}
/// @notice Activates the markets limits protection, by default it is deactivated. After activation the limits
/// is setup for each market separately.
function activateMarketsLimits() public override restricted {
AssetDistributionProtectionLib.activateMarketsLimits();
}
/// @notice Deactivates the markets limits protection.
function deactivateMarketsLimits() public override restricted {
AssetDistributionProtectionLib.deactivateMarketsLimits();
}
function updateCallbackHandler(address handler_, address sender_, bytes4 sig_) external override restricted {
CallbackHandlerLib.updateCallbackHandler(handler_, sender_, sig_);
}
function setTotalSupplyCap(uint256 cap_) external override restricted {
PlasmaVaultLib.setTotalSupplyCap(cap_);
}
function convertToPublicVault() external override restricted {
IIporFusionAccessManager(authority()).convertToPublicVault(address(this));
}
function enableTransferShares() external override restricted {
IIporFusionAccessManager(authority()).enableTransferShares(address(this));
}
function setMinimalExecutionDelaysForRoles(
uint64[] calldata rolesIds_,
uint256[] calldata delays_
) external override restricted {
IIporFusionAccessManager(authority()).setMinimalExecutionDelaysForRoles(rolesIds_, delays_);
}
function _addFuse(address fuse_) internal {
if (fuse_ == address(0)) {
revert Errors.WrongAddress();
}
FusesLib.addFuse(fuse_);
}
function _addBalanceFuse(uint256 marketId_, address fuse_) internal {
if (fuse_ == address(0)) {
revert Errors.WrongAddress();
}
FusesLib.addBalanceFuse(marketId_, fuse_);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {Errors} from "./errors/Errors.sol";
import {PlasmaVaultStorageLib} from "./PlasmaVaultStorageLib.sol";
import {FusesLib} from "./FusesLib.sol";
/// @notice Technical struct used to pass parameters in the `updateInstantWithdrawalFuses` function
struct InstantWithdrawalFusesParamsStruct {
/// @notice The address of the fuse
address fuse;
/// @notice The parameters of the fuse, first element is an amount, second element is an address of the asset or a market id or other substrate specific for the fuse
/// @dev Notice! Always first param is the asset value in underlying, next params are specific for the Fuse
bytes32[] params;
}
/// @title Plasma Vault Library responsible for managing the Plasma Vault
library PlasmaVaultLib {
using SafeCast for uint256;
using SafeCast for int256;
/// @dev Hard CAP for the performance fee in percentage - 50%
uint256 public constant PERFORMANCE_MAX_FEE_IN_PERCENTAGE = 5000;
/// @dev Hard CAP for the management fee in percentage - 5%
uint256 public constant MANAGEMENT_MAX_FEE_IN_PERCENTAGE = 500;
/// @dev The offset for the underlying asset decimals in the Plasma Vault
uint8 public constant DECIMALS_OFFSET = 2;
error InvalidPerformanceFee(uint256 feeInPercentage);
error InvalidManagementFee(uint256 feeInPercentage);
event InstantWithdrawalFusesConfigured(InstantWithdrawalFusesParamsStruct[] fuses);
event PriceOracleMiddlewareChanged(address newPriceOracleMiddleware);
event PerformanceFeeDataConfigured(address feeAccount, uint256 feeInPercentage);
event ManagementFeeDataConfigured(address feeAccount, uint256 feeInPercentage);
event RewardsClaimManagerAddressChanged(address newRewardsClaimManagerAddress);
event DependencyBalanceGraphChanged(uint256 marketId, uint256[] newDependenceGraph);
event WithdrawManagerChanged(address newWithdrawManager);
/// @notice Gets the total assets in the vault for all markets
/// @return The total assets in the vault for all markets, represented in decimals of the underlying asset
//solhint-disable-next-line
function getTotalAssetsInAllMarkets() internal view returns (uint256) {
return PlasmaVaultStorageLib.getTotalAssets().value;
}
/// @notice Gets the total assets in the vault for a specific market
/// @param marketId_ The market id
/// @return The total assets in the vault for the market, represented in decimals of the underlying asset
//solhint-disable-next-line
function getTotalAssetsInMarket(uint256 marketId_) internal view returns (uint256) {
return PlasmaVaultStorageLib.getMarketTotalAssets().value[marketId_];
}
/// @notice Gets the dependency balance graph for a specific market
/// @param marketId_ The market id
/// @return The dependency balance graph for the market
/// @dev The dependency balance graph is used to update appropriate balance markets when Plasma Vault interact with a given marketId_
function getDependencyBalanceGraph(uint256 marketId_) internal view returns (uint256[] memory) {
return PlasmaVaultStorageLib.getDependencyBalanceGraph().dependencyGraph[marketId_];
}
/// @notice Updates the dependency balance graph for a specific market
/// @param marketId_ The market id
/// @param newDependenceGraph_ The new dependency balance graph for the market
function updateDependencyBalanceGraph(uint256 marketId_, uint256[] memory newDependenceGraph_) internal {
PlasmaVaultStorageLib.getDependencyBalanceGraph().dependencyGraph[marketId_] = newDependenceGraph_;
emit DependencyBalanceGraphChanged(marketId_, newDependenceGraph_);
}
/// @notice Adds an amount to the total assets in the Plasma Vault for all markets
/// @param amount_ The amount to add, represented in decimals of the underlying asset
function addToTotalAssetsInAllMarkets(int256 amount_) internal {
if (amount_ < 0) {
PlasmaVaultStorageLib.getTotalAssets().value -= (-amount_).toUint256();
} else {
PlasmaVaultStorageLib.getTotalAssets().value += amount_.toUint256();
}
}
/// @notice Updates the total assets in the Plasma Vault for a specific market
/// @param marketId_ The market id
/// @param newTotalAssetsInUnderlying_ The new total assets in the vault for the market, represented in decimals of the underlying asset
/// @return deltaInUnderlying The difference between the old and the new total assets in the vault for the market
function updateTotalAssetsInMarket(
uint256 marketId_,
uint256 newTotalAssetsInUnderlying_
) internal returns (int256 deltaInUnderlying) {
uint256 oldTotalAssetsInUnderlying = PlasmaVaultStorageLib.getMarketTotalAssets().value[marketId_];
PlasmaVaultStorageLib.getMarketTotalAssets().value[marketId_] = newTotalAssetsInUnderlying_;
deltaInUnderlying = newTotalAssetsInUnderlying_.toInt256() - oldTotalAssetsInUnderlying.toInt256();
}
/// @notice Gets the management fee data
/// @return managementFeeData The management fee data, like the fee manager and the fee in percentage
//solhint-disable-next-line
function getManagementFeeData()
internal
view
returns (PlasmaVaultStorageLib.ManagementFeeData memory managementFeeData)
{
return PlasmaVaultStorageLib.getManagementFeeData();
}
/// @notice Configures the management fee data like the fee manager and the fee in percentage
/// @param feeAccount_ The address of the fee manager responsible for managing the management fee
/// @param feeInPercentage_ The fee in percentage, represented in 2 decimals, example: 100% = 10000, 1% = 100, 0.01% = 1
function configureManagementFee(address feeAccount_, uint256 feeInPercentage_) internal {
if (feeAccount_ == address(0)) {
revert Errors.WrongAddress();
}
if (feeInPercentage_ > MANAGEMENT_MAX_FEE_IN_PERCENTAGE) {
revert InvalidManagementFee(feeInPercentage_);
}
PlasmaVaultStorageLib.ManagementFeeData storage managementFeeData = PlasmaVaultStorageLib
.getManagementFeeData();
managementFeeData.feeAccount = feeAccount_;
managementFeeData.feeInPercentage = feeInPercentage_.toUint16();
emit ManagementFeeDataConfigured(feeAccount_, feeInPercentage_);
}
/// @notice Gets the performance fee data
/// @return performanceFeeData The performance fee data, like the fee manager and the fee in percentage
//solhint-disable-next-line
function getPerformanceFeeData()
internal
view
returns (PlasmaVaultStorageLib.PerformanceFeeData memory performanceFeeData)
{
return PlasmaVaultStorageLib.getPerformanceFeeData();
}
/// @notice Configures the performance fee data like the fee manager and the fee in percentage
/// @param feeAccount_ The address of the fee manager responsible for managing the performance fee
/// @param feeInPercentage_ The fee in percentage, represented in 2 decimals, example: 100% = 10000, 1% = 100, 0.01% = 1
function configurePerformanceFee(address feeAccount_, uint256 feeInPercentage_) internal {
if (feeAccount_ == address(0)) {
revert Errors.WrongAddress();
}
if (feeInPercentage_ > PERFORMANCE_MAX_FEE_IN_PERCENTAGE) {
revert InvalidPerformanceFee(feeInPercentage_);
}
PlasmaVaultStorageLib.PerformanceFeeData storage performanceFeeData = PlasmaVaultStorageLib
.getPerformanceFeeData();
performanceFeeData.feeAccount = feeAccount_;
performanceFeeData.feeInPercentage = feeInPercentage_.toUint16();
emit PerformanceFeeDataConfigured(feeAccount_, feeInPercentage_);
}
/// @notice Updates the management fee data with the current timestamp
/// @dev lastUpdateTimestamp is used to calculate unrealized management fees
function updateManagementFeeData() internal {
PlasmaVaultStorageLib.ManagementFeeData storage feeData = PlasmaVaultStorageLib.getManagementFeeData();
feeData.lastUpdateTimestamp = block.timestamp.toUint32();
}
/// @notice Gets instant withdrawal fuses
/// @return The instant withdrawal fuses, the order of the fuses is important
function getInstantWithdrawalFuses() internal view returns (address[] memory) {
return PlasmaVaultStorageLib.getInstantWithdrawalFusesArray().value;
}
/// @notice Gets the instant withdrawal fuses parameters for a specific fuse
/// @param fuse_ The fuse address
/// @param index_ The index of the Fuse in the fuses array
/// @return The instant withdrawal fuses parameters
function getInstantWithdrawalFusesParams(address fuse_, uint256 index_) internal view returns (bytes32[] memory) {
return
PlasmaVaultStorageLib.getInstantWithdrawalFusesParams().value[keccak256(abi.encodePacked(fuse_, index_))];
}
/// @notice Configures order of the instant withdrawal fuses. Order of the fuse is important, as it will be used in the same order during the instant withdrawal process
/// @param fuses_ The fuses to configure
/// @dev Order of the fuses is important, the same fuse can be used multiple times with different parameters (for example different assets, markets or any other substrate specific for the fuse)
function configureInstantWithdrawalFuses(InstantWithdrawalFusesParamsStruct[] calldata fuses_) internal {
address[] memory fusesList = new address[](fuses_.length);
PlasmaVaultStorageLib.InstantWithdrawalFusesParams storage instantWithdrawalFusesParams = PlasmaVaultStorageLib
.getInstantWithdrawalFusesParams();
bytes32 key;
for (uint256 i; i < fuses_.length; ++i) {
if (!FusesLib.isFuseSupported(fuses_[i].fuse)) {
revert FusesLib.FuseUnsupported(fuses_[i].fuse);
}
fusesList[i] = fuses_[i].fuse;
key = keccak256(abi.encodePacked(fuses_[i].fuse, i));
delete instantWithdrawalFusesParams.value[key];
for (uint256 j; j < fuses_[i].params.length; ++j) {
instantWithdrawalFusesParams.value[key].push(fuses_[i].params[j]);
}
}
delete PlasmaVaultStorageLib.getInstantWithdrawalFusesArray().value;
PlasmaVaultStorageLib.getInstantWithdrawalFusesArray().value = fusesList;
emit InstantWithdrawalFusesConfigured(fuses_);
}
/// @notice Gets the Price Oracle Middleware address
/// @return The Price Oracle Middleware address
function getPriceOracleMiddleware() internal view returns (address) {
return PlasmaVaultStorageLib.getPriceOracleMiddleware().value;
}
/// @notice Sets the Price Oracle Middleware address
/// @param priceOracleMiddleware_ The Price Oracle Middleware address
function setPriceOracleMiddleware(address priceOracleMiddleware_) internal {
PlasmaVaultStorageLib.getPriceOracleMiddleware().value = priceOracleMiddleware_;
emit PriceOracleMiddlewareChanged(priceOracleMiddleware_);
}
/// @notice Gets the Rewards Claim Manager address
/// @return The Rewards Claim Manager address
function getRewardsClaimManagerAddress() internal view returns (address) {
return PlasmaVaultStorageLib.getRewardsClaimManagerAddress().value;
}
/// @notice Sets the Rewards Claim Manager address
/// @param rewardsClaimManagerAddress_ The rewards claim manager address
function setRewardsClaimManagerAddress(address rewardsClaimManagerAddress_) internal {
PlasmaVaultStorageLib.getRewardsClaimManagerAddress().value = rewardsClaimManagerAddress_;
emit RewardsClaimManagerAddressChanged(rewardsClaimManagerAddress_);
}
/// @notice Gets the total supply cap
/// @return The total supply cap, represented in decimals of the underlying asset
function getTotalSupplyCap() internal view returns (uint256) {
return PlasmaVaultStorageLib.getERC20CappedStorage().cap;
}
/// @notice Sets the total supply cap
/// @param cap_ The total supply cap, represented in decimals of the underlying asset
function setTotalSupplyCap(uint256 cap_) internal {
if (cap_ == 0) {
revert Errors.WrongValue();
}
PlasmaVaultStorageLib.getERC20CappedStorage().cap = cap_;
}
/// @notice Sets the total supply cap validation
/// @param flag_ The total supply cap validation flag
/// @dev 1 - no validation, 0 - validation, total supply validation cap is disabled when performance fee or management fee is minted.
/// By default, the total supply cap validation is enabled (flag_ = 0)
function setTotalSupplyCapValidation(uint256 flag_) internal {
PlasmaVaultStorageLib.getERC20CappedValidationFlag().value = flag_;
}
/// @notice Checks if the total supply cap validation is enabled
/// @return true if the total supply cap validation is enabled, false otherwise
function isTotalSupplyCapValidationEnabled() internal view returns (bool) {
return PlasmaVaultStorageLib.getERC20CappedValidationFlag().value == 0;
}
/// @notice Sets the execution state to started, used in the execute function called by Alpha
/// @dev Alpha can do interaction with the Plasma Vault using more than one FuseAction
function executeStarted() internal {
PlasmaVaultStorageLib.getExecutionState().value = 1;
}
/// @notice Sets the execution state to finished, used in the execute function called by Alpha
/// @dev Alpha can do interaction with the Plasma Vault using more than one FuseAction
function executeFinished() internal {
PlasmaVaultStorageLib.getExecutionState().value = 0;
}
/// @notice Checks if the execution is started
/// @return true if the execution is started
function isExecutionStarted() internal view returns (bool) {
return PlasmaVaultStorageLib.getExecutionState().value == 1;
}
/// @notice Updates the Withdraw Manager address. If the address is zero, it means that scheduled withdrawals are turned off.
function updateWithdrawManager(address newWithdrawManager_) internal {
PlasmaVaultStorageLib.getWithdrawManager().manager = newWithdrawManager_;
emit WithdrawManagerChanged(newWithdrawManager_);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
/// @title Library responsible for managing access to the storage of the PlasmaVault contract using the ERC-7201 standard
library PlasmaVaultStorageLib {
/// @dev value taken from ERC4626 contract, don't change it!
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC4626")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ERC4626_STORAGE_LOCATION =
0x0773e532dfede91f04b12a73d3d2acd361424f41f76b4fb79f090161e36b4e00;
/// @dev value taken from ERC20CappedUpgradeable contract, don't change it!
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20Capped")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ERC20_CAPPED_STORAGE_LOCATION =
0x0f070392f17d5f958cc1ac31867dabecfc5c9758b4a419a200803226d7155d00;
/// @dev storage pointer location for a flag which indicates if the Total Supply Cap validation is enabled
// keccak256(abi.encode(uint256(keccak256("io.ipor.Erc20CappedValidationFlag")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ERC20_CAPPED_VALIDATION_FLAG =
0xaef487a7a52e82ae7bbc470b42be72a1d3c066fb83773bf99cce7e6a7df2f900;
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.PlasmaVaultTotalAssetsInAllMarkets")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant PLASMA_VAULT_TOTAL_ASSETS_IN_ALL_MARKETS =
0x24e02552e88772b8e8fd15f3e6699ba530635ffc6b52322da922b0b497a77300;
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.PlasmaVaultTotalAssetsInMarket")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant PLASMA_VAULT_TOTAL_ASSETS_IN_MARKET =
0x656f5ca8c676f20b936e991a840e1130bdd664385322f33b6642ec86729ee600;
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.CfgPlasmaVaultMarketSubstrates")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant CFG_PLASMA_VAULT_MARKET_SUBSTRATES =
0x78e40624004925a4ef6749756748b1deddc674477302d5b7fe18e5335cde3900;
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.CfgPlasmaVaultBalanceFuses")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant CFG_PLASMA_VAULT_BALANCE_FUSES =
0x150144dd6af711bac4392499881ec6649090601bd196a5ece5174c1400b1f700;
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.CfgPlasmaVaultInstantWithdrawalFusesArray")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant CFG_PLASMA_VAULT_INSTANT_WITHDRAWAL_FUSES_ARRAY =
0xd243afa3da07e6bdec20fdd573a17f99411aa8a62ae64ca2c426d3a86ae0ac00;
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.PriceOracleMiddleware")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant PRICE_ORACLE_MIDDLEWARE =
0x0d761ae54d86fc3be4f1f2b44ade677efb1c84a85fc6bb1d087dc42f1e319a00;
/// @notice Every fuse has a list of parameters used for instant withdrawal
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.CfgPlasmaVaultInstantWithdrawalFusesParams")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant CFG_PLASMA_VAULT_INSTANT_WITHDRAWAL_FUSES_PARAMS =
0x45a704819a9dcb1bb5b8cff129eda642cf0e926a9ef104e27aa53f1d1fa47b00;
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.CfgPlasmaVaultFeeConfig")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant CFG_PLASMA_VAULT_FEE_CONFIG =
0x78b5ce597bdb64d5aa30a201c7580beefe408ff13963b5d5f3dce2dc09e89c00;
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.PlasmaVaultPerformanceFeeData")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant PLASMA_VAULT_PERFORMANCE_FEE_DATA =
0x9399757a27831a6cfb6cf4cd5c97a908a2f8f41e95a5952fbf83a04e05288400;
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.PlasmaVaultManagementFeeData")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant PLASMA_VAULT_MANAGEMENT_FEE_DATA =
0x239dd7e43331d2af55e2a25a6908f3bcec2957025f1459db97dcdc37c0003f00;
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.RewardsClaimManagerAddress")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant REWARDS_CLAIM_MANAGER_ADDRESS =
0x08c469289c3f85d9b575f3ae9be6831541ff770a06ea135aa343a4de7c962d00;
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.MarketLimits")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant MARKET_LIMITS = 0xc2733c187287f795e2e6e84d35552a190e774125367241c3e99e955f4babf000;
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.DependencyBalanceGraph")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant DEPENDENCY_BALANCE_GRAPH =
0x82411e549329f2815579116a6c5e60bff72686c93ab5dba4d06242cfaf968900;
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.executeRunning")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant EXECUTE_RUNNING = 0x054644eb87255c1c6a2d10801735f52fa3b9d6e4477dbed74914d03844ab6600;
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.callbackHandler")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant CALLBACK_HANDLER = 0xb37e8684757599da669b8aea811ee2b3693b2582d2c730fab3f4965fa2ec3e00;
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.WithdrawManager")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant WITHDRAW_MANAGER = 0xb37e8684757599da669b8aea811ee2b3693b2582d2c730fab3f4965fa2ec3e11;
/// @dev Value taken from ERC20VotesUpgradeable contract, don't change it!
/// @custom:storage-location erc7201:openzeppelin.storage.ERC4626
struct ERC4626Storage {
/// @dev underlying asset in Plasma Vault
address asset;
/// @dev underlying asset decimals in Plasma Vault
uint8 underlyingDecimals;
}
/// @dev Value taken from ERC20VotesUpgradeable contract, don't change it!
/// @custom:storage-location erc7201:openzeppelin.storage.ERC20Capped
struct ERC20CappedStorage {
uint256 cap;
}
/// @notice ERC20CappedValidationFlag is used to enable or disable the total supply cap validation during execution
/// Required for situation when performance fee or management fee is minted for fee managers
/// @custom:storage-location erc7201:io.ipor.Erc20CappedValidationFlag
struct ERC20CappedValidationFlag {
uint256 value;
}
/// @custom:storage-location erc7201:io.ipor.RewardsClaimManagerAddress
struct RewardsClaimManagerAddress {
/// @dev total assets in the Plasma Vault
address value;
}
/// @custom:storage-location erc7201:io.ipor.PlasmaVaultTotalAssetsInAllMarkets
struct TotalAssets {
/// @dev total assets in the Plasma Vault
uint256 value;
}
/// @custom:storage-location erc7201:io.ipor.PlasmaVaultTotalAssetsInMarket
struct MarketTotalAssets {
/// @dev marketId => total assets in the vault in the market
mapping(uint256 => uint256) value;
}
/// @notice Market Substrates configuration
/// @dev Substrate - abstract item in the market, could be asset or sub market in the external protocol, it could be any item required to calculate balance in the market
struct MarketSubstratesStruct {
/// @notice Define which substrates are allowed and supported in the market
/// @dev key can be specific asset or sub market in a specific external protocol (market), value - 1 - granted, otherwise - not granted
mapping(bytes32 => uint256) substrateAllowances;
/// @dev it could be list of assets or sub markets in a specific protocol or any other ids required to calculate balance in the market (external protocol)
bytes32[] substrates;
}
/// @custom:storage-location erc7201:io.ipor.CfgPlasmaVaultMarketSubstrates
struct MarketSubstrates {
/// @dev marketId => MarketSubstratesStruct
mapping(uint256 => MarketSubstratesStruct) value;
}
/// @custom:storage-location erc7201:io.ipor.CfgPlasmaVaultBalanceFuses
struct BalanceFuses {
/// @dev marketId => balance fuse address
mapping(uint256 => address) value;
}
/// @custom:storage-location erc7201:io.ipor.BalanceDependenceGraph
struct DependencyBalanceGraph {
mapping(uint256 marketId => uint256[] marketIds) dependencyGraph;
}
/// @custom:storage-location erc7201:io.ipor.callbackHandler
struct CallbackHandler {
/// @dev key: keccak256(abi.encodePacked(sender, sig)), value: handler address
mapping(bytes32 key => address handler) callbackHandler;
}
/// @custom:storage-location erc7201:io.ipor.CfgPlasmaVaultInstantWithdrawalFusesArray
struct InstantWithdrawalFuses {
/// @dev value is a Fuse address used for instant withdrawal
address[] value;
}
/// @custom:storage-location erc7201:io.ipor.CfgPlasmaVaultInstantWithdrawalFusesParams
struct InstantWithdrawalFusesParams {
/// @dev key: fuse address and index in InstantWithdrawalFuses array, value: list of parameters used for instant withdrawal
/// @dev first param always amount in underlying asset of PlasmaVault, second and next params are specific for the fuse and market
mapping(bytes32 => bytes32[]) value;
}
/// @custom:storage-location erc7201:io.ipor.PlasmaVaultPerformanceFeeData
struct PerformanceFeeData {
address feeAccount;
uint16 feeInPercentage;
}
/// @custom:storage-location erc7201:io.ipor.PlasmaVaultManagementFeeData
struct ManagementFeeData {
address feeAccount;
uint16 feeInPercentage;
uint32 lastUpdateTimestamp;
}
/// @custom:storage-location erc7201:io.ipor.PriceOracleMiddleware
struct PriceOracleMiddleware {
address value;
}
/// @custom:storage-location erc7201:io.ipor.executeRunning
struct ExecuteState {
uint256 value;
}
/// @custom:storage-location erc7201:io.ipor.WithdrawManager
struct WithdrawManager {
address manager;
}
/// @dev limit is percentage of total assets in the market in 18 decimals, 1e18 is 100%
/// @deb if limit for zero marketId is greater than 0, then limits are activated
/// @custom:storage-location erc7201:io.ipor.MarketLimits
struct MarketLimits {
mapping(uint256 marketId => uint256 limit) limitInPercentage;
}
function getERC4626Storage() internal pure returns (ERC4626Storage storage $) {
assembly {
$.slot := ERC4626_STORAGE_LOCATION
}
}
function getERC20CappedStorage() internal pure returns (ERC20CappedStorage storage $) {
assembly {
$.slot := ERC20_CAPPED_STORAGE_LOCATION
}
}
function getERC20CappedValidationFlag() internal pure returns (ERC20CappedValidationFlag storage $) {
assembly {
$.slot := ERC20_CAPPED_VALIDATION_FLAG
}
}
/// @notice Gets the total assets storage pointer
/// @return totalAssets storage pointer
function getTotalAssets() internal pure returns (TotalAssets storage totalAssets) {
assembly {
totalAssets.slot := PLASMA_VAULT_TOTAL_ASSETS_IN_ALL_MARKETS
}
}
/// @notice Gets execution state storage pointer
/// @return executeRunning storage pointer
function getExecutionState() internal pure returns (ExecuteState storage executeRunning) {
assembly {
executeRunning.slot := EXECUTE_RUNNING
}
}
/// @notice Gets the callback handler storage pointer
/// @return handler storage pointer
function getCallbackHandler() internal pure returns (CallbackHandler storage handler) {
assembly {
handler.slot := CALLBACK_HANDLER
}
}
/// @notice Gets the dependency balance graph storage pointer
/// @return dependencyBalanceGraph storage pointer
function getDependencyBalanceGraph() internal pure returns (DependencyBalanceGraph storage dependencyBalanceGraph) {
assembly {
dependencyBalanceGraph.slot := DEPENDENCY_BALANCE_GRAPH
}
}
/// @notice Gets the market total assets storage pointer
/// @return marketTotalAssets storage pointer
function getMarketTotalAssets() internal pure returns (MarketTotalAssets storage marketTotalAssets) {
assembly {
marketTotalAssets.slot := PLASMA_VAULT_TOTAL_ASSETS_IN_MARKET
}
}
/// @notice Gets the market substrates storage pointer
/// @return marketSubstrates storage pointer
function getMarketSubstrates() internal pure returns (MarketSubstrates storage marketSubstrates) {
assembly {
marketSubstrates.slot := CFG_PLASMA_VAULT_MARKET_SUBSTRATES
}
}
/// @notice Gets the balance fuses storage pointer
/// @return balanceFuses storage pointer
function getBalanceFuses() internal pure returns (BalanceFuses storage balanceFuses) {
assembly {
balanceFuses.slot := CFG_PLASMA_VAULT_BALANCE_FUSES
}
}
/// @notice Gets the instant withdrawal fuses storage pointer
/// @return instantWithdrawalFuses storage pointer
function getInstantWithdrawalFusesArray()
internal
pure
returns (InstantWithdrawalFuses storage instantWithdrawalFuses)
{
assembly {
instantWithdrawalFuses.slot := CFG_PLASMA_VAULT_INSTANT_WITHDRAWAL_FUSES_ARRAY
}
}
/// @notice Gets the instant withdrawal fuses params storage pointer
/// @return instantWithdrawalFusesParams storage pointer
function getInstantWithdrawalFusesParams()
internal
pure
returns (InstantWithdrawalFusesParams storage instantWithdrawalFusesParams)
{
assembly {
instantWithdrawalFusesParams.slot := CFG_PLASMA_VAULT_INSTANT_WITHDRAWAL_FUSES_PARAMS
}
}
/// @notice Gets the PriceOracleMiddleware storage pointer
/// @return oracle storage pointer
function getPriceOracleMiddleware() internal pure returns (PriceOracleMiddleware storage oracle) {
assembly {
oracle.slot := PRICE_ORACLE_MIDDLEWARE
}
}
/// @notice Gets performance fee config storage pointer
/// @return performanceFeeData storage pointer
function getPerformanceFeeData() internal pure returns (PerformanceFeeData storage performanceFeeData) {
assembly {
performanceFeeData.slot := PLASMA_VAULT_PERFORMANCE_FEE_DATA
}
}
/// @notice Gets management fee config storage pointer
/// @return managementFeeData storage pointer
function getManagementFeeData() internal pure returns (ManagementFeeData storage managementFeeData) {
assembly {
managementFeeData.slot := PLASMA_VAULT_MANAGEMENT_FEE_DATA
}
}
/// @notice Gets the Rewards Claim Manager address storage pointer
/// @return rewardsClaimManagerAddress storage pointer
function getRewardsClaimManagerAddress()
internal
pure
returns (RewardsClaimManagerAddress storage rewardsClaimManagerAddress)
{
assembly {
rewardsClaimManagerAddress.slot := REWARDS_CLAIM_MANAGER_ADDRESS
}
}
/// @notice Gets the MarketLimits storage pointer
/// @return marketLimits storage pointer
function getMarketsLimits() internal pure returns (MarketLimits storage marketLimits) {
assembly {
marketLimits.slot := MARKET_LIMITS
}
}
/// @notice Gets the WithdrawManager storage pointer
/// @return withdrawManager storage pointer
function getWithdrawManager() internal pure returns (WithdrawManager storage withdrawManager) {
assembly {
withdrawManager.slot := WITHDRAW_MANAGER
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {PlasmaVault} from "../../vaults/PlasmaVault.sol";
import {IporFusionAccessManagersStorageLib} from "./IporFusionAccessManagersStorageLib.sol";
bytes4 constant DEPOSIT_SELECTOR = PlasmaVault.deposit.selector;
bytes4 constant DEPOSIT_WITH_PERMIT_SELECTOR = PlasmaVault.depositWithPermit.selector;
bytes4 constant MINT_SELECTOR = PlasmaVault.mint.selector;
bytes4 constant WITHDRAW_SELECTOR = PlasmaVault.withdraw.selector;
bytes4 constant REDEEM_SELECTOR = PlasmaVault.redeem.selector;
/// @title Library for the redemption delay responsible for locking accounts for withdraw and redeem functions after deposit or mint functions.
library RedemptionDelayLib {
error AccountIsLocked(uint256 unlockTime);
/// @notice Get the account lock time for a redemption function (withdraw, redeem)
/// @param account_ The account to check the lock time
/// @return The lock time in seconds
/// @dev The lock time is the time the account is locked for withdraw and redeem functions after deposit or mint functions
function getAccountLockTime(address account_) internal view returns (uint256) {
return IporFusionAccessManagersStorageLib.getRedemptionLocks().redemptionLock[account_];
}
/// @notice Check if account is locked for a specific function (correlation withdraw, redeem functions to deposit, mint functions)
/// @dev When deposit or mint functions are called, the account is locked for withdraw and redeem functions for a specific time defined by the redemption delay.
function lockChecks(address account_, bytes4 sig_) internal {
if (sig_ == WITHDRAW_SELECTOR || sig_ == REDEEM_SELECTOR) {
uint256 unlockTime = IporFusionAccessManagersStorageLib.getRedemptionLocks().redemptionLock[account_];
if (unlockTime > block.timestamp) {
revert AccountIsLocked(unlockTime);
}
} else if (sig_ == DEPOSIT_SELECTOR || sig_ == MINT_SELECTOR || sig_ == DEPOSIT_WITH_PERMIT_SELECTOR) {
IporFusionAccessManagersStorageLib.setRedemptionLocks(account_);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// On the first call to nonReentrant, _status will be NOT_ENTERED
if ($._status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
$._status = ENTERED;
}
function _nonReentrantAfter() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
$._status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {IporFusionAccessManagersStorageLib} from "./IporFusionAccessManagersStorageLib.sol";
/// @title Library for the role execution timelock responsible for timelocking actions for a given role
library RoleExecutionTimelockLib {
event MinimalExecutionDelayForRoleUpdated(uint64 roleId, uint256 delay);
/// @notice Gets the minimal execution delay for a role. When value is higher than 0, it means that actions for a given role have a timelock.
/// @param roleId_ The role ID
/// @return The minimal execution delay in seconds
function getMinimalExecutionDelayForRole(uint64 roleId_) internal view returns (uint256) {
return IporFusionAccessManagersStorageLib.getMinimalExecutionDelayForRole().delays[roleId_];
}
/// @notice Sets the minimal execution delays for roles. The delays are used to timelock actions for a given role.
/// @param roleIds_ The roles for which the minimal execution delay is set
/// @param delays_ The minimal execution delays for the specified roles
function setMinimalExecutionDelaysForRoles(uint64[] memory roleIds_, uint256[] memory delays_) internal {
uint256 length = roleIds_.length;
for (uint256 i; i < length; ++i) {
IporFusionAccessManagersStorageLib.getMinimalExecutionDelayForRole().delays[roleIds_[i]] = delays_[i];
emit MinimalExecutionDelayForRoleUpdated(roleIds_[i], delays_[i]);
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
/// @title Predefined roles used in the IPOR Fusion protocol
/// @notice For documentation purposes: When new roles are added by authorized property of PlasmaVault during runtime, they should be added and described here as well.
library Roles {
/// @notice Account with this role has rights to manage the IporFusionAccessManager in general. The highest role, which could manage all roles including ADMIN_ROLE and OWNER_ROLE. It recommended to use MultiSig contract for this role.
/// @dev Managed by the Admin, the highest role from AccessManager
uint64 public constant ADMIN_ROLE = 0;
/// @notice Account with this role has rights to manage Owners, Guardians, Atomists. It recommended to use MultiSig contract for this role.
/// @dev Managed by the Owner, if applicable managed by the Admin
uint64 public constant OWNER_ROLE = 1;
/// @notice Account with this role has rights to cancel time-locked operations, pause restricted methods in PlasmaVault contracts in case of emergency
/// @dev Managed by the Owner
uint64 public constant GUARDIAN_ROLE = 2;
/// @notice Technical role to limited access to method only from the PlasmaVault contract
/// @dev Managed only on bootstrap, this value could not be change after initialization
uint64 public constant TECH_PLASMA_VAULT_ROLE = 3;
/// @notice Technical role to limited access to method only from the PlasmaVault contract
/// @dev Managed only on bootstrap, this value could not be change after initialization
uint64 public constant IPOR_DAO_ROLE = 4;
/// @notice Account with this role has rights to manage the PlasmaVault. It recommended to use MultiSig contract for this role.
/// @dev Managed by Owner
uint64 public constant ATOMIST_ROLE = 100;
/// @notice Account with this role has rights to execute the alpha strategy on the PlasmaVault using execute method.
/// @dev Managed by the Atomist
uint64 public constant ALPHA_ROLE = 200;
/// @notice Account with this role has rights to manage the FuseManager contract, add or remove fuses, balance fuses and reward fuses
/// @dev Managed by the Atomist
uint64 public constant FUSE_MANAGER_ROLE = 300;
/// @notice Technical role for the FeeManager. Account with this role has rights to manage the performance fee, define the performance fee rate and manage the performance fee recipient
/// @dev Managed by itself the Performance Fee Manager
uint64 public constant TECH_PERFORMANCE_FEE_MANAGER_ROLE = 400;
/// @notice Technical role for the FeeManager. Account with this role has rights to manage the management fee, define the management fee rate and manage the management fee recipient
/// @dev Managed by itself the Management Fee Manager
uint64 public constant TECH_MANAGEMENT_FEE_MANAGER_ROLE = 500;
/// @notice Account with this role has rights to claim rewards from the PlasmaVault using and interacting with the RewardsClaimManager contract
/// @dev Managed by the Atomist
uint64 public constant CLAIM_REWARDS_ROLE = 600;
/// @notice Technical role for the RewardsClaimManager contract. Account with this role has rights to claim rewards from the PlasmaVault
/// @dev Could be assigned only on bootstrap, this value could not be change after initialization
uint64 public constant TECH_REWARDS_CLAIM_MANAGER_ROLE = 601;
/// @notice Account with this role has rights to transfer rewards from the PlasmaVault to the RewardsClaimManager
/// @dev Managed by the Atomist
uint64 public constant TRANSFER_REWARDS_ROLE = 700;
/// @notice Account with this role has rights to deposit / mint and withdraw / redeem assets from the PlasmaVault
/// @dev Managed by the Atomist
uint64 public constant WHITELIST_ROLE = 800;
/// @notice Account with this role has rights to configure instant withdrawal fuses order.
/// @dev Managed by the Atomist
uint64 public constant CONFIG_INSTANT_WITHDRAWAL_FUSES_ROLE = 900;
/// @notice Public role, no restrictions
uint64 public constant PUBLIC_ROLE = type(uint64).max;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/types/Time.sol)
pragma solidity ^0.8.20;
import {Math} from "../math/Math.sol";
import {SafeCast} from "../math/SafeCast.sol";
/**
* @dev This library provides helpers for manipulating time-related objects.
*
* It uses the following types:
* - `uint48` for timepoints
* - `uint32` for durations
*
* While the library doesn't provide specific types for timepoints and duration, it does provide:
* - a `Delay` type to represent duration that can be programmed to change value automatically at a given point
* - additional helper functions
*/
library Time {
using Time for *;
/**
* @dev Get the block timestamp as a Timepoint.
*/
function timestamp() internal view returns (uint48) {
return SafeCast.toUint48(block.timestamp);
}
/**
* @dev Get the block number as a Timepoint.
*/
function blockNumber() internal view returns (uint48) {
return SafeCast.toUint48(block.number);
}
// ==================================================== Delay =====================================================
/**
* @dev A `Delay` is a uint32 duration that can be programmed to change value automatically at a given point in the
* future. The "effect" timepoint describes when the transitions happens from the "old" value to the "new" value.
* This allows updating the delay applied to some operation while keeping some guarantees.
*
* In particular, the {update} function guarantees that if the delay is reduced, the old delay still applies for
* some time. For example if the delay is currently 7 days to do an upgrade, the admin should not be able to set
* the delay to 0 and upgrade immediately. If the admin wants to reduce the delay, the old delay (7 days) should
* still apply for some time.
*
*
* The `Delay` type is 112 bits long, and packs the following:
*
* ```
* | [uint48]: effect date (timepoint)
* | | [uint32]: value before (duration)
* ↓ ↓ ↓ [uint32]: value after (duration)
* 0xAAAAAAAAAAAABBBBBBBBCCCCCCCC
* ```
*
* NOTE: The {get} and {withUpdate} functions operate using timestamps. Block number based delays are not currently
* supported.
*/
type Delay is uint112;
/**
* @dev Wrap a duration into a Delay to add the one-step "update in the future" feature
*/
function toDelay(uint32 duration) internal pure returns (Delay) {
return Delay.wrap(duration);
}
/**
* @dev Get the value at a given timepoint plus the pending value and effect timepoint if there is a scheduled
* change after this timepoint. If the effect timepoint is 0, then the pending value should not be considered.
*/
function _getFullAt(Delay self, uint48 timepoint) private pure returns (uint32, uint32, uint48) {
(uint32 valueBefore, uint32 valueAfter, uint48 effect) = self.unpack();
return effect <= timepoint ? (valueAfter, 0, 0) : (valueBefore, valueAfter, effect);
}
/**
* @dev Get the current value plus the pending value and effect timepoint if there is a scheduled change. If the
* effect timepoint is 0, then the pending value should not be considered.
*/
function getFull(Delay self) internal view returns (uint32, uint32, uint48) {
return _getFullAt(self, timestamp());
}
/**
* @dev Get the current value.
*/
function get(Delay self) internal view returns (uint32) {
(uint32 delay, , ) = self.getFull();
return delay;
}
/**
* @dev Update a Delay object so that it takes a new duration after a timepoint that is automatically computed to
* enforce the old delay at the moment of the update. Returns the updated Delay object and the timestamp when the
* new delay becomes effective.
*/
function withUpdate(
Delay self,
uint32 newValue,
uint32 minSetback
) internal view returns (Delay updatedDelay, uint48 effect) {
uint32 value = self.get();
uint32 setback = uint32(Math.max(minSetback, value > newValue ? value - newValue : 0));
effect = timestamp() + setback;
return (pack(value, newValue, effect), effect);
}
/**
* @dev Split a delay into its components: valueBefore, valueAfter and effect (transition timepoint).
*/
function unpack(Delay self) internal pure returns (uint32 valueBefore, uint32 valueAfter, uint48 effect) {
uint112 raw = Delay.unwrap(self);
valueAfter = uint32(raw);
valueBefore = uint32(raw >> 32);
effect = uint48(raw >> 64);
return (valueBefore, valueAfter, effect);
}
/**
* @dev pack the components into a Delay object.
*/
function pack(uint32 valueBefore, uint32 valueAfter, uint48 effect) internal pure returns (Delay) {
return Delay.wrap((uint112(effect) << 64) | (uint112(valueBefore) << 32) | uint112(valueAfter));
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {AccessManagedUpgradeable} from "../access/AccessManagedUpgradeable.sol";
import {WithdrawManagerStorageLib} from "./WithdrawManagerStorageLib.sol";
import {WithdrawRequest} from "./WithdrawManagerStorageLib.sol";
struct WithdrawRequestInfo {
uint256 amount;
uint256 endWithdrawWindowTimestamp;
bool canWithdraw;
uint256 withdrawWindowInSeconds;
}
/**
* @title WithdrawManager
* @dev Manages withdrawal requests and their processing, ensuring that withdrawals are only allowed within specified windows and conditions.
*/
contract WithdrawManager is AccessManagedUpgradeable {
constructor(address accessManager_) {
initialize(accessManager_);
}
function initialize(address accessManager_) internal initializer {
super.__AccessManaged_init(accessManager_);
}
/**
* @notice Checks if the account can withdraw the specified amount and updates the withdraw request.
* @dev This function can only be executed by `plasmaVault` with role TECH_PLASMA_VAULT_ROLE.
* @param account_ The address of the account to check.
* @param amount_ The amount to check for withdrawal.
* @return bool True if the account can withdraw the specified amount, false otherwise.
*/
function canWithdrawAndUpdate(address account_, uint256 amount_) external restricted returns (bool) {
uint256 releaseFundsTimestamp = WithdrawManagerStorageLib.getLastReleaseFundsTimestamp();
WithdrawRequest memory request = WithdrawManagerStorageLib.getWithdrawRequest(account_);
if (request.endWithdrawWindowTimestamp == 0) {
return false;
}
if (
_canWithdraw(
request.endWithdrawWindowTimestamp,
WithdrawManagerStorageLib.getWithdrawWindowInSeconds(),
releaseFundsTimestamp
) && request.amount >= amount_
) {
WithdrawManagerStorageLib.deleteWithdrawRequest(account_);
return true;
}
return false;
}
function request(uint256 amount_) external {
WithdrawManagerStorageLib.updateWithdrawRequest(msg.sender, amount_);
}
function releaseFunds() external restricted {
WithdrawManagerStorageLib.releaseFunds();
}
function updateWithdrawWindow(uint256 window_) external restricted {
WithdrawManagerStorageLib.updateWithdrawWindowLength(window_);
}
function getWithdrawWindow() external view returns (uint256) {
return WithdrawManagerStorageLib.getWithdrawWindowInSeconds();
}
function requestInfo(address account_) external view returns (WithdrawRequestInfo memory) {
uint256 withdrawWindow = WithdrawManagerStorageLib.getWithdrawWindowInSeconds();
uint256 releaseFundsTimestamp = WithdrawManagerStorageLib.getLastReleaseFundsTimestamp();
WithdrawRequest memory request = WithdrawManagerStorageLib.getWithdrawRequest(account_);
return
WithdrawRequestInfo({
amount: request.amount,
endWithdrawWindowTimestamp: request.endWithdrawWindowTimestamp,
canWithdraw: _canWithdraw(request.endWithdrawWindowTimestamp, withdrawWindow, releaseFundsTimestamp),
withdrawWindowInSeconds: withdrawWindow
});
}
function _canWithdraw(
uint256 endWithdrawWindowTimestamp,
uint256 withdrawWindow,
uint256 releaseFundsTimestamp
) private view returns (bool) {
/// @dev endWithdrawWindowTimestamp - withdrawWindow = moment when user did request for withdraw
return
block.timestamp >= endWithdrawWindowTimestamp - withdrawWindow &&
block.timestamp <= endWithdrawWindowTimestamp &&
endWithdrawWindowTimestamp - withdrawWindow < releaseFundsTimestamp;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
struct WithdrawRequest {
/// @dev The amount of the request, in underlying token decimals
uint128 amount;
/// @dev The end of the withdraw window, to calculate requestTimeStamp + withdrawWindowInSeconds;
uint32 endWithdrawWindowTimestamp;
}
struct WithdrawRequests {
mapping(address account => WithdrawRequest request) requests;
}
struct WithdrawWindow {
/// @dev The length of the withdraw window, in seconds
uint256 withdrawWindowInSeconds;
}
struct ReleaseFunds {
/// @dev The last time the funds were released
uint256 lastReleaseFundsTimestamp;
}
library WithdrawManagerStorageLib {
using SafeCast for uint256;
event WithdrawWindowLengthUpdated(uint256 withdrawWindowLength);
event WithdrawRequestUpdated(address account, uint256 amount, uint32 endWithdrawWindow);
event ReleaseFundsUpdated(uint256 releaseFunds);
error WithdrawWindowLengthCannotBeZero();
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.managers.rewards.withdrawWindowInSeconds")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant WITHDRAW_WINDOW_IN_SECONDS =
0xc98a13e0ed3915d36fc042835990f5c6fbf2b2570bd63878dcd560ca2b767c00;
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.managers.rewards.withdrawRequests")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant WITHDRAW_REQUESTS = 0x5f79d61c9d5139383097775e8e8bbfd941634f6602a18bee02d4f80d80c89f00;
/// @dev keccak256(abi.encode(uint256(keccak256("io.ipor.managers.rewards.lastReleaseFudsTimestamp")) - 1)) & ~bytes32(uint256(0xff));
bytes32 private constant LAST_RELEASE_FUNDS_TIMESTAMP =
0x6603575a0b471dee79b9613aa260e2a8f3515603a898fdc76d6849fcd1ac7800;
function _getWithdrawWindowLength() private view returns (WithdrawWindow storage withdrawWindow) {
assembly {
withdrawWindow.slot := WITHDRAW_WINDOW_IN_SECONDS
}
}
function _getWithdrawRequests() private view returns (WithdrawRequests storage requests) {
assembly {
requests.slot := WITHDRAW_REQUESTS
}
}
function _getReleaseFunds() private view returns (ReleaseFunds storage releaseFundsResult) {
assembly {
releaseFundsResult.slot := LAST_RELEASE_FUNDS_TIMESTAMP
}
}
function updateWithdrawWindowLength(uint256 withdrawWindowLength_) internal {
if (withdrawWindowLength_ == 0) {
revert WithdrawWindowLengthCannotBeZero();
}
WithdrawWindow storage withdrawWindow = _getWithdrawWindowLength();
withdrawWindow.withdrawWindowInSeconds = withdrawWindowLength_;
emit WithdrawWindowLengthUpdated(withdrawWindowLength_);
}
function getWithdrawWindowInSeconds() internal view returns (uint256) {
return _getWithdrawWindowLength().withdrawWindowInSeconds;
}
function getWithdrawRequest(address account_) internal view returns (WithdrawRequest memory) {
return _getWithdrawRequests().requests[account_];
}
function updateWithdrawRequest(address requester, uint256 amount_) internal {
uint256 withdrawWindowLength = getWithdrawWindowInSeconds();
WithdrawRequest memory request = WithdrawRequest({
amount: amount_.toUint128(),
endWithdrawWindowTimestamp: block.timestamp.toUint32() + withdrawWindowLength.toUint32()
});
_getWithdrawRequests().requests[requester] = request;
emit WithdrawRequestUpdated(requester, amount_, request.endWithdrawWindowTimestamp);
}
function deleteWithdrawRequest(address account_) internal {
delete _getWithdrawRequests().requests[account_];
emit WithdrawRequestUpdated(account_, 0, 0);
}
function getLastReleaseFundsTimestamp() internal view returns (uint256) {
return _getReleaseFunds().lastReleaseFundsTimestamp;
}
function releaseFunds() internal {
ReleaseFunds storage releaseFundsLocal = _getReleaseFunds();
releaseFundsLocal.lastReleaseFundsTimestamp = block.timestamp;
emit ReleaseFundsUpdated(block.timestamp);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
{
"compilationTarget": {
"contracts/managers/access/IporFusionAccessManager.sol": "IporFusionAccessManager"
},
"evmVersion": "cancun",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 1000000
},
"remappings": [
":@chainlink/=node_modules/@chainlink/",
":@ensdomains/=node_modules/@ensdomains/",
":@eth-optimism/=node_modules/@eth-optimism/",
":@ethereum-vault-connector/=node_modules/ethereum-vault-connector/",
":@morpho-org/=node_modules/@morpho-org/",
":@openzeppelin/=node_modules/@openzeppelin/",
":@prb/test/=lib/foundry-random/lib/prb-test/src/",
":@scroll-tech/=node_modules/@scroll-tech/",
":@uniswap/v3-core/=node_modules/@uniswap/v3-core/",
":CramBit/=lib/foundry-random/lib/CramBit/",
":base64-sol/=node_modules/base64-sol/",
":crambit/=lib/foundry-random/lib/CramBit/src/",
":ds-test/=lib/forge-std/lib/ds-test/src/",
":eth-gas-reporter/=node_modules/eth-gas-reporter/",
":ethereum-vault-connector/=node_modules/ethereum-vault-connector/",
":forge-std/=lib/forge-std/src/",
":foundry-random/=lib/foundry-random/src/",
":openzeppelin/=node_modules/ethereum-vault-connector/lib/openzeppelin-contracts/contracts/",
":prb-test/=lib/foundry-random/lib/prb-test/src/",
":solidity-bytes-utils/=lib/foundry-random/lib/solidity-bytes-utils/contracts/",
":src/=lib/foundry-random/src/"
]
}
[{"inputs":[{"internalType":"address","name":"initialAdmin_","type":"address"},{"internalType":"uint256","name":"redemptionDelayInSeconds_","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"AccessManagedUnauthorized","type":"error"},{"inputs":[{"internalType":"bytes32","name":"operationId","type":"bytes32"}],"name":"AccessManagerAlreadyScheduled","type":"error"},{"inputs":[],"name":"AccessManagerBadConfirmation","type":"error"},{"inputs":[{"internalType":"bytes32","name":"operationId","type":"bytes32"}],"name":"AccessManagerExpired","type":"error"},{"inputs":[{"internalType":"address","name":"initialAdmin","type":"address"}],"name":"AccessManagerInvalidInitialAdmin","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AccessManagerLockedAccount","type":"error"},{"inputs":[{"internalType":"uint64","name":"roleId","type":"uint64"}],"name":"AccessManagerLockedRole","type":"error"},{"inputs":[{"internalType":"bytes32","name":"operationId","type":"bytes32"}],"name":"AccessManagerNotReady","type":"error"},{"inputs":[{"internalType":"bytes32","name":"operationId","type":"bytes32"}],"name":"AccessManagerNotScheduled","type":"error"},{"inputs":[{"internalType":"address","name":"msgsender","type":"address"},{"internalType":"uint64","name":"roleId","type":"uint64"}],"name":"AccessManagerUnauthorizedAccount","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"},{"internalType":"address","name":"target","type":"address"},{"internalType":"bytes4","name":"selector","type":"bytes4"}],"name":"AccessManagerUnauthorizedCall","type":"error"},{"inputs":[{"internalType":"address","name":"msgsender","type":"address"},{"internalType":"address","name":"caller","type":"address"},{"internalType":"address","name":"target","type":"address"},{"internalType":"bytes4","name":"selector","type":"bytes4"}],"name":"AccessManagerUnauthorizedCancel","type":"error"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AccessManagerUnauthorizedConsume","type":"error"},{"inputs":[{"internalType":"uint256","name":"unlockTime","type":"uint256"}],"name":"AccountIsLocked","type":"error"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"AlreadyInitialized","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[{"internalType":"uint8","name":"bits","type":"uint8"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"SafeCastOverflowedUintDowncast","type":"error"},{"inputs":[{"internalType":"uint256","name":"redemptionDelayInSeconds","type":"uint256"}],"name":"TooLongRedemptionDelay","type":"error"},{"inputs":[{"internalType":"uint64","name":"roleId","type":"uint64"},{"internalType":"uint32","name":"executionDelay","type":"uint32"}],"name":"TooShortExecutionDelayForRole","type":"error"},{"anonymous":false,"inputs":[],"name":"IporFusionAccessManagerInitialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"roleId","type":"uint64"},{"indexed":false,"internalType":"uint256","name":"delay","type":"uint256"}],"name":"MinimalExecutionDelayForRoleUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"operationId","type":"bytes32"},{"indexed":true,"internalType":"uint32","name":"nonce","type":"uint32"}],"name":"OperationCanceled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"operationId","type":"bytes32"},{"indexed":true,"internalType":"uint32","name":"nonce","type":"uint32"}],"name":"OperationExecuted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"operationId","type":"bytes32"},{"indexed":true,"internalType":"uint32","name":"nonce","type":"uint32"},{"indexed":false,"internalType":"uint48","name":"schedule","type":"uint48"},{"indexed":false,"internalType":"address","name":"caller","type":"address"},{"indexed":false,"internalType":"address","name":"target","type":"address"},{"indexed":false,"internalType":"bytes","name":"data","type":"bytes"}],"name":"OperationScheduled","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"redemptionDelay","type":"uint256"}],"name":"RedemptionDelayForAccountUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint64","name":"roleId","type":"uint64"},{"indexed":true,"internalType":"uint64","name":"admin","type":"uint64"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint64","name":"roleId","type":"uint64"},{"indexed":false,"internalType":"uint32","name":"delay","type":"uint32"},{"indexed":false,"internalType":"uint48","name":"since","type":"uint48"}],"name":"RoleGrantDelayChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint64","name":"roleId","type":"uint64"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint32","name":"delay","type":"uint32"},{"indexed":false,"internalType":"uint48","name":"since","type":"uint48"},{"indexed":false,"internalType":"bool","name":"newMember","type":"bool"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint64","name":"roleId","type":"uint64"},{"indexed":true,"internalType":"uint64","name":"guardian","type":"uint64"}],"name":"RoleGuardianChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint64","name":"roleId","type":"uint64"},{"indexed":false,"internalType":"string","name":"label","type":"string"}],"name":"RoleLabel","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint64","name":"roleId","type":"uint64"},{"indexed":true,"internalType":"address","name":"account","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"target","type":"address"},{"indexed":false,"internalType":"uint32","name":"delay","type":"uint32"},{"indexed":false,"internalType":"uint48","name":"since","type":"uint48"}],"name":"TargetAdminDelayUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"target","type":"address"},{"indexed":false,"internalType":"bool","name":"closed","type":"bool"}],"name":"TargetClosed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"target","type":"address"},{"indexed":false,"internalType":"bytes4","name":"selector","type":"bytes4"},{"indexed":true,"internalType":"uint64","name":"roleId","type":"uint64"}],"name":"TargetFunctionRoleUpdated","type":"event"},{"inputs":[],"name":"ADMIN_ROLE","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_REDEMPTION_DELAY_IN_SECONDS","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PUBLIC_ROLE","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"REDEMPTION_DELAY_IN_SECONDS","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"caller","type":"address"},{"internalType":"address","name":"target","type":"address"},{"internalType":"bytes4","name":"selector","type":"bytes4"}],"name":"canCall","outputs":[{"internalType":"bool","name":"immediate","type":"bool"},{"internalType":"uint32","name":"delay","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"caller_","type":"address"},{"internalType":"address","name":"target_","type":"address"},{"internalType":"bytes4","name":"selector_","type":"bytes4"}],"name":"canCallAndUpdate","outputs":[{"internalType":"bool","name":"immediate","type":"bool"},{"internalType":"uint32","name":"delay","type":"uint32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"caller","type":"address"},{"internalType":"address","name":"target","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"cancel","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"caller","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"consumeScheduledOp","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"vault_","type":"address"}],"name":"convertToPublicVault","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"vault_","type":"address"}],"name":"enableTransferShares","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"execute","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"expiration","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint64","name":"roleId","type":"uint64"},{"internalType":"address","name":"account","type":"address"}],"name":"getAccess","outputs":[{"internalType":"uint48","name":"since","type":"uint48"},{"internalType":"uint32","name":"currentDelay","type":"uint32"},{"internalType":"uint32","name":"pendingDelay","type":"uint32"},{"internalType":"uint48","name":"effect","type":"uint48"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account_","type":"address"}],"name":"getAccountLockTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint64","name":"roleId_","type":"uint64"}],"name":"getMinimalExecutionDelayForRole","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"id","type":"bytes32"}],"name":"getNonce","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint64","name":"roleId","type":"uint64"}],"name":"getRoleAdmin","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint64","name":"roleId","type":"uint64"}],"name":"getRoleGrantDelay","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint64","name":"roleId","type":"uint64"}],"name":"getRoleGuardian","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"id","type":"bytes32"}],"name":"getSchedule","outputs":[{"internalType":"uint48","name":"","type":"uint48"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"getTargetAdminDelay","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"bytes4","name":"selector","type":"bytes4"}],"name":"getTargetFunctionRole","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint64","name":"roleId_","type":"uint64"},{"internalType":"address","name":"account_","type":"address"},{"internalType":"uint32","name":"executionDelay_","type":"uint32"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint64","name":"roleId","type":"uint64"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"isMember","type":"bool"},{"internalType":"uint32","name":"executionDelay","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"caller","type":"address"},{"internalType":"address","name":"target","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"hashOperation","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"components":[{"internalType":"address","name":"target","type":"address"},{"internalType":"uint64","name":"roleId","type":"uint64"},{"internalType":"bytes4","name":"functionSelector","type":"bytes4"},{"internalType":"uint256","name":"minimalExecutionDelay","type":"uint256"}],"internalType":"struct RoleToFunction[]","name":"roleToFunctions","type":"tuple[]"},{"components":[{"internalType":"uint64","name":"roleId","type":"uint64"},{"internalType":"address","name":"account","type":"address"},{"internalType":"uint32","name":"executionDelay","type":"uint32"}],"internalType":"struct AccountToRole[]","name":"accountToRoles","type":"tuple[]"},{"components":[{"internalType":"uint64","name":"roleId","type":"uint64"},{"internalType":"uint64","name":"adminRoleId","type":"uint64"}],"internalType":"struct AdminRole[]","name":"adminRoles","type":"tuple[]"}],"internalType":"struct InitializationData","name":"initialData_","type":"tuple"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"isConsumingScheduledOp","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"isTargetClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint64","name":"roleId","type":"uint64"},{"internalType":"string","name":"label","type":"string"}],"name":"labelRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"minSetback","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"results","type":"bytes[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint64","name":"roleId","type":"uint64"},{"internalType":"address","name":"callerConfirmation","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint64","name":"roleId","type":"uint64"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"uint48","name":"when","type":"uint48"}],"name":"schedule","outputs":[{"internalType":"bytes32","name":"operationId","type":"bytes32"},{"internalType":"uint32","name":"nonce","type":"uint32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint64","name":"roleId","type":"uint64"},{"internalType":"uint32","name":"newDelay","type":"uint32"}],"name":"setGrantDelay","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint64[]","name":"rolesIds_","type":"uint64[]"},{"internalType":"uint256[]","name":"delays_","type":"uint256[]"}],"name":"setMinimalExecutionDelaysForRoles","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint64","name":"roleId","type":"uint64"},{"internalType":"uint64","name":"admin","type":"uint64"}],"name":"setRoleAdmin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint64","name":"roleId","type":"uint64"},{"internalType":"uint64","name":"guardian","type":"uint64"}],"name":"setRoleGuardian","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"uint32","name":"newDelay","type":"uint32"}],"name":"setTargetAdminDelay","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"bool","name":"closed","type":"bool"}],"name":"setTargetClosed","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"bytes4[]","name":"selectors","type":"bytes4[]"},{"internalType":"uint64","name":"roleId","type":"uint64"}],"name":"setTargetFunctionRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"address","name":"newAuthority","type":"address"}],"name":"updateAuthority","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"target_","type":"address"},{"internalType":"bool","name":"closed_","type":"bool"}],"name":"updateTargetClosed","outputs":[],"stateMutability":"nonpayable","type":"function"}]