Source Code
| Transaction Hash |
|
Block
|
From
|
To
|
|||||
|---|---|---|---|---|---|---|---|---|---|
View more zero value Internal Transactions in Advanced View mode
Advanced mode:
Cross-Chain Transactions
Loading...
Loading
Contract Name:
MorphoVaultArk
Compiler Version
v0.8.28+commit.7893614a
Optimization Enabled:
Yes with 25 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IUniversalRewardsDistributor} from "../../interfaces/morpho/IUniversalRewardsDistributor.sol";
import "../Ark.sol";
import {IMetaMorpho} from "metamorpho/interfaces/IMetaMorpho.sol";
import {IUrdFactory} from "morpho-blue/interfaces/IUrdFactory.sol";
error InvalidUrdAddress();
error InvalidUrdFactoryAddress();
/**
* @title MorphoVaultArk
* @notice Ark contract for managing token supply and yield generation through MetaMorpho vaults.
* @dev Implements strategy for depositing tokens, withdrawing tokens, and claiming rewards from MetaMorpho vaults.
*/
contract MorphoVaultArk is Ark {
using SafeERC20 for IERC20;
/**
* @notice Struct to hold data for claiming rewards
* @param urd Array of Universal Rewards Distributor addresses
* @param rewards Array of reward token addresses
* @param claimable Array of claimable reward amounts
* @param proofs Array of Merkle proofs for claiming rewards
*/
struct RewardsData {
address[] urd;
address[] rewards;
uint256[] claimable;
bytes32[][] proofs;
}
/*//////////////////////////////////////////////////////////////
STATE VARIABLES
//////////////////////////////////////////////////////////////*/
/// @notice The MetaMorpho vault this Ark interacts with
IMetaMorpho public immutable metaMorpho;
/// @notice The URD factory this Ark interacts with
IUrdFactory public immutable URD_FACTORY;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/**
* @notice Constructor to set up the MorphoVaultArk
* @param _metaMorpho Address of the MetaMorpho vault
* @param _urdFactory Address of the URD factory
* @param _params ArkParams struct containing necessary parameters for Ark initialization
*/
constructor(
address _metaMorpho,
address _urdFactory,
ArkParams memory _params
) Ark(_params) {
if (_metaMorpho == address(0)) {
revert InvalidVaultAddress();
}
if (_urdFactory == address(0)) {
revert InvalidUrdFactoryAddress();
}
URD_FACTORY = IUrdFactory(_urdFactory);
metaMorpho = IMetaMorpho(_metaMorpho);
}
/*//////////////////////////////////////////////////////////////
VIEW FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @inheritdoc IArk
* @notice Returns the total assets managed by this Ark in the MetaMorpho vault
* @return assets The total balance of underlying assets held in the vault for this Ark
*/
function totalAssets() public view override returns (uint256 assets) {
uint256 shares = metaMorpho.balanceOf(address(this));
if (shares > 0) {
assets = metaMorpho.convertToAssets(shares);
}
}
/*//////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Internal function to get the total assets that are withdrawable
* @dev MetaMorphoArk is always withdrawable
*/
function _withdrawableTotalAssets()
internal
view
override
returns (uint256 withdrawableAssets)
{
uint256 shares = metaMorpho.balanceOf(address(this));
if (shares > 0) {
withdrawableAssets = metaMorpho.maxWithdraw(address(this));
}
}
/**
* @notice Deposits assets into the MetaMorpho vault
* @param amount The amount of assets to deposit
* @param /// data Additional data (unused in this implementation)
*/
function _board(uint256 amount, bytes calldata) internal override {
config.asset.forceApprove(address(metaMorpho), amount);
metaMorpho.deposit(amount, address(this));
}
/**
* @notice Withdraws assets from the MetaMorpho vault
* @param amount The amount of assets to withdraw
* @param /// data Additional data (unused in this implementation)
*/
function _disembark(uint256 amount, bytes calldata) internal override {
if (amount == totalAssets()) {
metaMorpho.redeem(
metaMorpho.balanceOf(address(this)),
address(this),
address(this)
);
} else {
metaMorpho.withdraw(amount, address(this), address(this));
}
}
/**
* @notice Internal function to harvest rewards based on the provided claim data
* @dev This function decodes the claim data, iterates through the rewards, and claims them
* from the respective Universal Rewards Distributors. The claimed rewards are then
* transferred to the configured raft address.
*
* @param _claimData Encoded RewardsData struct containing information about the rewards to be claimed
*
* @return rewardTokens An array of addresses of the reward tokens that were claimed
* @return rewardAmounts An array of amounts of the reward tokens that were claimed
*
* The RewardsData struct is expected to contain:
* - urd: An array of Universal Rewards Distributor addresses
* - rewards: An array of reward token addresses
* - claimable: An array of claimable reward amounts
* - proofs: An array of Merkle proofs for claiming rewards
*
* Emits an {ArkHarvested} event upon successful harvesting of rewards.
*/
function _harvest(
bytes calldata _claimData
)
internal
override
returns (address[] memory rewardTokens, uint256[] memory rewardAmounts)
{
RewardsData memory claimData = abi.decode(_claimData, (RewardsData));
rewardTokens = new address[](claimData.rewards.length);
rewardAmounts = new uint256[](claimData.rewards.length);
for (uint256 i = 0; i < claimData.rewards.length; i++) {
if (!URD_FACTORY.isUrd(claimData.urd[i])) {
revert InvalidUrdAddress();
}
/**
* @dev Claims rewards from the Universal Rewards Distributor
* @param address(this) The address of the contract claiming the rewards (this MorphoVaultArk)
* @param claimData.rewards[i] The address of the reward token to claim
* @param claimData.claimable[i] The amount of rewards to claim
* @param claimData.proofs[i] The Merkle proof required to claim the rewards
*/
uint256 claimed = IUniversalRewardsDistributor(claimData.urd[i])
.claim(
address(this),
claimData.rewards[i],
claimData.claimable[i],
claimData.proofs[i]
);
rewardTokens[i] = claimData.rewards[i];
rewardAmounts[i] = claimed;
IERC20(claimData.rewards[i]).safeTransfer(raft(), claimed);
}
emit ArkHarvested(rewardTokens, rewardAmounts);
}
/**
* @notice Validates the board data
* @dev This Ark does not require any validation for board data
* @param /// data Additional data to validate (unused in this implementation)
*/
function _validateBoardData(bytes calldata) internal override {}
/**
* @notice Validates the disembark data
* @dev This Ark does not require any validation for disembark data
* @param /// data Additional data to validate (unused in this implementation)
*/
function _validateDisembarkData(bytes calldata) internal override {}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {IERC165, ERC165} from "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
mapping(bytes32 role => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
return _roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
if (!hasRole(role, account)) {
_roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
if (hasRole(role, account)) {
_roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)
pragma solidity >=0.8.4;
/**
* @dev External interface of AccessControl declared to support ERC-165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted to signal this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 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 ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-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 ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 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);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC4626.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Interface of the ERC-4626 "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 redemption 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: MIT
// OpenZeppelin Contracts (last updated v5.4.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 ERC-20
* applications.
*/
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}.
*
* Both 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;
}
/// @inheritdoc IERC20
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/// @inheritdoc IERC20
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;
}
/// @inheritdoc IERC20
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}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* 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:
*
* ```solidity
* 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.4.0) (token/ERC20/extensions/ERC4626.sol)
pragma solidity ^0.8.20;
import {IERC20, IERC20Metadata, ERC20} from "../ERC20.sol";
import {SafeERC20} from "../utils/SafeERC20.sol";
import {IERC4626} from "../../../interfaces/IERC4626.sol";
import {Math} from "../../../utils/math/Math.sol";
/**
* @dev Implementation of the ERC-4626 "Tokenized Vault Standard" as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*
* This extension allows the minting and burning of "shares" (represented using the ERC-20 inheritance) in exchange for
* underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends
* the ERC-20 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 introduces configurable virtual assets and shares to help developers 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 even if an attacker is able to capture value from multiple user deposits, 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:ROOT: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 ERC4626 is ERC20, IERC4626 {
using Math for uint256;
IERC20 private immutable _asset;
uint8 private immutable _underlyingDecimals;
/**
* @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 (ERC-20 or ERC-777).
*/
constructor(IERC20 asset_) {
(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 ok, uint8 assetDecimals) {
(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, ERC20) returns (uint8) {
return _underlyingDecimals + _decimalsOffset();
}
/// @inheritdoc IERC4626
function asset() public view virtual returns (address) {
return address(_asset);
}
/// @inheritdoc IERC4626
function totalAssets() public view virtual returns (uint256) {
return IERC20(asset()).balanceOf(address(this));
}
/// @inheritdoc IERC4626
function convertToShares(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Floor);
}
/// @inheritdoc IERC4626
function convertToAssets(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Floor);
}
/// @inheritdoc IERC4626
function maxDeposit(address) public view virtual returns (uint256) {
return type(uint256).max;
}
/// @inheritdoc IERC4626
function maxMint(address) public view virtual returns (uint256) {
return type(uint256).max;
}
/// @inheritdoc IERC4626
function maxWithdraw(address owner) public view virtual returns (uint256) {
return _convertToAssets(balanceOf(owner), Math.Rounding.Floor);
}
/// @inheritdoc IERC4626
function maxRedeem(address owner) public view virtual returns (uint256) {
return balanceOf(owner);
}
/// @inheritdoc IERC4626
function previewDeposit(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Floor);
}
/// @inheritdoc IERC4626
function previewMint(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Ceil);
}
/// @inheritdoc IERC4626
function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Ceil);
}
/// @inheritdoc IERC4626
function previewRedeem(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Floor);
}
/// @inheritdoc IERC4626
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;
}
/// @inheritdoc IERC4626
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;
}
/// @inheritdoc IERC4626
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;
}
/// @inheritdoc IERC4626
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 {
// If asset() is ERC-777, `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(IERC20(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 {
if (caller != owner) {
_spendAllowance(owner, caller, shares);
}
// If asset() is ERC-777, `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(IERC20(asset()), receiver, assets);
emit Withdraw(caller, receiver, owner, assets, shares);
}
function _decimalsOffset() internal view virtual returns (uint8) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 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.4.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC-20 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.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
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.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 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 {
/**
* @dev An operation with an ERC-20 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 Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(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.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
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.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
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.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
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 Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
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 silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}// 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.4.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(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.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* 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 {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 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 low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, 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 ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
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⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// 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²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev 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) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @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 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @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.1.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/bool 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);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/ReentrancyGuardTransient.sol)
pragma solidity ^0.8.24;
import {TransientSlot} from "./TransientSlot.sol";
/**
* @dev Variant of {ReentrancyGuard} that uses transient storage.
*
* NOTE: This variant only works on networks where EIP-1153 is available.
*
* _Available since v5.1._
*/
abstract contract ReentrancyGuardTransient {
using TransientSlot for *;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
/**
* @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 {
// On the first call to nonReentrant, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
}
function _nonReentrantAfter() private {
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
}
/**
* @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) {
return REENTRANCY_GUARD_STORAGE.asBoolean().tload();
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.
pragma solidity ^0.8.24;
/**
* @dev Library for reading and writing value-types to specific transient storage slots.
*
* Transient slots are often used to store temporary values that are removed after the current transaction.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* * Example reading and writing values using transient storage:
* ```solidity
* contract Lock {
* using TransientSlot for *;
*
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
*
* modifier locked() {
* require(!_LOCK_SLOT.asBoolean().tload());
*
* _LOCK_SLOT.asBoolean().tstore(true);
* _;
* _LOCK_SLOT.asBoolean().tstore(false);
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library TransientSlot {
/**
* @dev UDVT that represents a slot holding an address.
*/
type AddressSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a AddressSlot.
*/
function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
return AddressSlot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a bool.
*/
type BooleanSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a BooleanSlot.
*/
function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
return BooleanSlot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a bytes32.
*/
type Bytes32Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Bytes32Slot.
*/
function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
return Bytes32Slot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a uint256.
*/
type Uint256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Uint256Slot.
*/
function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
return Uint256Slot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a int256.
*/
type Int256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Int256Slot.
*/
function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
return Int256Slot.wrap(slot);
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(AddressSlot slot) internal view returns (address value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(AddressSlot slot, address value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(BooleanSlot slot) internal view returns (bool value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(BooleanSlot slot, bool value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Bytes32Slot slot, bytes32 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Uint256Slot slot) internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Uint256Slot slot, uint256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Int256Slot slot) internal view returns (int256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Int256Slot slot, int256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IAccessControlErrors} from "../interfaces/IAccessControlErrors.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
/**
* @title LimitedAccessControl
* @dev This contract extends OpenZeppelin's AccessControl, disabling direct role granting and revoking.
* It's designed to be used as a base contract for more specific access control implementations.
* @dev This contract overrides the grantRole and revokeRole functions from AccessControl to disable direct role
* granting and revoking.
* @dev It doesn't override the renounceRole function, so it can be used to renounce roles for compromised accounts.
*/
abstract contract LimitedAccessControl is AccessControl, IAccessControlErrors {
/**
* @dev Overrides the grantRole function from AccessControl to disable direct role granting.
* @notice This function always reverts with a DirectGrantIsDisabled error.
*/
function grantRole(bytes32, address) public view override {
revert DirectGrantIsDisabled(msg.sender);
}
/**
* @dev Overrides the revokeRole function from AccessControl to disable direct role revoking.
* @notice This function always reverts with a DirectRevokeIsDisabled error.
*/
function revokeRole(bytes32, address) public view override {
revert DirectRevokeIsDisabled(msg.sender);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IAccessControlErrors} from "../interfaces/IAccessControlErrors.sol";
import {ContractSpecificRoles, IProtocolAccessManager} from "../interfaces/IProtocolAccessManager.sol";
import {ProtocolAccessManager} from "./ProtocolAccessManager.sol";
import {Context} from "@openzeppelin/contracts/utils/Context.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @title ProtocolAccessManaged
* @notice This contract provides role-based access control functionality for protocol contracts
* by interfacing with a central ProtocolAccessManager.
*
* @dev This contract is meant to be inherited by other protocol contracts that need
* role-based access control. It provides modifiers and utilities to check various roles.
*
* The contract supports several key roles through modifiers:
* 1. GOVERNOR_ROLE: System-wide administrators
* 2. KEEPER_ROLE: Routine maintenance operators (contract-specific)
* 3. SUPER_KEEPER_ROLE: Advanced maintenance operators (global)
* 4. CURATOR_ROLE: Fleet-specific managers
* 5. GUARDIAN_ROLE: Emergency response operators
* 6. DECAY_CONTROLLER_ROLE: Specific role for decay management
* 7. ADMIRALS_QUARTERS_ROLE: Specific role for admirals quarters bundler contract
*
* Usage:
* - Inherit from this contract to gain access to role-checking modifiers
* - Use modifiers like onlyGovernor, onlyKeeper, etc. to protect functions
* - Access the internal _accessManager to perform custom role checks
*
* Security Considerations:
* - The contract validates the access manager address during construction
* - All role checks are performed against the immutable access manager instance
* - Contract-specific roles are generated using the contract's address to prevent conflicts
*/
contract ProtocolAccessManaged is IAccessControlErrors, Context {
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @notice Role identifier for protocol governors - highest privilege level with admin capabilities
bytes32 public constant GOVERNOR_ROLE = keccak256("GOVERNOR_ROLE");
/// @notice Role identifier for super keepers who can globally perform fleet maintanence roles
bytes32 public constant SUPER_KEEPER_ROLE = keccak256("SUPER_KEEPER_ROLE");
/**
* @notice Role identifier for protocol guardians
* @dev Guardians have emergency powers across multiple protocol components:
* - Can pause/unpause Fleet operations for security
* - Can pause/unpause TipJar operations
* - Can cancel governance proposals on SummerGovernor even if they don't meet normal cancellation requirements
* - Can cancel TipJar proposals
*
* The guardian role serves as an emergency backstop to protect the protocol, but with less
* privilege than governors.
*/
bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE");
/**
* @notice Role identifier for decay controller
* @dev This role allows the decay controller to manage the decay of user voting power
*/
bytes32 public constant DECAY_CONTROLLER_ROLE =
keccak256("DECAY_CONTROLLER_ROLE");
/**
* @notice Role identifier for admirals quarters bundler contract
* @dev This role allows Admirals Quarters to unstake and withdraw assets from fleets, on behalf of users
* @dev Withdrawn tokens go straight to users wallet, lowering the risk of manipulation if the role is compromised
*/
bytes32 public constant ADMIRALS_QUARTERS_ROLE =
keccak256("ADMIRALS_QUARTERS_ROLE");
/*//////////////////////////////////////////////////////////////
STATE VARIABLES
//////////////////////////////////////////////////////////////*/
/// @notice The ProtocolAccessManager instance used for access control
ProtocolAccessManager internal immutable _accessManager;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/**
* @notice Initializes the ProtocolAccessManaged contract
* @param accessManager Address of the ProtocolAccessManager contract
* @dev Validates the provided accessManager address and initializes the _accessManager
*/
constructor(address accessManager) {
if (accessManager == address(0)) {
revert InvalidAccessManagerAddress(address(0));
}
if (
!IERC165(accessManager).supportsInterface(
type(IProtocolAccessManager).interfaceId
)
) {
revert InvalidAccessManagerAddress(accessManager);
}
_accessManager = ProtocolAccessManager(accessManager);
}
/*//////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////*/
/**
* @notice Modifier to restrict access to governors only
*
* @dev Modifier to check that the caller has the Governor role
* @custom:internal-logic
* - Checks if the caller has the GOVERNOR_ROLE in the access manager
* @custom:effects
* - Reverts if the caller doesn't have the GOVERNOR_ROLE
* - Allows the function to proceed if the caller has the role
* @custom:security-considerations
* - Ensures that only authorized governors can access critical functions
* - Relies on the correct setup of the access manager
*/
modifier onlyGovernor() {
if (!_accessManager.hasRole(GOVERNOR_ROLE, msg.sender)) {
revert CallerIsNotGovernor(msg.sender);
}
_;
}
/**
* @notice Modifier to restrict access to keepers only
* @dev Modifier to check that the caller has the Keeper role
* @custom:internal-logic
* - Checks if the caller has either the contract-specific KEEPER_ROLE or the SUPER_KEEPER_ROLE
* @custom:effects
* - Reverts if the caller doesn't have either of the required roles
* - Allows the function to proceed if the caller has one of the roles
* @custom:security-considerations
* - Ensures that only authorized keepers can access maintenance functions
* - Allows for both contract-specific and super keepers
* @custom:gas-considerations
* - Performs two role checks, which may impact gas usage
*/
modifier onlyKeeper() {
if (
!_accessManager.hasRole(
generateRole(ContractSpecificRoles.KEEPER_ROLE, address(this)),
msg.sender
) && !_accessManager.hasRole(SUPER_KEEPER_ROLE, msg.sender)
) {
revert CallerIsNotKeeper(msg.sender);
}
_;
}
/**
* @notice Modifier to restrict access to super keepers only
* @dev Modifier to check that the caller has the Super Keeper role
* @custom:internal-logic
* - Checks if the caller has the SUPER_KEEPER_ROLE in the access manager
* @custom:effects
* - Reverts if the caller doesn't have the SUPER_KEEPER_ROLE
* - Allows the function to proceed if the caller has the role
* @custom:security-considerations
* - Ensures that only authorized super keepers can access advanced maintenance functions
* - Relies on the correct setup of the access manager
*/
modifier onlySuperKeeper() {
if (!_accessManager.hasRole(SUPER_KEEPER_ROLE, msg.sender)) {
revert CallerIsNotSuperKeeper(msg.sender);
}
_;
}
/**
* @notice Modifier to restrict access to curators only
* @param fleetAddress The address of the fleet to check the curator role for
* @dev Checks if the caller has the contract-specific CURATOR_ROLE
*/
modifier onlyCurator(address fleetAddress) {
if (
fleetAddress == address(0) ||
!_accessManager.hasRole(
generateRole(ContractSpecificRoles.CURATOR_ROLE, fleetAddress),
msg.sender
)
) {
revert CallerIsNotCurator(msg.sender);
}
_;
}
/**
* @notice Modifier to restrict access to guardians only
* @dev Modifier to check that the caller has the Guardian role
* @custom:internal-logic
* - Checks if the caller has the GUARDIAN_ROLE in the access manager
* @custom:effects
* - Reverts if the caller doesn't have the GUARDIAN_ROLE
* - Allows the function to proceed if the caller has the role
* @custom:security-considerations
* - Ensures that only authorized guardians can access emergency functions
* - Relies on the correct setup of the access manager
*/
modifier onlyGuardian() {
if (!_accessManager.hasRole(GUARDIAN_ROLE, msg.sender)) {
revert CallerIsNotGuardian(msg.sender);
}
_;
}
/**
* @notice Modifier to restrict access to either guardians or governors
* @dev Modifier to check that the caller has either the Guardian or Governor role
* @custom:internal-logic
* - Checks if the caller has either the GUARDIAN_ROLE or the GOVERNOR_ROLE
* @custom:effects
* - Reverts if the caller doesn't have either of the required roles
* - Allows the function to proceed if the caller has one of the roles
* @custom:security-considerations
* - Ensures that only authorized guardians or governors can access certain functions
* - Provides flexibility for functions that can be accessed by either role
* @custom:gas-considerations
* - Performs two role checks, which may impact gas usage
*/
modifier onlyGuardianOrGovernor() {
if (
!_accessManager.hasRole(GUARDIAN_ROLE, msg.sender) &&
!_accessManager.hasRole(GOVERNOR_ROLE, msg.sender)
) {
revert CallerIsNotGuardianOrGovernor(msg.sender);
}
_;
}
/**
* @notice Modifier to restrict access to decay controllers only
*/
modifier onlyDecayController() {
if (!_accessManager.hasRole(DECAY_CONTROLLER_ROLE, msg.sender)) {
revert CallerIsNotDecayController(msg.sender);
}
_;
}
/**
* @notice Modifier to restrict access to foundation only
* @dev Modifier to check that the caller has the Foundation role
* @custom:security-considerations
* - Ensures that only the Foundation can access vesting and related functions
* - Relies on the correct setup of the access manager
*/
modifier onlyFoundation() {
if (
!_accessManager.hasRole(
_accessManager.FOUNDATION_ROLE(),
msg.sender
)
) {
revert CallerIsNotFoundation(msg.sender);
}
_;
}
/*//////////////////////////////////////////////////////////////
PUBLIC FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Generates a role identifier for a specific contract and role
* @param roleName The name of the role
* @param roleTargetContract The address of the contract the role is for
* @return The generated role identifier
* @dev This function is used to create unique role identifiers for contract-specific roles
*/
function generateRole(
ContractSpecificRoles roleName,
address roleTargetContract
) public pure returns (bytes32) {
return keccak256(abi.encodePacked(roleName, roleTargetContract));
}
/**
* @notice Checks if an account has the Admirals Quarters role
* @param account The address to check
* @return bool True if the account has the Admirals Quarters role
*/
function hasAdmiralsQuartersRole(
address account
) public view returns (bool) {
return _accessManager.hasRole(ADMIRALS_QUARTERS_ROLE, account);
}
/*//////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Helper function to check if an address has the Governor role
* @param account The address to check
* @return bool True if the address has the Governor role
*/
function _isGovernor(address account) internal view returns (bool) {
return _accessManager.hasRole(GOVERNOR_ROLE, account);
}
function _isDecayController(address account) internal view returns (bool) {
return _accessManager.hasRole(DECAY_CONTROLLER_ROLE, account);
}
/**
* @notice Helper function to check if an address has the Foundation role
* @param account The address to check
* @return bool True if the address has the Foundation role
*/
function _isFoundation(address account) internal view returns (bool) {
return
_accessManager.hasRole(_accessManager.FOUNDATION_ROLE(), account);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {ContractSpecificRoles, IProtocolAccessManager} from "../interfaces/IProtocolAccessManager.sol";
import {LimitedAccessControl} from "./LimitedAccessControl.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
/**
* @title ProtocolAccessManager
* @notice This contract is the central authority for access control within the protocol.
* It defines and manages various roles that govern different aspects of the system.
*
* @dev This contract extends LimitedAccessControl, which restricts direct role management.
* Roles are typically assigned during deployment or through governance proposals.
*
* The contract defines four main roles:
* 1. GOVERNOR_ROLE: System-wide administrators
* 2. KEEPER_ROLE: Routine maintenance operators
* 3. SUPER_KEEPER_ROLE: Advanced maintenance operators
* 4. COMMANDER_ROLE: Managers of specific protocol components (Arks)
* 5. ADMIRALS_QUARTERS_ROLE: Specific role for admirals quarters bundler contract
* Role Hierarchy and Management:
* - The GOVERNOR_ROLE is at the top of the hierarchy and can manage all other roles.
* - Other roles cannot manage roles directly due to LimitedAccessControl restrictions.
* - Role assignments are typically done through governance proposals or during initial setup.
*
* Usage in the System:
* - Other contracts in the system inherit from ProtocolAccessManaged, which checks permissions
* against this ProtocolAccessManager.
* - Critical functions in various contracts are protected by role-based modifiers
* (e.g., onlyGovernor, onlyKeeper, etc.) which query this contract for permissions.
*
* Security Considerations:
* - The GOVERNOR_ROLE has significant power and should be managed carefully, potentially
* through a multi-sig wallet or governance contract.
* - The SUPER_KEEPER_ROLE has elevated privileges and should be assigned judiciously.
* - The COMMANDER_ROLE is not directly manageable through this contract but is used
* in other parts of the system for specific access control.
*/
contract ProtocolAccessManager is IProtocolAccessManager, LimitedAccessControl {
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @notice Role identifier for protocol governors - highest privilege level with admin capabilities
bytes32 public constant GOVERNOR_ROLE = keccak256("GOVERNOR_ROLE");
/// @notice Role identifier for super keepers who can globally perform fleet maintanence roles
bytes32 public constant SUPER_KEEPER_ROLE = keccak256("SUPER_KEEPER_ROLE");
/**
* @notice Role identifier for protocol guardians
* @dev Guardians have emergency powers across multiple protocol components:
* - Can pause/unpause Fleet operations for security
* - Can pause/unpause TipJar operations
* - Can cancel governance proposals on SummerGovernor even if they don't meet normal cancellation requirements
* - Can cancel TipJar proposals
*
* The guardian role serves as an emergency backstop to protect the protocol, but with less
* privilege than governors.
*/
bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE");
/**
* @notice Role identifier for decay controller
* @dev This role allows the decay controller to manage the decay of user voting power
*/
bytes32 public constant DECAY_CONTROLLER_ROLE =
keccak256("DECAY_CONTROLLER_ROLE");
/**
* @notice Role identifier for admirals quarters bundler contract
* @dev This role allows Admirals Quarters to unstake and withdraw assets from fleets, on behalf of users
* @dev Withdrawn tokens go straight to users wallet, lowering the risk of manipulation if the role is compromised
*/
bytes32 public constant ADMIRALS_QUARTERS_ROLE =
keccak256("ADMIRALS_QUARTERS_ROLE");
/// @notice Minimum allowed guardian expiration period (7 days)
uint256 public constant MIN_GUARDIAN_EXPIRY = 7 days;
/// @notice Maximum allowed guardian expiration period (180 days)
uint256 public constant MAX_GUARDIAN_EXPIRY = 180 days;
/// @notice Role identifier for the Foundation which manages vesting wallets and related operations
bytes32 public constant FOUNDATION_ROLE = keccak256("FOUNDATION_ROLE");
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/**
* @notice Initializes the ProtocolAccessManager contract
* @param governor Address of the initial governor
* @dev Grants the governor address the GOVERNOR_ROLE
*/
constructor(address governor) {
_grantRole(GOVERNOR_ROLE, governor);
}
/**
* @dev Modifier to check that the caller has the Governor role
*/
modifier onlyGovernor() {
if (!hasRole(GOVERNOR_ROLE, msg.sender)) {
revert CallerIsNotGovernor(msg.sender);
}
_;
}
/*//////////////////////////////////////////////////////////////
PUBLIC FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Checks if the contract supports a given interface
* @dev Overrides the supportsInterface function from AccessControl
* @param interfaceId The interface identifier, as specified in ERC-165
* @return bool True if the contract supports the interface, false otherwise
*
* This function supports:
* - IProtocolAccessManager interface
* - All interfaces supported by the parent AccessControl contract
*/
function supportsInterface(
bytes4 interfaceId
) public view override returns (bool) {
return
interfaceId == type(IProtocolAccessManager).interfaceId ||
super.supportsInterface(interfaceId);
}
/// @inheritdoc IProtocolAccessManager
function grantGovernorRole(address account) external onlyGovernor {
_grantRole(GOVERNOR_ROLE, account);
}
/// @inheritdoc IProtocolAccessManager
function revokeGovernorRole(address account) external onlyGovernor {
_revokeRole(GOVERNOR_ROLE, account);
}
/*//////////////////////////////////////////////////////////////
EXTERNAL GOVERNOR FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IProtocolAccessManager
function grantSuperKeeperRole(address account) external onlyGovernor {
_grantRole(SUPER_KEEPER_ROLE, account);
}
/// @inheritdoc IProtocolAccessManager
function grantGuardianRole(address account) external onlyGovernor {
_grantRole(GUARDIAN_ROLE, account);
}
/// @inheritdoc IProtocolAccessManager
function revokeGuardianRole(address account) external onlyGovernor {
_revokeRole(GUARDIAN_ROLE, account);
}
/// @inheritdoc IProtocolAccessManager
function revokeSuperKeeperRole(address account) external onlyGovernor {
_revokeRole(SUPER_KEEPER_ROLE, account);
}
/// @inheritdoc IProtocolAccessManager
function grantContractSpecificRole(
ContractSpecificRoles roleName,
address roleTargetContract,
address roleOwner
) public onlyGovernor {
bytes32 role = generateRole(roleName, roleTargetContract);
_grantRole(role, roleOwner);
}
/// @inheritdoc IProtocolAccessManager
function revokeContractSpecificRole(
ContractSpecificRoles roleName,
address roleTargetContract,
address roleOwner
) public onlyGovernor {
bytes32 role = generateRole(roleName, roleTargetContract);
_revokeRole(role, roleOwner);
}
/// @inheritdoc IProtocolAccessManager
function grantCuratorRole(
address fleetCommanderAddress,
address account
) public onlyGovernor {
grantContractSpecificRole(
ContractSpecificRoles.CURATOR_ROLE,
fleetCommanderAddress,
account
);
}
/// @inheritdoc IProtocolAccessManager
function revokeCuratorRole(
address fleetCommanderAddress,
address account
) public onlyGovernor {
revokeContractSpecificRole(
ContractSpecificRoles.CURATOR_ROLE,
fleetCommanderAddress,
account
);
}
/// @inheritdoc IProtocolAccessManager
function grantKeeperRole(
address fleetCommanderAddress,
address account
) public onlyGovernor {
grantContractSpecificRole(
ContractSpecificRoles.KEEPER_ROLE,
fleetCommanderAddress,
account
);
}
/// @inheritdoc IProtocolAccessManager
function revokeKeeperRole(
address fleetCommanderAddress,
address account
) public onlyGovernor {
revokeContractSpecificRole(
ContractSpecificRoles.KEEPER_ROLE,
fleetCommanderAddress,
account
);
}
/// @inheritdoc IProtocolAccessManager
function grantCommanderRole(
address arkAddress,
address account
) public onlyGovernor {
grantContractSpecificRole(
ContractSpecificRoles.COMMANDER_ROLE,
arkAddress,
account
);
}
/// @inheritdoc IProtocolAccessManager
function revokeCommanderRole(
address arkAddress,
address account
) public onlyGovernor {
revokeContractSpecificRole(
ContractSpecificRoles.COMMANDER_ROLE,
arkAddress,
account
);
}
/// @inheritdoc IProtocolAccessManager
function grantDecayControllerRole(address account) public onlyGovernor {
_grantRole(DECAY_CONTROLLER_ROLE, account);
}
/// @inheritdoc IProtocolAccessManager
function revokeDecayControllerRole(address account) public onlyGovernor {
_revokeRole(DECAY_CONTROLLER_ROLE, account);
}
/*//////////////////////////////////////////////////////////////
PUBLIC FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IProtocolAccessManager
function selfRevokeContractSpecificRole(
ContractSpecificRoles roleName,
address roleTargetContract
) public {
bytes32 role = generateRole(roleName, roleTargetContract);
if (!hasRole(role, msg.sender)) {
revert CallerIsNotContractSpecificRole(msg.sender, role);
}
_revokeRole(role, msg.sender);
}
/// @inheritdoc IProtocolAccessManager
function generateRole(
ContractSpecificRoles roleName,
address roleTargetContract
) public pure returns (bytes32) {
return keccak256(abi.encodePacked(roleName, roleTargetContract));
}
/// @inheritdoc IProtocolAccessManager
function grantAdmiralsQuartersRole(
address account
) external onlyRole(GOVERNOR_ROLE) {
_grantRole(ADMIRALS_QUARTERS_ROLE, account);
}
/// @inheritdoc IProtocolAccessManager
function revokeAdmiralsQuartersRole(
address account
) external onlyRole(GOVERNOR_ROLE) {
_revokeRole(ADMIRALS_QUARTERS_ROLE, account);
}
mapping(address guardian => uint256 expirationTimestamp)
public guardianExpirations;
/**
* @notice Checks if an account is an active guardian (has role and not expired)
* @param account Address to check
* @return bool True if account is an active guardian
*/
function isActiveGuardian(address account) public view returns (bool) {
return
hasRole(GUARDIAN_ROLE, account) &&
guardianExpirations[account] > block.timestamp;
}
/**
* @notice Sets the expiration timestamp for a guardian
* @param account Guardian address
* @param expiration Timestamp when guardian powers expire
* @dev The expiration period (time from now until expiration) must be between MIN_GUARDIAN_EXPIRY and MAX_GUARDIAN_EXPIRY
* This ensures guardians can't be immediately removed (protecting against malicious proposals) while still
* allowing for their eventual phase-out (protecting against malicious guardians)
*/
function setGuardianExpiration(
address account,
uint256 expiration
) external onlyRole(GOVERNOR_ROLE) {
if (!hasRole(GUARDIAN_ROLE, account)) {
revert CallerIsNotGuardian(account);
}
uint256 expiryPeriod = expiration - block.timestamp;
if (
expiryPeriod < MIN_GUARDIAN_EXPIRY ||
expiryPeriod > MAX_GUARDIAN_EXPIRY
) {
revert InvalidGuardianExpiryPeriod(
expiryPeriod,
MIN_GUARDIAN_EXPIRY,
MAX_GUARDIAN_EXPIRY
);
}
guardianExpirations[account] = expiration;
emit GuardianExpirationSet(account, expiration);
}
/**
* @inheritdoc IProtocolAccessManager
*/
function hasRole(
bytes32 role,
address account
)
public
view
virtual
override(IProtocolAccessManager, AccessControl)
returns (bool)
{
return super.hasRole(role, account);
}
/// @inheritdoc IProtocolAccessManager
function getGuardianExpiration(
address account
) external view returns (uint256 expiration) {
if (!hasRole(GUARDIAN_ROLE, account)) {
revert CallerIsNotGuardian(account);
}
return guardianExpirations[account];
}
/// @inheritdoc IProtocolAccessManager
function grantFoundationRole(address account) external onlyGovernor {
_grantRole(FOUNDATION_ROLE, account);
}
/// @inheritdoc IProtocolAccessManager
function revokeFoundationRole(address account) external onlyGovernor {
_revokeRole(FOUNDATION_ROLE, account);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title IAccessControlErrors
* @dev This file contains custom error definitions for access control in the system.
* @notice These custom errors provide more gas-efficient and informative error handling
* compared to traditional require statements with string messages.
*/
interface IAccessControlErrors {
/**
* @notice Thrown when a caller does not have the required role.
*/
error CallerIsNotContractSpecificRole(address caller, bytes32 role);
/**
* @notice Thrown when a caller is not the curator.
*/
error CallerIsNotCurator(address caller);
/**
* @notice Thrown when a caller is not the governor.
*/
error CallerIsNotGovernor(address caller);
/**
* @notice Thrown when a caller is not a keeper.
*/
error CallerIsNotKeeper(address caller);
/**
* @notice Thrown when a caller is not a super keeper.
*/
error CallerIsNotSuperKeeper(address caller);
/**
* @notice Thrown when a caller is not the commander.
*/
error CallerIsNotCommander(address caller);
/**
* @notice Thrown when a caller is neither the Raft nor the commander.
*/
error CallerIsNotRaftOrCommander(address caller);
/**
* @notice Thrown when a caller is not the Raft.
*/
error CallerIsNotRaft(address caller);
/**
* @notice Thrown when a caller is not an admin.
*/
error CallerIsNotAdmin(address caller);
/**
* @notice Thrown when a caller is not the guardian.
*/
error CallerIsNotGuardian(address caller);
/**
* @notice Thrown when a caller is not the guardian or governor.
*/
error CallerIsNotGuardianOrGovernor(address caller);
/**
* @notice Thrown when a caller is not the decay controller.
*/
error CallerIsNotDecayController(address caller);
/**
* @notice Thrown when a caller is not authorized to board.
*/
error CallerIsNotAuthorizedToBoard(address caller);
/**
* @notice Thrown when direct grant is disabled.
*/
error DirectGrantIsDisabled(address caller);
/**
* @notice Thrown when direct revoke is disabled.
*/
error DirectRevokeIsDisabled(address caller);
/**
* @notice Thrown when an invalid access manager address is provided.
*/
error InvalidAccessManagerAddress(address invalidAddress);
/**
* @notice Error thrown when a caller is not the Foundation
* @param caller The address that attempted the operation
*/
error CallerIsNotFoundation(address caller);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
/**
* @dev Dynamic roles are roles that are not hardcoded in the contract but are defined by the protocol
* Members of this enum are treated as prefixes to the role generated using prefix and target contract address
* e.g generateRole(ContractSpecificRoles.CURATOR_ROLE, address(this)) for FleetCommander, to generate the CURATOR_ROLE
* for the curator of the FleetCommander contract
*/
enum ContractSpecificRoles {
CURATOR_ROLE,
KEEPER_ROLE,
COMMANDER_ROLE
}
/**
* @title IProtocolAccessManager
* @notice Defines system roles and provides role based remote-access control for
* contracts that inherit from ProtocolAccessManaged contract
*/
interface IProtocolAccessManager {
/**
* @notice Grants the Governor role to a given account
*
* @param account The account to which the Governor role will be granted
*/
function grantGovernorRole(address account) external;
/**
* @notice Revokes the Governor role from a given account
*
* @param account The account from which the Governor role will be revoked
*/
function revokeGovernorRole(address account) external;
/**
* @notice Grants the Super Keeper role to a given account
*
* @param account The account to which the Super Keeper role will be granted
*/
function grantSuperKeeperRole(address account) external;
/**
* @notice Revokes the Super Keeper role from a given account
*
* @param account The account from which the Super Keeper role will be revoked
*/
function revokeSuperKeeperRole(address account) external;
/**
* @dev Generates a unique role identifier based on the role name and target contract address
* @param roleName The name of the role (from ContractSpecificRoles enum)
* @param roleTargetContract The address of the contract the role is for
* @return bytes32 The generated role identifier
* @custom:internal-logic
* - Combines the roleName and roleTargetContract using abi.encodePacked
* - Applies keccak256 hash function to generate a unique bytes32 identifier
* @custom:effects
* - Does not modify any state, pure function
* @custom:security-considerations
* - Ensures unique role identifiers for different contracts
* - Relies on the uniqueness of contract addresses and role names
*/
function generateRole(
ContractSpecificRoles roleName,
address roleTargetContract
) external pure returns (bytes32);
/**
* @notice Grants a contract specific role to a given account
* @param roleName The name of the role to grant
* @param roleTargetContract The address of the contract to grant the role for
* @param account The account to which the role will be granted
*/
function grantContractSpecificRole(
ContractSpecificRoles roleName,
address roleTargetContract,
address account
) external;
/**
* @notice Revokes a contract specific role from a given account
* @param roleName The name of the role to revoke
* @param roleTargetContract The address of the contract to revoke the role for
* @param account The account from which the role will be revoked
*/
function revokeContractSpecificRole(
ContractSpecificRoles roleName,
address roleTargetContract,
address account
) external;
/**
* @notice Grants the Curator role to a given account
* @param fleetCommanderAddress The address of the fleet commander to grant the role for
* @param account The account to which the role will be granted
*/
function grantCuratorRole(
address fleetCommanderAddress,
address account
) external;
/**
* @notice Revokes the Curator role from a given account
* @param fleetCommanderAddress The address of the fleet commander to revoke the role for
* @param account The account from which the role will be revoked
*/
function revokeCuratorRole(
address fleetCommanderAddress,
address account
) external;
/**
* @notice Grants the Keeper role to a given account
* @param fleetCommanderAddress The address of the fleet commander to grant the role for
* @param account The account to which the role will be granted
*/
function grantKeeperRole(
address fleetCommanderAddress,
address account
) external;
/**
* @notice Revokes the Keeper role from a given account
* @param fleetCommanderAddress The address of the fleet commander to revoke the role for
* @param account The account from which the role will be revoked
*/
function revokeKeeperRole(
address fleetCommanderAddress,
address account
) external;
/**
* @notice Grants the Commander role for a specific Ark
* @param arkAddress Address of the Ark contract
* @param account Address to grant the Commander role to
*/
function grantCommanderRole(address arkAddress, address account) external;
/**
* @notice Revokes the Commander role for a specific Ark
* @param arkAddress Address of the Ark contract
* @param account Address to revoke the Commander role from
*/
function revokeCommanderRole(address arkAddress, address account) external;
/**
* @notice Revokes a contract specific role from the caller
* @param roleName The name of the role to revoke
* @param roleTargetContract The address of the contract to revoke the role for
*/
function selfRevokeContractSpecificRole(
ContractSpecificRoles roleName,
address roleTargetContract
) external;
/**
* @notice Grants the Guardian role to a given account
*
* @param account The account to which the Guardian role will be granted
*/
function grantGuardianRole(address account) external;
/**
* @notice Revokes the Guardian role from a given account
*
* @param account The account from which the Guardian role will be revoked
*/
function revokeGuardianRole(address account) external;
/**
* @notice Grants the Decay Controller role to a given account
* @param account The account to which the Decay Controller role will be granted
*/
function grantDecayControllerRole(address account) external;
/**
* @notice Revokes the Decay Controller role from a given account
* @param account The account from which the Decay Controller role will be revoked
*/
function revokeDecayControllerRole(address account) external;
/**
* @notice Grants the ADMIRALS_QUARTERS_ROLE to an address
* @param account The address to grant the role to
*/
function grantAdmiralsQuartersRole(address account) external;
/**
* @notice Revokes the ADMIRALS_QUARTERS_ROLE from an address
* @param account The address to revoke the role from
*/
function revokeAdmiralsQuartersRole(address account) external;
/*//////////////////////////////////////////////////////////////
ROLE CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @notice Role identifier for the Governor role
function GOVERNOR_ROLE() external pure returns (bytes32);
/// @notice Role identifier for the Guardian role
function GUARDIAN_ROLE() external pure returns (bytes32);
/// @notice Role identifier for the Super Keeper role
function SUPER_KEEPER_ROLE() external pure returns (bytes32);
/// @notice Role identifier for the Decay Controller role
function DECAY_CONTROLLER_ROLE() external pure returns (bytes32);
/// @notice Role identifier for the Admirals Quarters role
function ADMIRALS_QUARTERS_ROLE() external pure returns (bytes32);
/// @notice Role identifier for the Foundation, responsible for managing vesting wallets and related operations
function FOUNDATION_ROLE() external pure returns (bytes32);
/**
* @notice Checks if an account has a specific role
* @param role The role identifier to check
* @param account The account to check the role for
* @return bool True if the account has the role, false otherwise
*/
function hasRole(
bytes32 role,
address account
) external view returns (bool);
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/**
* @notice Emitted when a guardian's expiration is set
* @param account The address of the guardian
* @param expiration The timestamp until which the guardian powers are valid
*/
event GuardianExpirationSet(address indexed account, uint256 expiration);
/*//////////////////////////////////////////////////////////////
GUARDIAN FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Checks if an account is an active guardian (has role and not expired)
* @param account Address to check
* @return bool True if account is an active guardian
*/
function isActiveGuardian(address account) external view returns (bool);
/**
* @notice Sets the expiration timestamp for a guardian
* @param account Guardian address
* @param expiration Timestamp when guardian powers expire
*/
function setGuardianExpiration(
address account,
uint256 expiration
) external;
/**
* @notice Gets the expiration timestamp for a guardian
* @param account Guardian address
* @return uint256 Timestamp when guardian powers expire
*/
function guardianExpirations(
address account
) external view returns (uint256);
/**
* @notice Gets the expiration timestamp for a guardian
* @param account Guardian address
* @return expiration Timestamp when guardian powers expire
*/
function getGuardianExpiration(
address account
) external view returns (uint256 expiration);
/**
* @notice Emitted when an invalid guardian expiry period is set
* @param expiryPeriod The expiry period that was set
* @param minExpiryPeriod The minimum allowed expiry period
* @param maxExpiryPeriod The maximum allowed expiry period
*/
error InvalidGuardianExpiryPeriod(
uint256 expiryPeriod,
uint256 minExpiryPeriod,
uint256 maxExpiryPeriod
);
/**
* @notice Grants the Foundation role to a given account. The Foundation is responsible for
* managing vesting wallets and related operations.
* @param account The account to which the Foundation role will be granted
*/
function grantFoundationRole(address account) external;
/**
* @notice Revokes the Foundation role from a given account
* @param account The account from which the Foundation role will be revoked
*/
function revokeFoundationRole(address account) external;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IConfigurationManaged} from "../interfaces/IConfigurationManaged.sol";
import {IConfigurationManager} from "../interfaces/IConfigurationManager.sol";
/**
* @title ConfigurationManaged
* @notice Base contract for contracts that need to read from the ConfigurationManager
* @custom:see IConfigurationManaged
*/
abstract contract ConfigurationManaged is IConfigurationManaged {
IConfigurationManager public immutable configurationManager;
/**
* @notice Constructs the ConfigurationManaged contract
* @param _configurationManager The address of the ConfigurationManager contract
*/
constructor(address _configurationManager) {
if (_configurationManager == address(0)) {
revert ConfigurationManagerZeroAddress();
}
configurationManager = IConfigurationManager(_configurationManager);
}
/// @inheritdoc IConfigurationManaged
function raft() public view virtual returns (address) {
return configurationManager.raft();
}
/// @inheritdoc IConfigurationManaged
function tipJar() public view virtual returns (address) {
return configurationManager.tipJar();
}
/// @inheritdoc IConfigurationManaged
function treasury() public view virtual returns (address) {
return configurationManager.treasury();
}
/// @inheritdoc IConfigurationManaged
function harborCommand() public view virtual returns (address) {
return configurationManager.harborCommand();
}
/// @inheritdoc IConfigurationManaged
function fleetCommanderRewardsManagerFactory()
public
view
virtual
returns (address)
{
return configurationManager.fleetCommanderRewardsManagerFactory();
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title IConfigurationManagerErrors
* @dev This file contains custom error definitions for the ConfigurationManager contract.
* @notice These custom errors provide more gas-efficient and informative error handling
* compared to traditional require statements with string messages.
*/
interface IConfigurationManagerErrors {
/**
* @notice Thrown when ConfigurationManager was already initialized.
*/
error ConfigurationManagerAlreadyInitialized();
/**
* @notice Thrown when the Raft address is not set.
*/
error RaftNotSet();
/**
* @notice Thrown when the TipJar address is not set.
*/
error TipJarNotSet();
/**
* @notice Thrown when the Treasury address is not set.
*/
error TreasuryNotSet();
/**
* @notice Thrown when constructor address is set to the zero address.
*/
error AddressZero();
/**
* @notice Thrown when the HarborCommand address is not set.
*/
error HarborCommandNotSet();
/**
* @notice Thrown when a feature is not supported.
*/
error NotSupported();
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title IConfigurationManagerEvents
* @notice Interface for events emitted by the Configuration Manager
*/
interface IConfigurationManagerEvents {
/**
* @notice Emitted when the Raft address is updated
* @param newRaft The address of the new Raft
*/
event RaftUpdated(address oldRaft, address newRaft);
/**
* @notice Emitted when the tip jar address is updated
* @param newTipJar The address of the new tip jar
*/
event TipJarUpdated(address oldTipJar, address newTipJar);
/**
* @notice Emitted when the tip rate is updated
* @param newTipRate The new tip rate value
*/
event TipRateUpdated(uint8 oldTipRate, uint8 newTipRate);
/**
* @notice Emitted when the Treasury address is updated
* @param newTreasury The address of the new Treasury
*/
event TreasuryUpdated(address oldTreasury, address newTreasury);
/**
* @notice Emitted when the Harbor Command address is updated
* @param oldHarborCommand The address of the old Harbor Command
* @param newHarborCommand The address of the new Harbor Command
*/
event HarborCommandUpdated(
address oldHarborCommand,
address newHarborCommand
);
/**
* @notice Emitted when the Fleet Commander Rewards Manager Factory address is updated
* @param oldFleetCommanderRewardsManagerFactory The address of the old Fleet Commander Rewards Manager Factory
* @param newFleetCommanderRewardsManagerFactory The address of the new Fleet Commander Rewards Manager Factory
*/
event FleetCommanderRewardsManagerFactoryUpdated(
address oldFleetCommanderRewardsManagerFactory,
address newFleetCommanderRewardsManagerFactory
);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IConfigurationManager} from "./IConfigurationManager.sol";
/**
* @title IConfigurationManaged
* @notice Interface for contracts that need to read from the ConfigurationManager
* @dev This interface defines the standard methods for accessing configuration values
* from the ConfigurationManager. It should be implemented by contracts that
* need to read these configurations.
*/
interface IConfigurationManaged {
/**
* @notice Gets the address of the ConfigurationManager contract
* @return The address of the ConfigurationManager contract
*/
function configurationManager()
external
view
returns (IConfigurationManager);
/**
* @notice Gets the address of the Raft contract
* @return The address of the Raft contract
*/
function raft() external view returns (address);
/**
* @notice Gets the address of the TipJar contract
* @return The address of the TipJar contract
*/
function tipJar() external view returns (address);
/**
* @notice Gets the address of the Treasury contract
* @return The address of the Treasury contract
*/
function treasury() external view returns (address);
/**
* @notice Gets the address of the HarborCommand contract
* @return The address of the HarborCommand contract
*/
function harborCommand() external view returns (address);
/**
* @notice Gets the address of the Fleet Commander Rewards Manager Factory contract
* @return The address of the Fleet Commander Rewards Manager Factory contract
*/
function fleetCommanderRewardsManagerFactory()
external
view
returns (address);
error ConfigurationManagerZeroAddress();
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IConfigurationManagerErrors} from "../errors/IConfigurationManagerErrors.sol";
import {IConfigurationManagerEvents} from "../events/IConfigurationManagerEvents.sol";
import {ConfigurationManagerParams} from "../types/ConfigurationManagerTypes.sol";
/**
* @title IConfigurationManager
* @notice Interface for the ConfigurationManager contract, which manages system-wide parameters
* @dev This interface defines the getters and setters for system-wide parameters
*/
interface IConfigurationManager is
IConfigurationManagerEvents,
IConfigurationManagerErrors
{
/**
* @notice Initialize the configuration with the given parameters
* @param params The parameters to initialize the configuration with
* @dev Can only be called by the governor
*/
function initializeConfiguration(
ConfigurationManagerParams memory params
) external;
/**
* @notice Get the address of the Raft contract
* @return The address of the Raft contract
* @dev This is where rewards and farmed tokens are sent for processing
*/
function raft() external view returns (address);
/**
* @notice Get the current tip jar address
* @return The current tip jar address
* @dev This is the contract that owns tips and is responsible for
* dispensing them to claimants
*/
function tipJar() external view returns (address);
/**
* @notice Get the current treasury address
* @return The current treasury address
* @dev This is the contract that owns the treasury and is responsible for
* dispensing funds to the protocol's operations
*/
function treasury() external view returns (address);
/**
* @notice Get the address of theHarbor command
* @return The address of theHarbor command
* @dev This is the contract that's the registry of all Fleet Commanders
*/
function harborCommand() external view returns (address);
/**
* @notice Get the address of the Fleet Commander Rewards Manager Factory contract
* @return The address of the Fleet Commander Rewards Manager Factory contract
*/
function fleetCommanderRewardsManagerFactory()
external
view
returns (address);
/**
* @notice Set a new address for the Raft contract
* @param newRaft The new address for the Raft contract
* @dev Can only be called by the governor
*/
function setRaft(address newRaft) external;
/**
* @notice Set a new tip ar address
* @param newTipJar The address of the new tip jar
* @dev Can only be called by the governor
*/
function setTipJar(address newTipJar) external;
/**
* @notice Set a new treasury address
* @param newTreasury The address of the new treasury
* @dev Can only be called by the governor
*/
function setTreasury(address newTreasury) external;
/**
* @notice Set a new harbor command address
* @param newHarborCommand The address of the new harbor command
* @dev Can only be called by the governor
*/
function setHarborCommand(address newHarborCommand) external;
/**
* @notice Set a new fleet commander rewards manager factory address
* @param newFleetCommanderRewardsManagerFactory The address of the new fleet commander rewards manager factory
* @dev Can only be called by the governor
*/
function setFleetCommanderRewardsManagerFactory(
address newFleetCommanderRewardsManagerFactory
) external;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @notice Initialization parameters for the ConfigurationManager contract
*/
struct ConfigurationManagerParams {
address raft;
address tipJar;
address treasury;
address harborCommand;
address fleetCommanderRewardsManagerFactory;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
library Constants {
// WAD: Common unit, stands for "18 decimals"
uint256 public constant WAD = 1e18;
// RAY: Higher precision unit, "27 decimals"
uint256 public constant RAY = 1e27;
// Conversion factor from WAD to RAY
uint256 public constant WAD_TO_RAY = 1e9;
// Number of seconds in a day
uint256 public constant SECONDS_PER_DAY = 1 days;
// Number of seconds in a year (assuming 365 days)
uint256 public constant SECONDS_PER_YEAR = 365 days;
// Maximum value for uint256
uint256 public constant MAX_UINT256 = type(uint256).max;
// AAVE V3 POOL CONFIG DATA MASK
uint256 internal constant ACTIVE_MASK =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF;
uint256 internal constant FROZEN_MASK =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF;
uint256 internal constant PAUSED_MASK =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFF;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title Percentage
* @author Roberto Cano
* @notice Custom type for Percentage values with associated utility functions
* @dev This contract defines a custom Percentage type and overloaded operators
* to perform arithmetic and comparison operations on Percentage values.
*/
/**
* @dev Custom percentage type as uint256
* @notice This type is used to represent percentage values with high precision
*/
type Percentage is uint256;
/**
* @dev Overridden operators declaration for Percentage
* @notice These operators allow for intuitive arithmetic and comparison operations
* on Percentage values
*/
using {
add as +,
subtract as -,
multiply as *,
divide as /,
lessOrEqualThan as <=,
lessThan as <,
greaterOrEqualThan as >=,
greaterThan as >,
equalTo as ==
} for Percentage global;
/**
* @dev The number of decimals used for the percentage
* This constant defines the precision of the Percentage type
*/
uint256 constant PERCENTAGE_DECIMALS = 18;
/**
* @dev The factor used to scale the percentage
* This constant is used to convert between human-readable percentages
* and the internal representation
*/
uint256 constant PERCENTAGE_FACTOR = 10 ** PERCENTAGE_DECIMALS;
/**
* @dev Percentage of 100% with the given `PERCENTAGE_DECIMALS`
* This constant represents 100% in the Percentage type
*/
Percentage constant PERCENTAGE_100 = Percentage.wrap(100 * PERCENTAGE_FACTOR);
/**
* @dev Percentage of 1 with the given `PERCENTAGE_DECIMALS`
* This constant represents 1 in the Percentage type
*/
Percentage constant PERCENTAGE_1 = Percentage.wrap(PERCENTAGE_FACTOR);
/**
* OPERATOR FUNCTIONS
*/
/**
* @dev Adds two Percentage values
* @param a The first Percentage value
* @param b The second Percentage value
* @return The sum of a and b as a Percentage
*/
function add(Percentage a, Percentage b) pure returns (Percentage) {
return Percentage.wrap(Percentage.unwrap(a) + Percentage.unwrap(b));
}
/**
* @dev Subtracts one Percentage value from another
* @param a The Percentage value to subtract from
* @param b The Percentage value to subtract
* @return The difference between a and b as a Percentage
*/
function subtract(Percentage a, Percentage b) pure returns (Percentage) {
return Percentage.wrap(Percentage.unwrap(a) - Percentage.unwrap(b));
}
/**
* @dev Multiplies two Percentage values
* @param a The first Percentage value
* @param b The second Percentage value
* @return The product of a and b as a Percentage, scaled appropriately
*/
function multiply(Percentage a, Percentage b) pure returns (Percentage) {
return
Percentage.wrap(
(Percentage.unwrap(a) * Percentage.unwrap(b)) /
Percentage.unwrap(PERCENTAGE_100)
);
}
/**
* @dev Divides one Percentage value by another
* @param a The Percentage value to divide
* @param b The Percentage value to divide by
* @return The quotient of a divided by b as a Percentage, scaled appropriately
*/
function divide(Percentage a, Percentage b) pure returns (Percentage) {
return
Percentage.wrap(
(Percentage.unwrap(a) * Percentage.unwrap(PERCENTAGE_100)) /
Percentage.unwrap(b)
);
}
/**
* @dev Checks if one Percentage value is less than or equal to another
* @param a The first Percentage value
* @param b The second Percentage value
* @return True if a is less than or equal to b, false otherwise
*/
function lessOrEqualThan(Percentage a, Percentage b) pure returns (bool) {
return Percentage.unwrap(a) <= Percentage.unwrap(b);
}
/**
* @dev Checks if one Percentage value is less than another
* @param a The first Percentage value
* @param b The second Percentage value
* @return True if a is less than b, false otherwise
*/
function lessThan(Percentage a, Percentage b) pure returns (bool) {
return Percentage.unwrap(a) < Percentage.unwrap(b);
}
/**
* @dev Checks if one Percentage value is greater than or equal to another
* @param a The first Percentage value
* @param b The second Percentage value
* @return True if a is greater than or equal to b, false otherwise
*/
function greaterOrEqualThan(Percentage a, Percentage b) pure returns (bool) {
return Percentage.unwrap(a) >= Percentage.unwrap(b);
}
/**
* @dev Checks if one Percentage value is greater than another
* @param a The first Percentage value
* @param b The second Percentage value
* @return True if a is greater than b, false otherwise
*/
function greaterThan(Percentage a, Percentage b) pure returns (bool) {
return Percentage.unwrap(a) > Percentage.unwrap(b);
}
/**
* @dev Checks if two Percentage values are equal
* @param a The first Percentage value
* @param b The second Percentage value
* @return True if a is equal to b, false otherwise
*/
function equalTo(Percentage a, Percentage b) pure returns (bool) {
return Percentage.unwrap(a) == Percentage.unwrap(b);
}
/**
* @dev Alias for equalTo function
* @param a The first Percentage value
* @param b The second Percentage value
* @return True if a is equal to b, false otherwise
*/
function equals(Percentage a, Percentage b) pure returns (bool) {
return Percentage.unwrap(a) == Percentage.unwrap(b);
}
/**
* @dev Converts a uint256 value to a Percentage
* @param value The uint256 value to convert
* @return The input value as a Percentage
*/
function toPercentage(uint256 value) pure returns (Percentage) {
return Percentage.wrap(value * PERCENTAGE_FACTOR);
}
/**
* @dev Converts a Percentage value to a uint256
* @param value The Percentage value to convert
* @return The Percentage value as a uint256
*/
function fromPercentage(Percentage value) pure returns (uint256) {
return Percentage.unwrap(value) / PERCENTAGE_FACTOR;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {PERCENTAGE_100, PERCENTAGE_FACTOR, Percentage, toPercentage} from "./Percentage.sol";
/**
* @title PercentageUtils
* @author Roberto Cano
* @notice Utility library to apply percentage calculations to input amounts
* @dev This library provides functions for adding, subtracting, and applying
* percentages to amounts, as well as utility functions for working with
* percentages.
*/
library PercentageUtils {
/**
* @notice Adds the percentage to the given amount and returns the result
* @param amount The base amount to which the percentage will be added
* @param percentage The percentage to add to the amount
* @return The amount after the percentage is applied
* @dev It performs the following operation: (100.0% + percentage) * amount
*/
function addPercentage(
uint256 amount,
Percentage percentage
) internal pure returns (uint256) {
return applyPercentage(amount, PERCENTAGE_100 + percentage);
}
/**
* @notice Subtracts the percentage from the given amount and returns the result
* @param amount The base amount from which the percentage will be subtracted
* @param percentage The percentage to subtract from the amount
* @return The amount after the percentage is applied
* @dev It performs the following operation: (100.0% - percentage) * amount
*/
function subtractPercentage(
uint256 amount,
Percentage percentage
) internal pure returns (uint256) {
return applyPercentage(amount, PERCENTAGE_100 - percentage);
}
/**
* @notice Applies the given percentage to the given amount and returns the result
* @param amount The amount to apply the percentage to
* @param percentage The percentage to apply to the amount
* @return The amount after the percentage is applied
* @dev This function is used internally by addPercentage and subtractPercentage
*/
function applyPercentage(
uint256 amount,
Percentage percentage
) internal pure returns (uint256) {
return
(amount * Percentage.unwrap(percentage)) /
Percentage.unwrap(PERCENTAGE_100);
}
/**
* @notice Checks if the given percentage is in range, this is, if it is between 0 and 100
* @param percentage The percentage to check
* @return True if the percentage is in range, false otherwise
* @dev This function is useful for validating input percentages
*/
function isPercentageInRange(
Percentage percentage
) internal pure returns (bool) {
return percentage <= PERCENTAGE_100;
}
/**
* @notice Converts the given fraction into a percentage with the right number of decimals
* @param numerator The numerator of the fraction
* @param denominator The denominator of the fraction
* @return The percentage with `PERCENTAGE_DECIMALS` decimals
* @dev This function is useful for converting ratios to percentages
* For example, fromFraction(1, 2) returns 50%
*/
function fromFraction(
uint256 numerator,
uint256 denominator
) internal pure returns (Percentage) {
return
Percentage.wrap(
(numerator * PERCENTAGE_FACTOR * 100) / denominator
);
}
/**
* @notice Converts the given integer into a percentage
* @param percentage The percentage in human-readable format, i.e., 50 for 50%
* @return The percentage with `PERCENTAGE_DECIMALS` decimals
* @dev This function is useful for converting human-readable percentages to the internal representation
*/
function fromIntegerPercentage(
uint256 percentage
) internal pure returns (Percentage) {
return toPercentage(percentage);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IStakingRewardsManagerBaseErrors} from "./IStakingRewardsManagerBaseErrors.sol";
/* @title IStakingRewardsManagerBase
* @notice Interface for the Staking Rewards Manager contract
* @dev Manages staking and distribution of multiple reward tokens
*/
interface IStakingRewardsManagerBase is IStakingRewardsManagerBaseErrors {
// Views
/* @notice Get the total amount of staked tokens
* @return The total supply of staked tokens
*/
function totalSupply() external view returns (uint256);
/* @notice Get the staked balance of a specific account
* @param account The address of the account to check
* @return The staked balance of the account
*/
function balanceOf(address account) external view returns (uint256);
/* @notice Get the last time the reward was applicable for a specific reward token
* @param rewardToken The address of the reward token
* @return The timestamp of the last applicable reward time
*/
function lastTimeRewardApplicable(
address rewardToken
) external view returns (uint256);
/* @notice Get the reward per token for a specific reward token
* @param rewardToken The address of the reward token
* @return The reward amount per staked token (WAD-scaled)
* @dev Returns a WAD-scaled value (1e18) to maintain precision in calculations
* @dev This value represents: (rewardRate * timeElapsed * WAD) / totalSupply
*/
function rewardPerToken(
address rewardToken
) external view returns (uint256);
/* @notice Calculate the earned reward for an account and a specific reward token
* @param account The address of the account
* @param rewardToken The address of the reward token
* @return The amount of reward tokens earned (not WAD-scaled)
* @dev Calculated as: (balance * (rewardPerToken - userRewardPerTokenPaid)) / WAD + rewards
*/
function earned(
address account,
address rewardToken
) external view returns (uint256);
/* @notice Get the reward for the entire duration for a specific reward token
* @param rewardToken The address of the reward token
* @return The total reward amount for the duration (not WAD-scaled)
* @dev Calculated as: (rewardRate * rewardsDuration) / WAD
*/
function getRewardForDuration(
address rewardToken
) external view returns (uint256);
/* @notice Get the address of the staking token
* @return The address of the staking token
*/
function stakingToken() external view returns (address);
/* @notice Get the reward token at a specific index
* @param index The index of the reward token
* @return The address of the reward token
* @dev Reverts with IndexOutOfBounds if index >= rewardTokensLength()
*/
function rewardTokens(uint256 index) external view returns (address);
/* @notice Get the total number of reward tokens
* @return The length of the reward tokens list
*/
function rewardTokensLength() external view returns (uint256);
/* @notice Check if a token is in the list of reward tokens
* @param rewardToken The address to check
* @return bool True if the token is a reward token, false otherwise
*/
function isRewardToken(address rewardToken) external view returns (bool);
// Mutative functions
/* @notice Stake tokens for an account
* @param amount The amount of tokens to stake
*/
function stake(uint256 amount) external;
/* @notice Stake tokens for an account on behalf of another account
* @param receiver The address of the account to stake for
* @param amount The amount of tokens to stake
*/
function stakeOnBehalfOf(address receiver, uint256 amount) external;
/* @notice Unstake staked tokens on behalf of another account
* @param owner The address of the account to unstake from
* @param amount The amount of tokens to unstake
* @param claimRewards Whether to claim rewards before unstaking
*/
function unstakeAndWithdrawOnBehalfOf(
address owner,
uint256 amount,
bool claimRewards
) external;
/* @notice Unstake staked tokens
* @param amount The amount of tokens to unstake
*/
function unstake(uint256 amount) external;
/* @notice Claim accumulated rewards for all reward tokens */
function getReward() external;
/* @notice Claim accumulated rewards for a specific reward token
* @param rewardToken The address of the reward token to claim
*/
function getReward(address rewardToken) external;
/* @notice Withdraw all staked tokens and claim rewards */
function exit() external;
// Admin functions
/* @notice Notify the contract about new reward amount
* @param rewardToken The address of the reward token
* @param reward The amount of new reward (not WAD-scaled)
* @param newRewardsDuration The duration for rewards distribution (only used when adding a new reward token)
* @dev Internally sets rewardRate as (reward * WAD) / duration to maintain precision
*/
function notifyRewardAmount(
address rewardToken,
uint256 reward,
uint256 newRewardsDuration
) external;
/* @notice Set the duration for rewards distribution
* @param rewardToken The address of the reward token
* @param _rewardsDuration The new duration for rewards
*/
function setRewardsDuration(
address rewardToken,
uint256 _rewardsDuration
) external;
/* @notice Removes a reward token from the list of reward tokens
* @dev Can only be called by governor
* @dev Can only be called after reward period is complete
* @dev Can only be called if remaining balance is below dust threshold
* @dev Can be multi-called by governor preceded by rescueToken for each reward token
* @param rewardToken The address of the reward token to remove
*/
function removeRewardToken(address rewardToken) external;
/* @notice Rescues a token from the contract
* @dev Can only be called by governor
* @dev Can be multi-called by governor followed by removeRewardToken for each token
* @dev To clean the dust balance, call rescueToken for each token
* @param _token The address of the token to rescue
* @param _to The address to send the rescued tokens to
*/
function rescueToken(address _token, address _to) external;
// Events
/* @notice Emitted when a new reward is added
* @param rewardToken The address of the reward token
* @param reward The amount of reward added
*/
event RewardAdded(address indexed rewardToken, uint256 reward);
/* @notice Emitted when tokens are staked
* @param staker The address that provided the tokens for staking
* @param receiver The address whose staking balance was updated
* @param amount The amount of tokens added to the staking position
*/
event Staked(
address indexed staker,
address indexed receiver,
uint256 amount
);
/* @notice Emitted when tokens are unstaked
* @param staker The address whose tokens were unstaked
* @param receiver The address receiving the unstaked tokens
* @param amount The amount of tokens unstaked
*/
event Unstaked(
address indexed staker,
address indexed receiver,
uint256 amount
);
/* @notice Emitted when tokens are withdrawn
* @param user The address of the user that withdrew
* @param amount The amount of tokens withdrawn
*/
event Withdrawn(address indexed user, uint256 amount);
/* @notice Emitted when rewards are paid out
* @param user The address of the user receiving the reward
* @param rewardToken The address of the reward token
* @param reward The amount of reward paid
*/
event RewardPaid(
address indexed user,
address indexed rewardToken,
uint256 reward
);
/* @notice Emitted when the rewards duration is updated
* @param rewardToken The address of the reward token
* @param newDuration The new duration for rewards
*/
event RewardsDurationUpdated(
address indexed rewardToken,
uint256 newDuration
);
/* @notice Emitted when a new reward token is added
* @param rewardToken The address of the new reward token
* @param rewardsDuration The duration for the new reward token
*/
event RewardTokenAdded(address rewardToken, uint256 rewardsDuration);
/* @notice Emitted when a reward token is removed
* @param rewardToken The address of the reward token
*/
event RewardTokenRemoved(address rewardToken);
/* @notice Claims rewards for a specific account
* @param account The address to claim rewards for
*/
function getRewardFor(address account) external;
/* @notice Claims rewards for a specific account and specific reward token
* @param account The address to claim rewards for
* @param rewardToken The address of the reward token to claim
*/
function getRewardFor(address account, address rewardToken) external;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/* @title IStakingRewardsManagerBaseErrors
* @notice Interface defining custom errors for the Staking Rewards Manager
*/
interface IStakingRewardsManagerBaseErrors {
/* @notice Thrown when attempting to stake zero tokens */
error CannotStakeZero();
/* @notice Thrown when attempting to withdraw zero tokens */
error CannotWithdrawZero();
/* @notice Thrown when the provided reward amount is too high */
error ProvidedRewardTooHigh();
/* @notice Thrown when trying to set rewards before the current period is complete */
error RewardPeriodNotComplete();
/* @notice Thrown when there are no reward tokens set */
error NoRewardTokens();
/* @notice Thrown when trying to add a reward token that already exists */
error RewardTokenAlreadyExists();
/* @notice Thrown when setting an invalid rewards duration */
error InvalidRewardsDuration();
/* @notice Thrown when trying to interact with a reward token that hasn't been initialized */
error RewardTokenNotInitialized();
/* @notice Thrown when the reward amount is invalid for the given duration
* @param rewardToken The address of the reward token
* @param rewardsDuration The duration for which the reward is invalid
*/
error InvalidRewardAmount(address rewardToken, uint256 rewardsDuration);
/* @notice Thrown when trying to interact with the staking token before it's initialized */
error StakingTokenNotInitialized();
/* @notice Thrown when trying to remove a reward token that doesn't exist */
error RewardTokenDoesNotExist();
/* @notice Thrown when trying to change the rewards duration of a reward token */
error CannotChangeRewardsDuration();
/* @notice Thrown when a reward token still has a balance */
error RewardTokenStillHasBalance(uint256 balance);
/* @notice Thrown when the index is out of bounds */
error IndexOutOfBounds();
/* @notice Thrown when the rewards duration is zero */
error RewardsDurationCannotBeZero();
/* @notice Thrown when attempting to unstake zero tokens */
error CannotUnstakeZero();
/* @notice Thrown when the rewards duration is too long */
error RewardsDurationTooLong();
/**
* @notice Thrown when the receiver is the zero address
*/
error CannotStakeToZeroAddress();
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import {IMorpho, Id, MarketParams} from "morpho-blue/interfaces/IMorpho.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import {MarketConfig, PendingUint192, PendingAddress} from "../libraries/PendingLib.sol";
struct MarketAllocation {
/// @notice The market to allocate.
MarketParams marketParams;
/// @notice The amount of assets to allocate.
uint256 assets;
}
interface IMulticall {
function multicall(bytes[] calldata) external returns (bytes[] memory);
}
interface IOwnable {
function owner() external view returns (address);
function transferOwnership(address) external;
function renounceOwnership() external;
function acceptOwnership() external;
function pendingOwner() external view returns (address);
}
/// @dev This interface is used for factorizing IMetaMorphoStaticTyping and IMetaMorpho.
/// @dev Consider using the IMetaMorpho interface instead of this one.
interface IMetaMorphoBase {
/// @notice The address of the Morpho contract.
function MORPHO() external view returns (IMorpho);
function DECIMALS_OFFSET() external view returns (uint8);
/// @notice The address of the curator.
function curator() external view returns (address);
/// @notice Stores whether an address is an allocator or not.
function isAllocator(address target) external view returns (bool);
/// @notice The current guardian. Can be set even without the timelock set.
function guardian() external view returns (address);
/// @notice The current fee.
function fee() external view returns (uint96);
/// @notice The fee recipient.
function feeRecipient() external view returns (address);
/// @notice The skim recipient.
function skimRecipient() external view returns (address);
/// @notice The current timelock.
function timelock() external view returns (uint256);
/// @dev Stores the order of markets on which liquidity is supplied upon deposit.
/// @dev Can contain any market. A market is skipped as soon as its supply cap is reached.
function supplyQueue(uint256) external view returns (Id);
/// @notice Returns the length of the supply queue.
function supplyQueueLength() external view returns (uint256);
/// @dev Stores the order of markets from which liquidity is withdrawn upon withdrawal.
/// @dev Always contain all non-zero cap markets as well as all markets on which the vault supplies liquidity,
/// without duplicate.
function withdrawQueue(uint256) external view returns (Id);
/// @notice Returns the length of the withdraw queue.
function withdrawQueueLength() external view returns (uint256);
/// @notice Stores the total assets managed by this vault when the fee was last accrued.
/// @dev May be greater than `totalAssets()` due to removal of markets with non-zero supply or socialized bad debt.
/// This difference will decrease the fee accrued until one of the functions updating `lastTotalAssets` is
/// triggered (deposit/mint/withdraw/redeem/setFee/setFeeRecipient).
function lastTotalAssets() external view returns (uint256);
/// @notice Submits a `newTimelock`.
/// @dev Warning: Reverts if a timelock is already pending. Revoke the pending timelock to overwrite it.
/// @dev In case the new timelock is higher than the current one, the timelock is set immediately.
function submitTimelock(uint256 newTimelock) external;
/// @notice Accepts the pending timelock.
function acceptTimelock() external;
/// @notice Revokes the pending timelock.
/// @dev Does not revert if there is no pending timelock.
function revokePendingTimelock() external;
/// @notice Submits a `newSupplyCap` for the market defined by `marketParams`.
/// @dev Warning: Reverts if a cap is already pending. Revoke the pending cap to overwrite it.
/// @dev Warning: Reverts if a market removal is pending.
/// @dev In case the new cap is lower than the current one, the cap is set immediately.
function submitCap(MarketParams memory marketParams, uint256 newSupplyCap) external;
/// @notice Accepts the pending cap of the market defined by `marketParams`.
function acceptCap(MarketParams memory marketParams) external;
/// @notice Revokes the pending cap of the market defined by `id`.
/// @dev Does not revert if there is no pending cap.
function revokePendingCap(Id id) external;
/// @notice Submits a forced market removal from the vault, eventually losing all funds supplied to the market.
/// @notice Funds can be recovered by enabling this market again and withdrawing from it (using `reallocate`),
/// but funds will be distributed pro-rata to the shares at the time of withdrawal, not at the time of removal.
/// @notice This forced removal is expected to be used as an emergency process in case a market constantly reverts.
/// To softly remove a sane market, the curator role is expected to bundle a reallocation that empties the market
/// first (using `reallocate`), followed by the removal of the market (using `updateWithdrawQueue`).
/// @dev Warning: Removing a market with non-zero supply will instantly impact the vault's price per share.
/// @dev Warning: Reverts for non-zero cap or if there is a pending cap. Successfully submitting a zero cap will
/// prevent such reverts.
function submitMarketRemoval(MarketParams memory marketParams) external;
/// @notice Revokes the pending removal of the market defined by `id`.
/// @dev Does not revert if there is no pending market removal.
function revokePendingMarketRemoval(Id id) external;
/// @notice Submits a `newGuardian`.
/// @notice Warning: a malicious guardian could disrupt the vault's operation, and would have the power to revoke
/// any pending guardian.
/// @dev In case there is no guardian, the gardian is set immediately.
/// @dev Warning: Submitting a gardian will overwrite the current pending gardian.
function submitGuardian(address newGuardian) external;
/// @notice Accepts the pending guardian.
function acceptGuardian() external;
/// @notice Revokes the pending guardian.
function revokePendingGuardian() external;
/// @notice Skims the vault `token` balance to `skimRecipient`.
function skim(address) external;
/// @notice Sets `newAllocator` as an allocator or not (`newIsAllocator`).
function setIsAllocator(address newAllocator, bool newIsAllocator) external;
/// @notice Sets `curator` to `newCurator`.
function setCurator(address newCurator) external;
/// @notice Sets the `fee` to `newFee`.
function setFee(uint256 newFee) external;
/// @notice Sets `feeRecipient` to `newFeeRecipient`.
function setFeeRecipient(address newFeeRecipient) external;
/// @notice Sets `skimRecipient` to `newSkimRecipient`.
function setSkimRecipient(address newSkimRecipient) external;
/// @notice Sets `supplyQueue` to `newSupplyQueue`.
/// @param newSupplyQueue is an array of enabled markets, and can contain duplicate markets, but it would only
/// increase the cost of depositing to the vault.
function setSupplyQueue(Id[] calldata newSupplyQueue) external;
/// @notice Updates the withdraw queue. Some markets can be removed, but no market can be added.
/// @notice Removing a market requires the vault to have 0 supply on it, or to have previously submitted a removal
/// for this market (with the function `submitMarketRemoval`).
/// @notice Warning: Anyone can supply on behalf of the vault so the call to `updateWithdrawQueue` that expects a
/// market to be empty can be griefed by a front-run. To circumvent this, the allocator can simply bundle a
/// reallocation that withdraws max from this market with a call to `updateWithdrawQueue`.
/// @dev Warning: Removing a market with supply will decrease the fee accrued until one of the functions updating
/// `lastTotalAssets` is triggered (deposit/mint/withdraw/redeem/setFee/setFeeRecipient).
/// @dev Warning: `updateWithdrawQueue` is not idempotent. Submitting twice the same tx will change the queue twice.
/// @param indexes The indexes of each market in the previous withdraw queue, in the new withdraw queue's order.
function updateWithdrawQueue(uint256[] calldata indexes) external;
/// @notice Reallocates the vault's liquidity so as to reach a given allocation of assets on each given market.
/// @dev The behavior of the reallocation can be altered by state changes, including:
/// - Deposits on the vault that supplies to markets that are expected to be supplied to during reallocation.
/// - Withdrawals from the vault that withdraws from markets that are expected to be withdrawn from during
/// reallocation.
/// - Donations to the vault on markets that are expected to be supplied to during reallocation.
/// - Withdrawals from markets that are expected to be withdrawn from during reallocation.
/// @dev Sender is expected to pass `assets = type(uint256).max` with the last MarketAllocation of `allocations` to
/// supply all the remaining withdrawn liquidity, which would ensure that `totalWithdrawn` = `totalSupplied`.
/// @dev A supply in a reallocation step will make the reallocation revert if the amount is greater than the net
/// amount from previous steps (i.e. total withdrawn minus total supplied).
function reallocate(MarketAllocation[] calldata allocations) external;
}
/// @dev This interface is inherited by MetaMorpho so that function signatures are checked by the compiler.
/// @dev Consider using the IMetaMorpho interface instead of this one.
interface IMetaMorphoStaticTyping is IMetaMorphoBase {
/// @notice Returns the current configuration of each market.
function config(Id) external view returns (uint184 cap, bool enabled, uint64 removableAt);
/// @notice Returns the pending guardian.
function pendingGuardian() external view returns (address guardian, uint64 validAt);
/// @notice Returns the pending cap for each market.
function pendingCap(Id) external view returns (uint192 value, uint64 validAt);
/// @notice Returns the pending timelock.
function pendingTimelock() external view returns (uint192 value, uint64 validAt);
}
/// @title IMetaMorpho
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @dev Use this interface for MetaMorpho to have access to all the functions with the appropriate function signatures.
interface IMetaMorpho is IMetaMorphoBase, IERC4626, IERC20Permit, IOwnable, IMulticall {
/// @notice Returns the current configuration of each market.
function config(Id) external view returns (MarketConfig memory);
/// @notice Returns the pending guardian.
function pendingGuardian() external view returns (PendingAddress memory);
/// @notice Returns the pending cap for each market.
function pendingCap(Id) external view returns (PendingUint192 memory);
/// @notice Returns the pending timelock.
function pendingTimelock() external view returns (PendingUint192 memory);
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
struct MarketConfig {
/// @notice The maximum amount of assets that can be allocated to the market.
uint184 cap;
/// @notice Whether the market is in the withdraw queue.
bool enabled;
/// @notice The timestamp at which the market can be instantly removed from the withdraw queue.
uint64 removableAt;
}
struct PendingUint192 {
/// @notice The pending value to set.
uint192 value;
/// @notice The timestamp at which the pending value becomes valid.
uint64 validAt;
}
struct PendingAddress {
/// @notice The pending value to set.
address value;
/// @notice The timestamp at which the pending value becomes valid.
uint64 validAt;
}
/// @title PendingLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Library to manage pending values and their validity timestamp.
library PendingLib {
/// @dev Updates `pending`'s value to `newValue` and its corresponding `validAt` timestamp.
/// @dev Assumes `timelock` <= `MAX_TIMELOCK`.
function update(PendingUint192 storage pending, uint184 newValue, uint256 timelock) internal {
pending.value = newValue;
// Safe "unchecked" cast because timelock <= MAX_TIMELOCK.
pending.validAt = uint64(block.timestamp + timelock);
}
/// @dev Updates `pending`'s value to `newValue` and its corresponding `validAt` timestamp.
/// @dev Assumes `timelock` <= `MAX_TIMELOCK`.
function update(PendingAddress storage pending, address newValue, uint256 timelock) internal {
pending.value = newValue;
// Safe "unchecked" cast because timelock <= MAX_TIMELOCK.
pending.validAt = uint64(block.timestamp + timelock);
}
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
type Id is bytes32;
struct MarketParams {
address loanToken;
address collateralToken;
address oracle;
address irm;
uint256 lltv;
}
/// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest
/// accrual.
struct Position {
uint256 supplyShares;
uint128 borrowShares;
uint128 collateral;
}
/// @dev Warning: `totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `totalSupplyShares` does not contain the additional shares accrued by `feeRecipient` since the last
/// interest accrual.
struct Market {
uint128 totalSupplyAssets;
uint128 totalSupplyShares;
uint128 totalBorrowAssets;
uint128 totalBorrowShares;
uint128 lastUpdate;
uint128 fee;
}
struct Authorization {
address authorizer;
address authorized;
bool isAuthorized;
uint256 nonce;
uint256 deadline;
}
struct Signature {
uint8 v;
bytes32 r;
bytes32 s;
}
/// @dev This interface is used for factorizing IMorphoStaticTyping and IMorpho.
/// @dev Consider using the IMorpho interface instead of this one.
interface IMorphoBase {
/// @notice The EIP-712 domain separator.
/// @dev Warning: Every EIP-712 signed message based on this domain separator can be reused on another chain sharing
/// the same chain id because the domain separator would be the same.
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice The owner of the contract.
/// @dev It has the power to change the owner.
/// @dev It has the power to set fees on markets and set the fee recipient.
/// @dev It has the power to enable but not disable IRMs and LLTVs.
function owner() external view returns (address);
/// @notice The fee recipient of all markets.
/// @dev The recipient receives the fees of a given market through a supply position on that market.
function feeRecipient() external view returns (address);
/// @notice Whether the `irm` is enabled.
function isIrmEnabled(address irm) external view returns (bool);
/// @notice Whether the `lltv` is enabled.
function isLltvEnabled(uint256 lltv) external view returns (bool);
/// @notice Whether `authorized` is authorized to modify `authorizer`'s position on all markets.
/// @dev Anyone is authorized to modify their own positions, regardless of this variable.
function isAuthorized(address authorizer, address authorized) external view returns (bool);
/// @notice The `authorizer`'s current nonce. Used to prevent replay attacks with EIP-712 signatures.
function nonce(address authorizer) external view returns (uint256);
/// @notice Sets `newOwner` as `owner` of the contract.
/// @dev Warning: No two-step transfer ownership.
/// @dev Warning: The owner can be set to the zero address.
function setOwner(address newOwner) external;
/// @notice Enables `irm` as a possible IRM for market creation.
/// @dev Warning: It is not possible to disable an IRM.
function enableIrm(address irm) external;
/// @notice Enables `lltv` as a possible LLTV for market creation.
/// @dev Warning: It is not possible to disable a LLTV.
function enableLltv(uint256 lltv) external;
/// @notice Sets the `newFee` for the given market `marketParams`.
/// @param newFee The new fee, scaled by WAD.
/// @dev Warning: The recipient can be the zero address.
function setFee(MarketParams memory marketParams, uint256 newFee) external;
/// @notice Sets `newFeeRecipient` as `feeRecipient` of the fee.
/// @dev Warning: If the fee recipient is set to the zero address, fees will accrue there and will be lost.
/// @dev Modifying the fee recipient will allow the new recipient to claim any pending fees not yet accrued. To
/// ensure that the current recipient receives all due fees, accrue interest manually prior to making any changes.
function setFeeRecipient(address newFeeRecipient) external;
/// @notice Creates the market `marketParams`.
/// @dev Here is the list of assumptions on the market's dependencies (tokens, IRM and oracle) that guarantees
/// Morpho behaves as expected:
/// - The token should be ERC-20 compliant, except that it can omit return values on `transfer` and `transferFrom`.
/// - The token balance of Morpho should only decrease on `transfer` and `transferFrom`. In particular, tokens with
/// burn functions are not supported.
/// - The token should not re-enter Morpho on `transfer` nor `transferFrom`.
/// - The token balance of the sender (resp. receiver) should decrease (resp. increase) by exactly the given amount
/// on `transfer` and `transferFrom`. In particular, tokens with fees on transfer are not supported.
/// - The IRM should not re-enter Morpho.
/// - The oracle should return a price with the correct scaling.
/// @dev Here is a list of properties on the market's dependencies that could break Morpho's liveness properties
/// (funds could get stuck):
/// - The token can revert on `transfer` and `transferFrom` for a reason other than an approval or balance issue.
/// - A very high amount of assets (~1e35) supplied or borrowed can make the computation of `toSharesUp` and
/// `toSharesDown` overflow.
/// - The IRM can revert on `borrowRate`.
/// - A very high borrow rate returned by the IRM can make the computation of `interest` in `_accrueInterest`
/// overflow.
/// - The oracle can revert on `price`. Note that this can be used to prevent `borrow`, `withdrawCollateral` and
/// `liquidate` from being used under certain market conditions.
/// - A very high price returned by the oracle can make the computation of `maxBorrow` in `_isHealthy` overflow, or
/// the computation of `assetsRepaid` in `liquidate` overflow.
/// @dev The borrow share price of a market with less than 1e4 assets borrowed can be decreased by manipulations, to
/// the point where `totalBorrowShares` is very large and borrowing overflows.
function createMarket(MarketParams memory marketParams) external;
/// @notice Supplies `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's
/// `onMorphoSupply` function with the given `data`.
/// @dev Either `assets` or `shares` should be zero. Most use cases should rely on `assets` as an input so the
/// caller is guaranteed to have `assets` tokens pulled from their balance, but the possibility to mint a specific
/// amount of shares is given for full compatibility and precision.
/// @dev Supplying a large amount can revert for overflow.
/// @dev Supplying an amount of shares may lead to supply more or fewer assets than expected due to slippage.
/// Consider using the `assets` parameter to avoid this.
/// @param marketParams The market to supply assets to.
/// @param assets The amount of assets to supply.
/// @param shares The amount of shares to mint.
/// @param onBehalf The address that will own the increased supply position.
/// @param data Arbitrary data to pass to the `onMorphoSupply` callback. Pass empty data if not needed.
/// @return assetsSupplied The amount of assets supplied.
/// @return sharesSupplied The amount of shares minted.
function supply(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
bytes memory data
) external returns (uint256 assetsSupplied, uint256 sharesSupplied);
/// @notice Withdraws `assets` or `shares` on behalf of `onBehalf` and sends the assets to `receiver`.
/// @dev Either `assets` or `shares` should be zero. To withdraw max, pass the `shares`'s balance of `onBehalf`.
/// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
/// @dev Withdrawing an amount corresponding to more shares than supplied will revert for underflow.
/// @dev It is advised to use the `shares` input when withdrawing the full position to avoid reverts due to
/// conversion roundings between shares and assets.
/// @param marketParams The market to withdraw assets from.
/// @param assets The amount of assets to withdraw.
/// @param shares The amount of shares to burn.
/// @param onBehalf The address of the owner of the supply position.
/// @param receiver The address that will receive the withdrawn assets.
/// @return assetsWithdrawn The amount of assets withdrawn.
/// @return sharesWithdrawn The amount of shares burned.
function withdraw(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
address receiver
) external returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn);
/// @notice Borrows `assets` or `shares` on behalf of `onBehalf` and sends the assets to `receiver`.
/// @dev Either `assets` or `shares` should be zero. Most use cases should rely on `assets` as an input so the
/// caller is guaranteed to borrow `assets` of tokens, but the possibility to mint a specific amount of shares is
/// given for full compatibility and precision.
/// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
/// @dev Borrowing a large amount can revert for overflow.
/// @dev Borrowing an amount of shares may lead to borrow fewer assets than expected due to slippage.
/// Consider using the `assets` parameter to avoid this.
/// @param marketParams The market to borrow assets from.
/// @param assets The amount of assets to borrow.
/// @param shares The amount of shares to mint.
/// @param onBehalf The address that will own the increased borrow position.
/// @param receiver The address that will receive the borrowed assets.
/// @return assetsBorrowed The amount of assets borrowed.
/// @return sharesBorrowed The amount of shares minted.
function borrow(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
address receiver
) external returns (uint256 assetsBorrowed, uint256 sharesBorrowed);
/// @notice Repays `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's
/// `onMorphoRepay` function with the given `data`.
/// @dev Either `assets` or `shares` should be zero. To repay max, pass the `shares`'s balance of `onBehalf`.
/// @dev Repaying an amount corresponding to more shares than borrowed will revert for underflow.
/// @dev It is advised to use the `shares` input when repaying the full position to avoid reverts due to conversion
/// roundings between shares and assets.
/// @dev An attacker can front-run a repay with a small repay making the transaction revert for underflow.
/// @param marketParams The market to repay assets to.
/// @param assets The amount of assets to repay.
/// @param shares The amount of shares to burn.
/// @param onBehalf The address of the owner of the debt position.
/// @param data Arbitrary data to pass to the `onMorphoRepay` callback. Pass empty data if not needed.
/// @return assetsRepaid The amount of assets repaid.
/// @return sharesRepaid The amount of shares burned.
function repay(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
bytes memory data
) external returns (uint256 assetsRepaid, uint256 sharesRepaid);
/// @notice Supplies `assets` of collateral on behalf of `onBehalf`, optionally calling back the caller's
/// `onMorphoSupplyCollateral` function with the given `data`.
/// @dev Interest are not accrued since it's not required and it saves gas.
/// @dev Supplying a large amount can revert for overflow.
/// @param marketParams The market to supply collateral to.
/// @param assets The amount of collateral to supply.
/// @param onBehalf The address that will own the increased collateral position.
/// @param data Arbitrary data to pass to the `onMorphoSupplyCollateral` callback. Pass empty data if not needed.
function supplyCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, bytes memory data)
external;
/// @notice Withdraws `assets` of collateral on behalf of `onBehalf` and sends the assets to `receiver`.
/// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
/// @dev Withdrawing an amount corresponding to more collateral than supplied will revert for underflow.
/// @param marketParams The market to withdraw collateral from.
/// @param assets The amount of collateral to withdraw.
/// @param onBehalf The address of the owner of the collateral position.
/// @param receiver The address that will receive the collateral assets.
function withdrawCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, address receiver)
external;
/// @notice Liquidates the given `repaidShares` of debt asset or seize the given `seizedAssets` of collateral on the
/// given market `marketParams` of the given `borrower`'s position, optionally calling back the caller's
/// `onMorphoLiquidate` function with the given `data`.
/// @dev Either `seizedAssets` or `repaidShares` should be zero.
/// @dev Seizing more than the collateral balance will underflow and revert without any error message.
/// @dev Repaying more than the borrow balance will underflow and revert without any error message.
/// @dev An attacker can front-run a liquidation with a small repay making the transaction revert for underflow.
/// @param marketParams The market of the position.
/// @param borrower The owner of the position.
/// @param seizedAssets The amount of collateral to seize.
/// @param repaidShares The amount of shares to repay.
/// @param data Arbitrary data to pass to the `onMorphoLiquidate` callback. Pass empty data if not needed.
/// @return The amount of assets seized.
/// @return The amount of assets repaid.
function liquidate(
MarketParams memory marketParams,
address borrower,
uint256 seizedAssets,
uint256 repaidShares,
bytes memory data
) external returns (uint256, uint256);
/// @notice Executes a flash loan.
/// @dev Flash loans have access to the whole balance of the contract (the liquidity and deposited collateral of all
/// markets combined, plus donations).
/// @dev Warning: Not ERC-3156 compliant but compatibility is easily reached:
/// - `flashFee` is zero.
/// - `maxFlashLoan` is the token's balance of this contract.
/// - The receiver of `assets` is the caller.
/// @param token The token to flash loan.
/// @param assets The amount of assets to flash loan.
/// @param data Arbitrary data to pass to the `onMorphoFlashLoan` callback.
function flashLoan(address token, uint256 assets, bytes calldata data) external;
/// @notice Sets the authorization for `authorized` to manage `msg.sender`'s positions.
/// @param authorized The authorized address.
/// @param newIsAuthorized The new authorization status.
function setAuthorization(address authorized, bool newIsAuthorized) external;
/// @notice Sets the authorization for `authorization.authorized` to manage `authorization.authorizer`'s positions.
/// @dev Warning: Reverts if the signature has already been submitted.
/// @dev The signature is malleable, but it has no impact on the security here.
/// @dev The nonce is passed as argument to be able to revert with a different error message.
/// @param authorization The `Authorization` struct.
/// @param signature The signature.
function setAuthorizationWithSig(Authorization calldata authorization, Signature calldata signature) external;
/// @notice Accrues interest for the given market `marketParams`.
function accrueInterest(MarketParams memory marketParams) external;
/// @notice Returns the data stored on the different `slots`.
function extSloads(bytes32[] memory slots) external view returns (bytes32[] memory);
}
/// @dev This interface is inherited by Morpho so that function signatures are checked by the compiler.
/// @dev Consider using the IMorpho interface instead of this one.
interface IMorphoStaticTyping is IMorphoBase {
/// @notice The state of the position of `user` on the market corresponding to `id`.
/// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest
/// accrual.
function position(Id id, address user)
external
view
returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral);
/// @notice The state of the market corresponding to `id`.
/// @dev Warning: `totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `totalSupplyShares` does not contain the accrued shares by `feeRecipient` since the last interest
/// accrual.
function market(Id id)
external
view
returns (
uint128 totalSupplyAssets,
uint128 totalSupplyShares,
uint128 totalBorrowAssets,
uint128 totalBorrowShares,
uint128 lastUpdate,
uint128 fee
);
/// @notice The market params corresponding to `id`.
/// @dev This mapping is not used in Morpho. It is there to enable reducing the cost associated to calldata on layer
/// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.
function idToMarketParams(Id id)
external
view
returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv);
}
/// @title IMorpho
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @dev Use this interface for Morpho to have access to all the functions with the appropriate function signatures.
interface IMorpho is IMorphoBase {
/// @notice The state of the position of `user` on the market corresponding to `id`.
/// @dev Warning: For `feeRecipient`, `p.supplyShares` does not contain the accrued shares since the last interest
/// accrual.
function position(Id id, address user) external view returns (Position memory p);
/// @notice The state of the market corresponding to `id`.
/// @dev Warning: `m.totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `m.totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `m.totalSupplyShares` does not contain the accrued shares by `feeRecipient` since the last
/// interest accrual.
function market(Id id) external view returns (Market memory m);
/// @notice The market params corresponding to `id`.
/// @dev This mapping is not used in Morpho. It is there to enable reducing the cost associated to calldata on layer
/// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.
function idToMarketParams(Id id) external view returns (MarketParams memory);
}pragma solidity 0.8.28;
interface IUrdFactory {
function isUrd(address _maybeUrd) external view returns (bool);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IArk} from "../interfaces/IArk.sol";
import {IFleetCommander} from "../interfaces/IFleetCommander.sol";
import {ArkConfig, ArkParams} from "../types/ArkTypes.sol";
import {ArkConfigProvider} from "./ArkConfigProvider.sol";
import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IDistributor} from "../interfaces/merkl/IDistributor.sol";
import {Constants} from "@summerfi/constants/Constants.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
/**
* @title Ark
* @author SummerFi
* @notice This contract implements the core functionality for the Ark system,
* handling asset boarding, disembarking, and harvesting operations.
* @dev This is an abstract contract that should be inherited by specific Ark implementations.
* Inheriting contracts must implement the abstract functions defined here.
*/
abstract contract Ark is IArk, ArkConfigProvider, ReentrancyGuardTransient {
using SafeERC20 for IERC20;
IDistributor constant MERKL_DISTRIBUTOR =
IDistributor(0x3Ef3D8bA38EBe18DB133cEc108f4D14CE00Dd9Ae);
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(ArkParams memory _params) ArkConfigProvider(_params) {}
/*//////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////*/
/**
* @notice Modifier to validate board data.
* @dev This modifier calls `_validateCommonData` and `_validateBoardData` to ensure the data is valid.
* In the base Ark contract, we use generic bytes for the data. It is the responsibility of the Ark
* implementing contract to override the `_validateBoardData` function to provide specific validation logic.
* @param data The data to be validated.
*/
modifier validateBoardData(bytes calldata data) {
_validateCommonData(data);
_validateBoardData(data);
_;
}
/**
* @notice Modifier to validate disembark data.
* @dev This modifier calls `_validateCommonData` and `_validateDisembarkData` to ensure the data is valid.
* In the base Ark contract, we use generic bytes for the data. It is the responsibility of the Ark
* implementing contract to override the `_validateDisembarkData` function to provide specific validation logic.
* @param data The data to be validated.
*/
modifier validateDisembarkData(bytes calldata data) {
_validateCommonData(data);
_validateDisembarkData(data);
_;
}
/*//////////////////////////////////////////////////////////////
EXTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IArk
function totalAssets() external view virtual returns (uint256) {}
/// @inheritdoc IArk
function withdrawableTotalAssets() external view returns (uint256) {
if (config.requiresKeeperData) {
return 0;
}
return _withdrawableTotalAssets();
}
/// @inheritdoc IArk
function harvest(
bytes calldata additionalData
)
external
onlyRaft
nonReentrant
returns (address[] memory rewardTokens, uint256[] memory rewardAmounts)
{
(rewardTokens, rewardAmounts) = _harvest(additionalData);
emit ArkHarvested(rewardTokens, rewardAmounts);
}
/// @inheritdoc IArk
function sweep(
address[] memory tokens
)
external
onlyRaft
nonReentrant
returns (address[] memory sweptTokens, uint256[] memory sweptAmounts)
{
sweptTokens = new address[](tokens.length);
sweptAmounts = new uint256[](tokens.length);
IERC20 asset = config.asset;
address bufferArk = address(
IFleetCommander(config.commander).bufferArk()
);
if (asset.balanceOf(address(this)) > 0 && address(this) != bufferArk) {
asset.forceApprove(bufferArk, asset.balanceOf(address(this)));
IArk(bufferArk).board(asset.balanceOf(address(this)), bytes(""));
}
for (uint256 i = 0; i < tokens.length; i++) {
uint256 amount = IERC20(tokens[i]).balanceOf(address(this));
if (amount > 0) {
IERC20(tokens[i]).safeTransfer(
raft(),
IERC20(tokens[i]).balanceOf(address(this))
);
sweptTokens[i] = tokens[i];
sweptAmounts[i] = amount;
}
}
emit ArkSwept(sweptTokens, sweptAmounts);
}
function whitelistMerklOperator(address operator) external onlyKeeper {
MERKL_DISTRIBUTOR.toggleOperator(address(this), operator);
}
/// @inheritdoc IArk
function board(
uint256 amount,
bytes calldata boardData
)
external
nonReentrant
onlyAuthorizedToBoard(this.commander())
validateBoardData(boardData)
{
address msgSender = msg.sender;
IERC20 asset = config.asset;
asset.safeTransferFrom(msgSender, address(this), amount);
_board(amount, boardData);
emit Boarded(msgSender, address(asset), amount);
}
/// @inheritdoc IArk
function disembark(
uint256 amount,
bytes calldata disembarkData
) external onlyCommander nonReentrant validateDisembarkData(disembarkData) {
address msgSender = msg.sender;
IERC20 asset = config.asset;
_disembark(amount, disembarkData);
asset.safeTransfer(msgSender, amount);
emit Disembarked(msgSender, address(asset), amount);
}
/// @inheritdoc IArk
function move(
uint256 amount,
address receiverArk,
bytes calldata boardData,
bytes calldata disembarkData
) external onlyCommander validateDisembarkData(disembarkData) {
_disembark(amount, disembarkData);
IERC20 asset = config.asset;
asset.forceApprove(receiverArk, amount);
IArk(receiverArk).board(amount, boardData);
emit Moved(address(this), receiverArk, address(asset), amount);
}
/*//////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Internal function to get the total assets that are withdrawable
* @dev This function should be implemented by derived contracts to define specific withdrawability logic
* @dev The Ark is withdrawable if it doesnt require keeper data and _withdrawableTotalAssets returns a non-zero
* value
* @return uint256 The total assets that are withdrawable
*/
function _withdrawableTotalAssets() internal view virtual returns (uint256);
/**
* @notice Internal function to handle the boarding (depositing) of assets
* @dev This function should be implemented by derived contracts to define specific boarding logic
* @param amount The amount of assets to board
* @param data Additional data for boarding, interpreted by the specific Ark implementation
*/
function _board(uint256 amount, bytes calldata data) internal virtual;
/**
* @notice Internal function to handle the disembarking (withdrawing) of assets
* @dev This function should be implemented by derived contracts to define specific disembarking logic
* @param amount The amount of assets to disembark
* @param data Additional data for disembarking, interpreted by the specific Ark implementation
*/
function _disembark(uint256 amount, bytes calldata data) internal virtual;
/**
* @notice Internal function to handle the harvesting of rewards
* @dev This function should be implemented by derived contracts to define specific harvesting logic
* @param additionalData Additional data for harvesting, interpreted by the specific Ark implementation
* @return rewardTokens The addresses of the reward tokens harvested
* @return rewardAmounts The amounts of the reward tokens harvested
*/
function _harvest(
bytes calldata additionalData
)
internal
virtual
returns (address[] memory rewardTokens, uint256[] memory rewardAmounts);
/**
* @notice Internal function to validate boarding data
* @dev This function should be implemented by derived contracts to define specific boarding data validation
* @param data The boarding data to validate
*/
function _validateBoardData(bytes calldata data) internal virtual;
/**
* @notice Internal function to validate disembarking data
* @dev This function should be implemented by derived contracts to define specific disembarking data validation
* @param data The disembarking data to validate
*/
function _validateDisembarkData(bytes calldata data) internal virtual;
/**
* @notice Internal function to validate the presence or absence of additional data based on withdrawal restrictions
* @dev This function checks if the data length is consistent with the Ark's withdrawal restrictions
* @param data The data to validate
*/
function _validateCommonData(bytes calldata data) internal view {
if (data.length > 0 && !config.requiresKeeperData) {
revert CannotUseKeeperDataWhenNotRequired();
}
if (data.length == 0 && config.requiresKeeperData) {
revert KeeperDataRequired();
}
}
/**
* @notice Internal function to get the balance of the Ark's asset
* @dev This function returns the balance of the Ark's token held by this contract
* @return The balance of the Ark's asset
*/
function _balanceOfAsset() internal view virtual returns (uint256) {
return config.asset.balanceOf(address(this));
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IArkAccessManaged} from "../interfaces/IArkAccessManaged.sol";
import {IConfigurationManaged} from "@summerfi/config-contracts/interfaces/IConfigurationManaged.sol";
import {IFleetCommander} from "../interfaces/IFleetCommander.sol";
import {ContractSpecificRoles} from "@summerfi/access-contracts/interfaces/IProtocolAccessManager.sol";
import {ProtocolAccessManaged} from "@summerfi/access-contracts/contracts/ProtocolAccessManaged.sol";
/**
* @title ArkAccessManaged
* @author SummerFi
* @notice This contract manages access control for Ark-related operations.
* @dev Inherits from ProtocolAccessManaged and implements IArkAccessManaged.
* @custom:see IArkAccessManaged
*/
contract ArkAccessManaged is IArkAccessManaged, ProtocolAccessManaged {
/**
* @notice Initializes the ArkAccessManaged contract.
* @param accessManager The address of the access manager contract.
*/
constructor(address accessManager) ProtocolAccessManaged(accessManager) {}
/**
* @notice Checks if the caller is authorized to board funds.
* @dev This modifier allows the Commander, RAFT contract, or active Arks to proceed.
* @param commander The address of the FleetCommander contract.
* @custom:internal-logic
* - Checks if the caller is the registered commander
* - If not, checks if the caller is the RAFT contract
* - If not, checks if the caller is an active Ark in the FleetCommander
* @custom:effects
* - Reverts if the caller doesn't have the necessary permissions
* - Allows the function to proceed if the caller is authorized
* @custom:security-considerations
* - Ensures that only authorized entities can board funds
* - Relies on the correct setup of the FleetCommander and RAFT contracts
*/
modifier onlyAuthorizedToBoard(address commander) {
if (commander != _msgSender()) {
address msgSender = _msgSender();
bool isRaft = msgSender ==
IConfigurationManaged(address(this)).raft();
if (!isRaft) {
bool isArk = IFleetCommander(commander).isArkActiveOrBufferArk(
msgSender
);
if (!isArk) {
revert CallerIsNotAuthorizedToBoard(msgSender);
}
}
}
_;
}
/**
* @notice Restricts access to only the RAFT contract.
* @dev Modifier to check that the caller is the RAFT contract
* @custom:internal-logic
* - Retrieves the RAFT address from the ConfigurationManaged contract
* - Compares the caller's address with the RAFT address
* @custom:effects
* - Reverts if the caller is not the RAFT contract
* - Allows the function to proceed if the caller is the RAFT contract
* @custom:security-considerations
* - Ensures that only the RAFT contract can call certain functions
* - Relies on the correct setup of the ConfigurationManaged contract
*/
modifier onlyRaft() {
if (_msgSender() != IConfigurationManaged(address(this)).raft()) {
revert CallerIsNotRaft(_msgSender());
}
_;
}
/**
* @notice Checks if the caller has the Commander role.
* @dev Internal function to check if the caller has the Commander role
* @return bool True if the caller has the Commander role, false otherwise
* @custom:internal-logic
* - Generates the Commander role identifier for this contract
* - Checks if the caller has the generated role in the access manager
* @custom:effects
* - Does not modify any state, view function only
* @custom:security-considerations
* - Relies on the correct setup of the access manager
* - Assumes that the Commander role is properly assigned
*/
function _hasCommanderRole() internal view returns (bool) {
return
_accessManager.hasRole(
generateRole(
ContractSpecificRoles.COMMANDER_ROLE,
address(this)
),
_msgSender()
);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {ArkConfig, ArkParams} from "../types/ArkTypes.sol";
import {IArkConfigProvider} from "../interfaces/IArkConfigProvider.sol";
import {ArkAccessManaged} from "./ArkAccessManaged.sol";
import {ConfigurationManaged} from "@summerfi/config-contracts/contracts/ConfigurationManaged.sol";
import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Percentage, PercentageUtils} from "@summerfi/percentage-solidity/contracts/PercentageUtils.sol";
/**
* @title ArkConfigProvider
* @author SummerFi
* @notice This contract manages the configuration for Ark contracts.
* @dev Inherits from IArkConfigProvider, ArkAccessManaged, and ConfigurationManaged.
* @custom:see IArkConfigProvider
*/
abstract contract ArkConfigProvider is
IArkConfigProvider,
ArkAccessManaged,
ConfigurationManaged
{
ArkConfig public config;
/**
* @notice Initializes the ArkConfigProvider contract.
* @param _params The initial parameters for the Ark configuration.
* @dev Validates input parameters and sets up the initial configuration.
*/
constructor(
ArkParams memory _params
)
ArkAccessManaged(_params.accessManager)
ConfigurationManaged(_params.configurationManager)
{
if (_params.asset == address(0)) {
revert CannotDeployArkWithoutToken();
}
if (bytes(_params.name).length == 0) {
revert CannotDeployArkWithEmptyName();
}
if (raft() == address(0)) {
revert CannotDeployArkWithoutRaft();
}
if (
!PercentageUtils.isPercentageInRange(
_params.maxDepositPercentageOfTVL
)
) {
revert MaxDepositPercentageOfTVLTooHigh();
}
config = ArkConfig({
asset: IERC20(_params.asset),
commander: address(0), // Commander is initially set to address(0)
raft: raft(),
depositCap: _params.depositCap,
maxRebalanceOutflow: _params.maxRebalanceOutflow,
maxRebalanceInflow: _params.maxRebalanceInflow,
name: _params.name,
details: _params.details,
requiresKeeperData: _params.requiresKeeperData,
maxDepositPercentageOfTVL: _params.maxDepositPercentageOfTVL
});
// The commander address is initially set to address(0).
// This allows the FleetCommander contract to self-register with the Ark later,
// using the `registerFleetCommander()` function. This approach ensures that:
// 1. The FleetCommander's address is not hardcoded during deployment.
// 2. Only the authorized FleetCommander can register itself.
// 3. The Ark remains flexible for potential commander changes in the future.
// See the `registerFleetCommander()` function for the actual registration process.
}
/// @inheritdoc IArkConfigProvider
function name() external view returns (string memory) {
return config.name;
}
/// @inheritdoc IArkConfigProvider
function details() external view returns (string memory) {
return config.details;
}
/// @inheritdoc IArkConfigProvider
function depositCap() external view returns (uint256) {
return config.depositCap;
}
/// @inheritdoc IArkConfigProvider
function asset() external view returns (IERC20) {
return config.asset;
}
function maxDepositPercentageOfTVL() external view returns (Percentage) {
return config.maxDepositPercentageOfTVL;
}
/// @inheritdoc IArkConfigProvider
function commander() public view returns (address) {
return config.commander;
}
/// @inheritdoc IArkConfigProvider
function maxRebalanceOutflow() external view returns (uint256) {
return config.maxRebalanceOutflow;
}
/// @inheritdoc IArkConfigProvider
function maxRebalanceInflow() external view returns (uint256) {
return config.maxRebalanceInflow;
}
/// @inheritdoc IArkConfigProvider
function requiresKeeperData() external view returns (bool) {
return config.requiresKeeperData;
}
/// @inheritdoc IArkConfigProvider
function getConfig() external view returns (ArkConfig memory) {
return config;
}
/// @inheritdoc IArkConfigProvider
function setDepositCap(uint256 newDepositCap) external onlyCommander {
config.depositCap = newDepositCap;
emit DepositCapUpdated(newDepositCap);
}
/// @inheritdoc IArkConfigProvider
function setMaxDepositPercentageOfTVL(
Percentage newMaxDepositPercentageOfTVL
) external onlyCommander {
if (
!PercentageUtils.isPercentageInRange(newMaxDepositPercentageOfTVL)
) {
revert MaxDepositPercentageOfTVLTooHigh();
}
config.maxDepositPercentageOfTVL = newMaxDepositPercentageOfTVL;
emit MaxDepositPercentageOfTVLUpdated(newMaxDepositPercentageOfTVL);
}
/// @inheritdoc IArkConfigProvider
function setMaxRebalanceOutflow(
uint256 newMaxRebalanceOutflow
) external onlyCommander {
config.maxRebalanceOutflow = newMaxRebalanceOutflow;
emit MaxRebalanceOutflowUpdated(newMaxRebalanceOutflow);
}
/// @inheritdoc IArkConfigProvider
function setMaxRebalanceInflow(
uint256 newMaxRebalanceInflow
) external onlyCommander {
config.maxRebalanceInflow = newMaxRebalanceInflow;
emit MaxRebalanceInflowUpdated(newMaxRebalanceInflow);
}
function registerFleetCommander() external {
if (!_hasCommanderRole()) {
revert CallerIsNotCommander(msg.sender);
}
if (config.commander != address(0)) {
revert FleetCommanderAlreadyRegistered();
}
config.commander = msg.sender;
emit FleetCommanderRegistered(msg.sender);
}
function unregisterFleetCommander() external {
if (_msgSender() != config.commander) {
revert FleetCommanderNotRegistered();
}
config.commander = address(0);
emit FleetCommanderUnregistered(msg.sender);
}
modifier onlyCommander() {
if (_msgSender() != config.commander) {
revert CallerIsNotCommander(_msgSender());
}
_;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title IArkConfigProviderErrors
* @dev This file contains custom error definitions for the ArkConfigProvider contract.
* @notice These custom errors provide more gas-efficient and informative error handling
* compared to traditional require statements with string messages.
*/
interface IArkConfigProviderErrors {
/**
* @notice Thrown when attempting to deploy an Ark without specifying a configuration manager.
*/
error CannotDeployArkWithoutConfigurationManager();
/**
* @notice Thrown when attempting to deploy an Ark without specifying a Raft address.
*/
error CannotDeployArkWithoutRaft();
/**
* @notice Thrown when attempting to deploy an Ark without specifying a token address.
*/
error CannotDeployArkWithoutToken();
/**
* @notice Thrown when attempting to deploy an Ark with an empty name.
*/
error CannotDeployArkWithEmptyName();
/**
* @notice Thrown when an invalid vault address is provided.
*/
error InvalidVaultAddress();
/**
* @notice Thrown when there's a mismatch between expected and actual assets in an ERC4626 operation.
*/
error ERC4626AssetMismatch();
/**
* @notice Thrown when the max deposit percentage of TVL is greater than 100%.
*/
error MaxDepositPercentageOfTVLTooHigh();
/**
* @notice Thrown when attempting to register a FleetCommander when one is already registered.
*/
error FleetCommanderAlreadyRegistered();
/**
* @notice Thrown when attempting to unregister a FleetCommander by a non-registered address.
*/
error FleetCommanderNotRegistered();
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title IArkErrors
* @dev This file contains custom error definitions for the Ark contract.
* @notice These custom errors provide more gas-efficient and informative error handling
* compared to traditional require statements with string messages.
*/
interface IArkErrors {
/**
* @notice Thrown when attempting to remove a commander from an Ark that still has assets.
*/
error CannotRemoveCommanderFromArkWithAssets();
/**
* @notice Thrown when trying to add a commander to an Ark that already has one.
*/
error CannotAddCommanderToArkWithCommander();
/**
* @notice Thrown when attempting to use keeper data when it's not required.
*/
error CannotUseKeeperDataWhenNotRequired();
/**
* @notice Thrown when keeper data is required but not provided.
*/
error KeeperDataRequired();
/**
* @notice Thrown when invalid board data is provided.
*/
error InvalidBoardData();
/**
* @notice Thrown when invalid disembark data is provided.
*/
error InvalidDisembarkData();
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title IFleetCommanderConfigProviderErrors
* @dev This file contains custom error definitions for the FleetCommanderConfigProvider contract.
* @notice These custom errors provide more gas-efficient and informative error handling
* compared to traditional require statements with string messages.
*/
interface IFleetCommanderConfigProviderErrors {
/**
* @notice Thrown when an operation is attempted on a non-existent Ark
* @param ark The address of the Ark that was not found
*/
error FleetCommanderArkNotFound(address ark);
/**
* @notice Thrown when trying to remove an Ark that still has a non-zero deposit cap
* @param ark The address of the Ark with a non-zero deposit cap
*/
error FleetCommanderArkDepositCapGreaterThanZero(address ark);
/**
* @notice Thrown when attempting to remove an Ark that still holds assets
* @param ark The address of the Ark with non-zero assets
*/
error FleetCommanderArkAssetsNotZero(address ark);
/**
* @notice Thrown when trying to add an Ark that already exists in the system
* @param ark The address of the Ark that already exists
*/
error FleetCommanderArkAlreadyExists(address ark);
/**
* @notice Thrown when an invalid Ark address is provided (e.g., zero address)
*/
error FleetCommanderInvalidArkAddress();
/**
* @notice Thrown when trying to set a StakingRewardsManager to the zero address
*/
error FleetCommanderInvalidStakingRewardsManager();
/**
* @notice Thrown when trying to set a max rebalance operations to a value greater than the max allowed
* @param newMaxRebalanceOperations The new max rebalance operations value
*/
error FleetCommanderMaxRebalanceOperationsTooHigh(
uint256 newMaxRebalanceOperations
);
/**
* @notice Thrown when the asset of the Ark does not match the asset of the FleetCommander
*/
error FleetCommanderAssetMismatch();
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title IFleetCommanderErrors
* @dev This file contains custom error definitions for the FleetCommander contract.
* @notice These custom errors provide more gas-efficient and informative error handling
* compared to traditional require statements with string messages.
*/
interface IFleetCommanderErrors {
/**
* @notice Thrown when transfers are disabled.
*/
error FleetCommanderTransfersDisabled();
/**
* @notice Thrown when an operation is attempted on an inactive Ark.
* @param ark The address of the inactive Ark.
*/
error FleetCommanderArkNotActive(address ark);
/**
* @notice Thrown when attempting to rebalance to an invalid Ark.
* @param ark The address of the invalid Ark.
* @param amount Amount of tokens added to target ark
* @param effectiveDepositCap Effective deposit cap of the ark (minimum of % of fleet TVL or arbitrary ark deposit
* cap)
*/
error FleetCommanderEffectiveDepositCapExceeded(
address ark,
uint256 amount,
uint256 effectiveDepositCap
);
/**
* @notice Thrown when there is insufficient buffer for an operation.
*/
error FleetCommanderInsufficientBuffer();
/**
* @notice Thrown when a rebalance operation is attempted with no actual operations.
*/
error FleetCommanderRebalanceNoOperations();
/**
* @notice Thrown when a rebalance operation exceeds the maximum allowed number of operations.
* @param operationsCount The number of operations attempted.
*/
error FleetCommanderRebalanceTooManyOperations(uint256 operationsCount);
/**
* @notice Thrown when a rebalance amount for an Ark is zero.
* @param ark The address of the Ark with zero rebalance amount.
*/
error FleetCommanderRebalanceAmountZero(address ark);
/**
* @notice Thrown when a withdrawal amount exceeds the maximum buffer limit.
*/
error WithdrawalAmountExceedsMaxBufferLimit();
/**
* @notice Thrown when an Ark's deposit cap is zero.
* @param ark The address of the Ark with zero deposit cap.
*/
error FleetCommanderArkDepositCapZero(address ark);
/**
* @notice Thrown when no funds were moved in an operation that expected fund movement.
*/
error FleetCommanderNoFundsMoved();
/**
* @notice Thrown when there are no excess funds to perform an operation.
*/
error FleetCommanderNoExcessFunds();
/**
* @notice Thrown when an invalid source Ark is specified for an operation.
* @param ark The address of the invalid source Ark.
*/
error FleetCommanderInvalidSourceArk(address ark);
/**
* @notice Thrown when an operation attempts to move more funds than available.
*/
error FleetCommanderMovedMoreThanAvailable();
/**
* @notice Thrown when an unauthorized withdrawal is attempted.
* @param caller The address attempting the withdrawal.
* @param owner The address of the authorized owner.
*/
error FleetCommanderUnauthorizedWithdrawal(address caller, address owner);
/**
* @notice Thrown when an unauthorized redemption is attempted.
* @param caller The address attempting the redemption.
* @param owner The address of the authorized owner.
*/
error FleetCommanderUnauthorizedRedemption(address caller, address owner);
/**
* @notice Thrown when attempting to use rebalance on a buffer Ark.
*/
error FleetCommanderCantUseRebalanceOnBufferArk();
/**
* @notice Thrown when attempting to use the maximum uint value for buffer adjustment from buffer.
*/
error FleetCommanderCantUseMaxUintMovingFromBuffer();
/**
* @notice Thrown when a rebalance operation exceeds the maximum outflow for an Ark.
* @param fromArk The address of the Ark from which funds are being moved.
* @param amount The amount being moved.
* @param maxRebalanceOutflow The maximum allowed outflow.
*/
error FleetCommanderExceedsMaxOutflow(
address fromArk,
uint256 amount,
uint256 maxRebalanceOutflow
);
/**
* @notice Thrown when a rebalance operation exceeds the maximum inflow for an Ark.
* @param fromArk The address of the Ark to which funds are being moved.
* @param amount The amount being moved.
* @param maxRebalanceInflow The maximum allowed inflow.
*/
error FleetCommanderExceedsMaxInflow(
address fromArk,
uint256 amount,
uint256 maxRebalanceInflow
);
/**
* @notice Thrown when the staking rewards manager is not set.
*/
error FleetCommanderStakingRewardsManagerNotSet();
/**
* @notice Thrown when user attempts to deposit/mint or withdraw/redeem 0 units
*/
error FleetCommanderZeroAmount();
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {Percentage} from "@summerfi/percentage-solidity/contracts/Percentage.sol";
/**
* @title IArkConfigProviderEvents
* @notice Interface for events emitted by ArkConfigProvider contracts
*/
interface IArkConfigProviderEvents {
/**
* @notice Emitted when the deposit cap of the Ark is updated
* @param newCap The new deposit cap value
*/
event DepositCapUpdated(uint256 newCap);
/**
* @notice Emitted when the maximum deposit percentage of TVL is updated
* @param newMaxDepositPercentageOfTVL The new maximum deposit percentage of TVL
*/
event MaxDepositPercentageOfTVLUpdated(
Percentage newMaxDepositPercentageOfTVL
);
/**
* @notice Emitted when the Raft address associated with the Ark is updated
* @param newRaft The address of the new Raft
*/
event RaftUpdated(address newRaft);
/**
* @notice Emitted when the maximum outflow limit for the Ark during rebalancing is updated
* @param newMaxOutflow The new maximum amount that can be transferred out of the Ark during a rebalance
*/
event MaxRebalanceOutflowUpdated(uint256 newMaxOutflow);
/**
* @notice Emitted when the maximum inflow limit for the Ark during rebalancing is updated
* @param newMaxInflow The new maximum amount that can be transferred into the Ark during a rebalance
*/
event MaxRebalanceInflowUpdated(uint256 newMaxInflow);
/**
* @notice Emitted when the Fleet Commander is registered
* @param commander The address of the Fleet Commander
*/
event FleetCommanderRegistered(address commander);
/**
* @notice Emitted when the Fleet Commander is unregistered
* @param commander The address of the Fleet Commander
*/
event FleetCommanderUnregistered(address commander);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title IArkEvents
* @notice Interface for events emitted by Ark contracts
*/
interface IArkEvents {
/**
* @notice Emitted when rewards are harvested from an Ark
* @param rewardTokens The addresses of the harvested reward tokens
* @param rewardAmounts The amounts of the harvested reward tokens
*/
event ArkHarvested(
address[] indexed rewardTokens,
uint256[] indexed rewardAmounts
);
/**
* @notice Emitted when tokens are boarded (deposited) into the Ark
* @param commander The address of the FleetCommander initiating the boarding
* @param token The address of the token being boarded
* @param amount The amount of tokens boarded
*/
event Boarded(address indexed commander, address token, uint256 amount);
/**
* @notice Emitted when tokens are disembarked (withdrawn) from the Ark
* @param commander The address of the FleetCommander initiating the disembarking
* @param token The address of the token being disembarked
* @param amount The amount of tokens disembarked
*/
event Disembarked(address indexed commander, address token, uint256 amount);
/**
* @notice Emitted when tokens are moved from one address to another
* @param from Ark being boarded from
* @param to Ark being boarded to
* @param token The address of the token being moved
* @param amount The amount of tokens moved
*/
event Moved(
address indexed from,
address indexed to,
address token,
uint256 amount
);
/**
* @notice Emitted when the Ark is poked and the share price is updated
* @param currentPrice Current share price of the Ark
* @param timestamp The timestamp of the poke
*/
event ArkPoked(uint256 currentPrice, uint256 timestamp);
/**
* @notice Emitted when the Ark is swept
* @param sweptTokens The addresses of the swept tokens
* @param sweptAmounts The amounts of the swept tokens
*/
event ArkSwept(
address[] indexed sweptTokens,
uint256[] indexed sweptAmounts
);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
interface IFleetCommanderConfigProviderEvents {
/**
* @notice Emitted when the deposit cap is updated
* @param newCap The new deposit cap value
*/
event FleetCommanderDepositCapUpdated(uint256 newCap);
/**
* @notice Emitted when a new Ark is added
* @param ark The address of the newly added Ark
*/
event ArkAdded(address indexed ark);
/**
* @notice Emitted when an Ark is removed
* @param ark The address of the removed Ark
*/
event ArkRemoved(address indexed ark);
/**
* @notice Emitted when new minimum funds buffer balance is set
* @param newBalance New minimum funds buffer balance
*/
event FleetCommanderminimumBufferBalanceUpdated(uint256 newBalance);
/**
* @notice Emitted when new max allowed rebalance operations is set
* @param newMaxRebalanceOperations Max allowed rebalance operations
*/
event FleetCommanderMaxRebalanceOperationsUpdated(
uint256 newMaxRebalanceOperations
);
/**
* @notice Emitted when the staking rewards contract address is updated
* @param newStakingRewards The address of the new staking rewards contract
*/
event FleetCommanderStakingRewardsUpdated(address newStakingRewards);
/**
* @notice Emitted when the transfer enabled status is updated
*/
event TransfersEnabled();
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {RebalanceData} from "../types/FleetCommanderTypes.sol";
interface IFleetCommanderEvents {
/* EVENTS */
/**
* @notice Emitted when a rebalance operation is completed
* @param keeper The address of the keeper who initiated the rebalance
* @param rebalances An array of RebalanceData structs detailing the rebalance operations
*/
event Rebalanced(address indexed keeper, RebalanceData[] rebalances);
/**
* @notice Emitted when queued funds are committed
* @param keeper The address of the keeper who committed the funds
* @param prevBalance The previous balance before committing funds
* @param newBalance The new balance after committing funds
*/
event QueuedFundsCommitted(
address indexed keeper,
uint256 prevBalance,
uint256 newBalance
);
/**
* @notice Emitted when the funds queue is refilled
* @param keeper The address of the keeper who initiated the queue refill
* @param prevBalance The previous balance before refilling
* @param newBalance The new balance after refilling
*/
event FundsQueueRefilled(
address indexed keeper,
uint256 prevBalance,
uint256 newBalance
);
/**
* @notice Emitted when the minimum balance of the funds queue is updated
* @param keeper The address of the keeper who updated the minimum balance
* @param newBalance The new minimum balance
*/
event MinFundsQueueBalanceUpdated(
address indexed keeper,
uint256 newBalance
);
/**
* @notice Emitted when the fee address is updated
* @param newAddress The new fee address
*/
event FeeAddressUpdated(address newAddress);
/**
* @notice Emitted when the funds buffer balance is updated
* @param user The address of the user who triggered the update
* @param prevBalance The previous buffer balance
* @param newBalance The new buffer balance
*/
event FundsBufferBalanceUpdated(
address indexed user,
uint256 prevBalance,
uint256 newBalance
);
/**
* @notice Emitted when funds are withdrawn from Arks
* @param owner The address of the owner who initiated the withdrawal
* @param receiver The address of the receiver of the withdrawn funds
* @param totalWithdrawn The total amount of funds withdrawn
*/
event FleetCommanderWithdrawnFromArks(
address indexed owner,
address receiver,
uint256 totalWithdrawn
);
/**
* @notice Emitted when funds are redeemed from Arks
* @param owner The address of the owner who initiated the redemption
* @param receiver The address of the receiver of the redeemed funds
* @param totalRedeemed The total amount of funds redeemed
*/
event FleetCommanderRedeemedFromArks(
address indexed owner,
address receiver,
uint256 totalRedeemed
);
/**
* @notice Emitted when referee deposits into the FleetCommander
* @param referee The address of the referee who was referred
* @param referralCode The referral code of the referrer
*/
event FleetCommanderReferral(
address indexed referee,
bytes indexed referralCode
);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IArkErrors} from "../errors/IArkErrors.sol";
import {IArkEvents} from "../events/IArkEvents.sol";
import {IArkAccessManaged} from "./IArkAccessManaged.sol";
import {IArkConfigProvider} from "./IArkConfigProvider.sol";
/**
* @title IArk
* @notice Interface for the Ark contract, which manages funds and interacts with Rafts
* @dev Inherits from IArkAccessManaged for access control and IArkEvents for event definitions
*/
interface IArk is
IArkAccessManaged,
IArkEvents,
IArkErrors,
IArkConfigProvider
{
/**
* @notice Returns the current underlying balance of the Ark
* @return The total assets in the Ark, in token precision
*/
function totalAssets() external view returns (uint256);
/**
* @notice Triggers a harvest operation to collect rewards
* @param additionalData Optional bytes that might be required by a specific protocol to harvest
* @return rewardTokens The reward token addresses
* @return rewardAmounts The reward amounts
*/
function harvest(
bytes calldata additionalData
)
external
returns (address[] memory rewardTokens, uint256[] memory rewardAmounts);
/**
* @notice Sweeps tokens from the Ark
* @param tokens The tokens to sweep
* @return sweptTokens The swept tokens
* @return sweptAmounts The swept amounts
*/
function sweep(
address[] calldata tokens
)
external
returns (address[] memory sweptTokens, uint256[] memory sweptAmounts);
/**
* @notice Deposits (boards) tokens into the Ark
* @dev This function is called by the Fleet Commander to deposit assets into the Ark.
* It transfers tokens from the caller to this contract and then calls the internal _board function.
* @param amount The amount of assets to board
* @param boardData Additional data required for boarding, specific to the Ark implementation
* @custom:security-note This function is only callable by authorized entities
*/
function board(uint256 amount, bytes calldata boardData) external;
/**
* @notice Withdraws (disembarks) tokens from the Ark
* @param amount The amount of tokens to withdraw
* @param disembarkData Additional data that might be required by a specific protocol to withdraw funds
*/
function disembark(uint256 amount, bytes calldata disembarkData) external;
/**
* @notice Moves tokens from one ark to another
* @param amount The amount of tokens to move
* @param receiver The address of the Ark the funds will be boarded to
* @param boardData Additional data that might be required by a specific protocol to board funds
* @param disembarkData Additional data that might be required by a specific protocol to disembark funds
*/
function move(
uint256 amount,
address receiver,
bytes calldata boardData,
bytes calldata disembarkData
) external;
/**
* @notice Internal function to get the total assets that are withdrawable
* @return uint256 The total assets that are withdrawable
* @dev _withdrawableTotalAssets is an internal function that should be implemented by derived contracts to define
* specific withdrawability logic
* @dev the ark is withdrawable if it doesnt require keeper data and _isWithdrawable returns true
*/
function withdrawableTotalAssets() external view returns (uint256);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title IArkAccessManaged
* @notice Extends the ProtocolAccessManaged contract with Ark specific AccessControl
* Used to specifically tie one FleetCommander to each Ark
*
* @dev One Ark specific role is defined:
* - Commander: is the fleet commander contract itself and couples an
* Ark to specific Fleet Commander
*
* The Commander role is still declared on the access manager to centralise
* role definitions.
*/
interface IArkAccessManaged {}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IArkConfigProviderErrors} from "../errors/IArkConfigProviderErrors.sol";
import {IArkAccessManaged} from "./IArkAccessManaged.sol";
import {IArkConfigProviderEvents} from "../events/IArkConfigProviderEvents.sol";
import {ArkConfig} from "../types/ArkTypes.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Percentage} from "@summerfi/percentage-solidity/contracts/Percentage.sol";
/**
* @title IArkConfigProvider
* @notice Interface for configuration of Ark contracts
* @dev Inherits from IArkAccessManaged for access control and IArkConfigProviderEvents for event definitions
*/
interface IArkConfigProvider is
IArkAccessManaged,
IArkConfigProviderErrors,
IArkConfigProviderEvents
{
/**
* @notice Retrieves the current fleet config
*/
function getConfig() external view returns (ArkConfig memory);
/**
* @dev Returns the name of the Ark.
* @return The name of the Ark as a string.
*/
function name() external view returns (string memory);
/**
* @notice Returns the details of the Ark
* @return The details of the Ark as a string
*/
function details() external view returns (string memory);
/**
* @notice Returns the deposit cap for this Ark
* @return The maximum amount of tokens that can be deposited into the Ark
*/
function depositCap() external view returns (uint256);
/**
* @notice Returns the maximum percentage of TVL that can be deposited into the Ark
* @return The maximum percentage of TVL that can be deposited into the Ark
*/
function maxDepositPercentageOfTVL() external view returns (Percentage);
/**
* @notice Returns the maximum amount that can be moved to this Ark in one rebalance
* @return maximum amount that can be moved to this Ark in one rebalance
*/
function maxRebalanceInflow() external view returns (uint256);
/**
* @notice Returns the maximum amount that can be moved from this Ark in one rebalance
* @return maximum amount that can be moved from this Ark in one rebalance
*/
function maxRebalanceOutflow() external view returns (uint256);
/**
* @notice Returns whether the Ark requires keeper data to board/disembark
* @return true if the Ark requires keeper data, false otherwise
*/
function requiresKeeperData() external view returns (bool);
/**
* @notice Returns the ERC20 token managed by this Ark
* @return The IERC20 interface of the managed token
*/
function asset() external view returns (IERC20);
/**
* @notice Returns the address of the Fleet commander managing the ark
* @return address Address of Fleet commander managing the ark if a Commander is assigned, address(0) otherwise
*/
function commander() external view returns (address);
/**
* @notice Sets a new maximum allocation for the Ark
* @param newDepositCap The new maximum allocation amount
*/
function setDepositCap(uint256 newDepositCap) external;
/**
* @notice Sets a new maximum deposit percentage of TVL for the Ark
* @param newMaxDepositPercentageOfTVL The new maximum deposit percentage of TVL
*/
function setMaxDepositPercentageOfTVL(
Percentage newMaxDepositPercentageOfTVL
) external;
/**
* @notice Sets a new maximum amount that can be moved from the Ark in one rebalance
* @param newMaxRebalanceOutflow The new maximum amount that can be moved from the Ark
*/
function setMaxRebalanceOutflow(uint256 newMaxRebalanceOutflow) external;
/**
* @notice Sets a new maximum amount that can be moved to the Ark in one rebalance
* @param newMaxRebalanceInflow The new maximum amount that can be moved to the Ark
*/
function setMaxRebalanceInflow(uint256 newMaxRebalanceInflow) external;
/**
* @notice Registers the Fleet commander for the Ark
* @dev This function is used to register the Fleet commander for the Ark
* it's called by the FleetCommander when ark is added to the fleet
*/
function registerFleetCommander() external;
/**
* @notice Unregisters the Fleet commander for the Ark
* @dev This function is used to unregister the Fleet commander for the Ark
* it's called by the FleetCommander when ark is removed from the fleet
* all balance checks are done within the FleetCommander
*/
function unregisterFleetCommander() external;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IFleetCommanderErrors} from "../errors/IFleetCommanderErrors.sol";
import {IFleetCommanderEvents} from "../events/IFleetCommanderEvents.sol";
import {RebalanceData} from "../types/FleetCommanderTypes.sol";
import {IFleetCommanderConfigProvider} from "./IFleetCommanderConfigProvider.sol";
import {IERC4626} from "@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol";
import {Percentage} from "@summerfi/percentage-solidity/contracts/Percentage.sol";
/**
* @title IFleetCommander Interface
* @notice Interface for the FleetCommander contract, which manages asset allocation across multiple Arks
*/
interface IFleetCommander is
IERC4626,
IFleetCommanderEvents,
IFleetCommanderErrors,
IFleetCommanderConfigProvider
{
/**
* @notice Returns the total assets that are currently withdrawable from the FleetCommander.
* @dev If cached data is available, it will be used. Otherwise, it will be calculated on demand (and cached)
* @return uint256 The total amount of assets that can be withdrawn.
*/
function withdrawableTotalAssets() external view returns (uint256);
/**
* @notice Returns the total assets that are managed the FleetCommander.
* @dev If cached data is available, it will be used. Otherwise, it will be calculated on demand (and cached)
* @return uint256 The total amount of assets that can be withdrawn.
*/
function totalAssets() external view returns (uint256);
/**
* @notice Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
* Vault, directly from Buffer.
* @param owner The address of the owner of the assets
* @return uint256 The maximum amount that can be withdrawn.
*/
function maxBufferWithdraw(address owner) external view returns (uint256);
/**
* @notice Returns the maximum amount of the underlying asset that can be redeemed from the owner balance in the
* Vault, directly from Buffer.
* @param owner The address of the owner of the assets
* @return uint256 The maximum amount that can be redeemed.
*/
function maxBufferRedeem(address owner) external view returns (uint256);
/* FUNCTIONS - PUBLIC - USER */
/**
* @notice Deposits a specified amount of assets into the contract for a given receiver.
* @param assets The amount of assets to be deposited.
* @param receiver The address of the receiver who will receive the deposited assets.
* @param referralCode An optional referral code that can be used for tracking or rewards.
*/
function deposit(
uint256 assets,
address receiver,
bytes memory referralCode
) external returns (uint256);
/**
* @notice Forces a withdrawal of assets from the FleetCommander
* @param assets The amount of assets to forcefully withdraw
* @param receiver The address that will receive the withdrawn assets
* @param owner The address of the owner of the assets
* @return shares The amount of shares redeemed
*/
function withdrawFromArks(
uint256 assets,
address receiver,
address owner
) external returns (uint256 shares);
/**
* @notice Withdraws a specified amount of assets from the FleetCommander
* @dev This function first attempts to withdraw from the buffer. If the buffer doesn't have enough assets,
* it will withdraw from the arks. It also handles the case where the maximum possible amount is requested.
* @param assets The amount of assets to withdraw. If set to type(uint256).max, it will withdraw the maximum
* possible amount.
* @param receiver The address that will receive the withdrawn assets
* @param owner The address of the owner of the shares
* @return shares The number of shares burned in exchange for the withdrawn assets
*/
function withdraw(
uint256 assets,
address receiver,
address owner
) external returns (uint256 shares);
/**
* @notice Redeems a specified amount of shares from the FleetCommander
* @dev This function first attempts to redeem from the buffer. If the buffer doesn't have enough assets,
* it will redeem from the arks. It also handles the case where the maximum possible amount is requested.
* @param shares The number of shares to redeem. If set to type(uint256).max, it will redeem all shares owned by the
* owner.
* @param receiver The address that will receive the redeemed assets
* @param owner The address of the owner of the shares
* @return assets The amount of assets received in exchange for the redeemed shares
*/
function redeem(
uint256 shares,
address receiver,
address owner
) external returns (uint256 assets);
/**
* @notice Redeems shares for assets from the FleetCommander
* @param shares The amount of shares to redeem
* @param receiver The address that will receive the assets
* @param owner The address of the owner of the shares
* @return assets The amount of assets forcefully withdrawn
*/
function redeemFromArks(
uint256 shares,
address receiver,
address owner
) external returns (uint256 assets);
/**
* @notice Redeems shares for assets directly from the Buffer
* @param shares The amount of shares to redeem
* @param receiver The address that will receive the assets
* @param owner The address of the owner of the shares
* @return assets The amount of assets redeemed
*/
function redeemFromBuffer(
uint256 shares,
address receiver,
address owner
) external returns (uint256 assets);
/**
* @notice Forces a withdrawal of assets directly from the Buffer
* @param assets The amount of assets to withdraw
* @param receiver The address that will receive the withdrawn assets
* @param owner The address of the owner of the assets
* @return shares The amount of shares redeemed
*/
function withdrawFromBuffer(
uint256 assets,
address receiver,
address owner
) external returns (uint256 shares);
/**
* @notice Accrues and distributes tips
* @return uint256 The amount of tips accrued
*/
function tip() external returns (uint256);
/**
* @notice Rebalances the assets across Arks, including buffer adjustments
* @param data Array of RebalanceData structs
* @dev RebalanceData struct contains:
* - fromArk: The address of the Ark to move assets from
* - toArk: The address of the Ark to move assets to
* - amount: The amount of assets to move
* - boardData: Additional data for the board operation
* - disembarkData: Additional data for the disembark operation
* @dev Using type(uint256).max as the amount will move all assets from the fromArk to the toArk
* @dev For standard rebalancing:
* - Operations cannot involve the buffer Ark directly
* @dev For buffer adjustments:
* - type(uint256).max is only allowed when moving TO the buffer
* - When withdrawing FROM buffer, total amount cannot reduce balance below minFundsBufferBalance
* @dev The number of operations in a single rebalance call is limited to MAX_REBALANCE_OPERATIONS
* @dev Rebalance is subject to a cooldown period between calls
* @dev Only callable by accounts with the Keeper role
*/
function rebalance(RebalanceData[] calldata data) external;
/* FUNCTIONS - EXTERNAL - GOVERNANCE */
/**
* @notice Sets a new tip rate for the FleetCommander
* @dev Only callable by the governor
* @dev The tip rate is set as a Percentage. Percentages use 18 decimals of precision
* For example, for a 5% rate, you'd pass 5 * 1e18 (5 000 000 000 000 000 000)
* @param newTipRate The new tip rate as a Percentage
*/
function setTipRate(Percentage newTipRate) external;
/**
* @notice Sets a new minimum pause time for the FleetCommander
* @dev Only callable by the governor
* @param newMinimumPauseTime The new minimum pause time in seconds
*/
function setMinimumPauseTime(uint256 newMinimumPauseTime) external;
/**
* @notice Updates the rebalance cooldown period
* @param newCooldown The new cooldown period in seconds
*/
function updateRebalanceCooldown(uint256 newCooldown) external;
/**
* @notice Forces a rebalance operation
* @param data Array of typed rebalance data struct
* @dev has no cooldown enforced but only callable by privileged role
*/
function forceRebalance(RebalanceData[] calldata data) external;
/**
* @notice Pauses the FleetCommander
* @dev This function is used to pause the FleetCommander in case of critical issues or emergencies
* @dev Only callable by the guardian or governor
*/
function pause() external;
/**
* @notice Unpauses the FleetCommander
* @dev This function is used to resume normal operations after a pause
* @dev Only callable by the guardian or governor
*/
function unpause() external;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IFleetCommanderConfigProviderErrors} from "../errors/IFleetCommanderConfigProviderErrors.sol";
import {IFleetCommanderConfigProviderEvents} from "../events/IFleetCommanderConfigProviderEvents.sol";
import {FleetConfig} from "../types/FleetCommanderTypes.sol";
import {Percentage} from "@summerfi/percentage-solidity/contracts/Percentage.sol";
/**
* @title IFleetCommander Interface
* @notice Interface for the FleetCommander contract, which manages asset allocation across multiple Arks
*/
interface IFleetCommanderConfigProvider is
IFleetCommanderConfigProviderErrors,
IFleetCommanderConfigProviderEvents
{
/**
* @notice Retrieves the ark address at the specified index
* @param index The index of the ark in the arks array
* @return The address of the ark at the specified index
*/
function arks(uint256 index) external view returns (address);
/**
* @notice Retrieves the arks currently linked to fleet (excluding the buffer ark)
*/
function getActiveArks() external view returns (address[] memory);
/**
* @notice Retrieves the current fleet config
*/
function getConfig() external view returns (FleetConfig memory);
/**
* @notice Retrieves the buffer ark address
*/
function bufferArk() external view returns (address);
/**
* @notice Checks if the ark is part of the fleet or is the buffer ark
* @param ark The address of the Ark
* @return bool Returns true if the ark is active or the buffer ark, false otherwise.
*/
function isArkActiveOrBufferArk(address ark) external view returns (bool);
/* FUNCTIONS - EXTERNAL - GOVERNANCE */
/**
* @notice Adds a new Ark
* @param ark The address of the new Ark
*/
function addArk(address ark) external;
/**
* @notice Removes an existing Ark
* @param ark The address of the Ark to remove
*/
function removeArk(address ark) external;
/**
* @notice Sets a new deposit cap for Fleet
* @param newDepositCap The new deposit cap
*/
function setFleetDepositCap(uint256 newDepositCap) external;
/**
* @notice Sets a new deposit cap for an Ark
* @param ark The address of the Ark
* @param newDepositCap The new deposit cap
*/
function setArkDepositCap(address ark, uint256 newDepositCap) external;
/**
* @notice Sets the max deposit percentage of TVL for an Ark
* @param ark The address of the Ark
* @param newMaxDepositPercentageOfTVL The new max deposit percentage of TVL
*/
function setArkMaxDepositPercentageOfTVL(
address ark,
Percentage newMaxDepositPercentageOfTVL
) external;
/**
* @dev Sets the minimum buffer balance for the fleet commander.
* @param newMinimumBalance The new minimum buffer balance to be set.
*/
function setMinimumBufferBalance(uint256 newMinimumBalance) external;
/**
* @dev Sets the minimum number of allowe rebalance operations.
* @param newMaxRebalanceOperations The new maximum allowed rebalance operations.
*/
function setMaxRebalanceOperations(
uint256 newMaxRebalanceOperations
) external;
/**
* @notice Sets the maxRebalanceOutflow for an Ark
* @dev Only callable by the governor
* @param ark The address of the Ark
* @param newMaxRebalanceOutflow The new maxRebalanceOutflow value
*/
function setArkMaxRebalanceOutflow(
address ark,
uint256 newMaxRebalanceOutflow
) external;
/**
* @notice Sets the maxRebalanceInflow for an Ark
* @dev Only callable by the governor
* @param ark The address of the Ark
* @param newMaxRebalanceInflow The new maxRebalanceInflow value
*/
function setArkMaxRebalanceInflow(
address ark,
uint256 newMaxRebalanceInflow
) external;
/**
* @notice Deploys and sets the staking rewards manager contract address
*/
function updateStakingRewardsManager() external;
/**
* @notice Enables or disables transfers of fleet commander shares
* @dev Only callable by the governor when not paused
*/
function setFleetTokenTransferability() external;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IStakingRewardsManagerBase} from "@summerfi/rewards-contracts/interfaces/IStakingRewardsManagerBase.sol";
/**
* @title IFleetCommanderRewardsManager
* @notice Interface for the FleetStakingRewardsManager contract
* @dev Extends IStakingRewardsManagerBase with Fleet-specific functionality
*/
interface IFleetCommanderRewardsManager is IStakingRewardsManagerBase {
/**
* @notice Returns the address of the FleetCommander contract
* @return The address of the FleetCommander
*/
function fleetCommander() external view returns (address);
/**
* @notice Thrown when a non-AdmiralsQuarters contract tries
* to unstake on behalf
*/
error CallerNotAdmiralsQuarters();
/**
* @notice Thrown when AdmiralsQuarters tries to unstake for
* someone other than msg.sender
*/
error InvalidUnstakeRecipient();
/* @notice Thrown when trying to add a staking token as a reward token */
error CantAddStakingTokenAsReward();
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
interface IDistributor {
function toggleOperator(address user, address operator) external;
function claim(
address[] calldata users,
address[] calldata tokens,
uint256[] calldata amounts,
bytes32[][] calldata proofs
) external;
function operators(
address user,
address operator
) external view returns (uint256);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.5.0;
/// @notice The pending root struct for a merkle tree distribution during the timelock.
struct PendingRoot {
/// @dev The submitted pending root.
bytes32 root;
/// @dev The optional ipfs hash containing metadata about the root (e.g. the merkle tree itself).
bytes32 ipfsHash;
/// @dev The timestamp at which the pending root can be accepted.
uint256 validAt;
}
/// @dev This interface is used for factorizing IUniversalRewardsDistributorStaticTyping and
/// IUniversalRewardsDistributor.
/// @dev Consider using the IUniversalRewardsDistributor interface instead of this one.
interface IUniversalRewardsDistributor {
function setRoot(bytes32 newRoot, bytes32 newIpfsHash) external;
function claim(
address account,
address reward,
uint256 claimable,
bytes32[] memory proof
) external returns (uint256 amount);
event Claimed(
address indexed account,
address indexed reward,
uint256 amount
);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Percentage} from "@summerfi/percentage-solidity/contracts/Percentage.sol";
/**
* @title ArkParams
* @notice Constructor parameters for the Ark contract
*
* @dev This struct is used to initialize an Ark contract with all necessary parameters
*/
struct ArkParams {
/**
* @notice The name of the Ark
* @dev This should be a unique, human-readable identifier for the Ark
*/
string name;
/**
* @notice Additional details about the Ark
* @dev This can be used to store additional information about the Ark
*/
string details;
/**
* @notice The address of the access manager contract
* @dev This contract manages roles and permissions for the Ark
*/
address accessManager;
/**
* @notice The address of the configuration manager contract
* @dev This contract stores global configuration parameters
*/
address configurationManager;
/**
* @notice The address of the ERC20 token managed by this Ark
* @dev This is the underlying asset that the Ark will handle
*/
address asset;
/**
* @notice The maximum amount of tokens that can be deposited into the Ark
* @dev This cap helps to manage risk and exposure
*/
uint256 depositCap;
/**
* @notice The maximum amount of tokens that can be moved from this Ark in a single transaction
* @dev This limit helps to prevent large, sudden outflows
*/
uint256 maxRebalanceOutflow;
/**
* @notice The maximum amount of tokens that can be moved to this Ark in a single transaction
* @dev This limit helps to prevent large, sudden inflows
*/
uint256 maxRebalanceInflow;
/**
* @notice Whether the Ark requires Keepr data to be passed in with rebalance transactions
* @dev This flag is used to determine whether Keepr data is required for rebalance transactions
*/
bool requiresKeeperData;
/**
* @notice The maximum percentage of Total Value Locked (TVL) that can be deposited into this Ark
* @dev This value is represented as a percentage with 18 decimal places (1e18 = 100%)
* For example, 0.5e18 represents 50% of TVL
*/
Percentage maxDepositPercentageOfTVL;
}
/**
* @title ArkConfig
* @notice Configuration of the Ark contract
* @dev This struct stores the current configuration of an Ark, which can be updated during its lifecycle
*/
struct ArkConfig {
/**
* @notice The address of the commander (typically a FleetCommander contract)
* @dev The commander has special permissions to manage the Ark
*/
address commander;
/**
* @notice The address of the associated Raft contract
* @dev The Raft contract handles reward distribution and other protocol-wide functions
*/
address raft;
/**
* @notice The ERC20 token interface for the asset managed by this Ark
* @dev This allows direct interaction with the token contract
*/
IERC20 asset;
/**
* @notice The current maximum amount of tokens that can be deposited into the Ark
* @dev This can be adjusted by the commander to manage capacity
*/
uint256 depositCap;
/**
* @notice The current maximum amount of tokens that can be moved from this Ark in a single transaction
* @dev This can be adjusted to manage liquidity and risk
*/
uint256 maxRebalanceOutflow;
/**
* @notice The current maximum amount of tokens that can be moved to this Ark in a single transaction
* @dev This can be adjusted to manage inflows and capacity
*/
uint256 maxRebalanceInflow;
/**
* @notice The name of the Ark
* @dev This is typically set at initialization and not changed
*/
string name;
/**
* @notice Additional details about the Ark
* @dev This can be used to store additional information about the Ark
*/
string details;
/**
* @notice Whether the Ark requires Keeper data to be passed in with rebalance transactions
* @dev This flag is used to determine whether Keeper data is required for rebalance transactions
*/
bool requiresKeeperData;
/**
* @notice The maximum percentage of Total Value Locked (TVL) that can be deposited into this Ark
* @dev This value is represented as a percentage with 18 decimal places (1e18 = 100%)
* For example, 0.5e18 represents 50% of TVL
*/
Percentage maxDepositPercentageOfTVL;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IArk} from "../interfaces/IArk.sol";
import {IFleetCommanderRewardsManager} from "../interfaces/IFleetCommanderRewardsManager.sol";
import {Percentage} from "@summerfi/percentage-solidity/contracts/Percentage.sol";
/**
* @notice Configuration parameters for the FleetCommander contract
*/
struct FleetCommanderParams {
string name;
string details;
string symbol;
address configurationManager;
address accessManager;
address asset;
uint256 initialMinimumBufferBalance;
uint256 initialRebalanceCooldown;
uint256 depositCap;
Percentage initialTipRate;
}
/**
* @title FleetConfig
* @notice Configuration parameters for the FleetCommander contract
* @dev This struct encapsulates the mutable configuration settings of a FleetCommander.
* These parameters can be updated during the contract's lifecycle to adjust its behavior.
*/
struct FleetConfig {
/**
* @notice The buffer Ark associated with this FleetCommander
* @dev This Ark is used as a temporary holding area for funds before they are allocated
* to other Arks or when they need to be quickly accessed for withdrawals.
*/
IArk bufferArk;
/**
* @notice The minimum balance that should be maintained in the buffer Ark
* @dev This value is used to ensure there's always a certain amount of funds readily
* available for withdrawals or rebalancing operations. It's denominated in the
* smallest unit of the underlying asset (e.g., wei for ETH).
*/
uint256 minimumBufferBalance;
/**
* @notice The maximum total value of assets that can be deposited into the FleetCommander
* @dev This cap helps manage the total assets under management and can be used to
* implement controlled growth strategies. It's denominated in the smallest unit
* of the underlying asset.
*/
uint256 depositCap;
/**
* @notice The maximum number of rebalance operations in a single rebalance
*/
uint256 maxRebalanceOperations;
/**
* @notice The address of the staking rewards contract
*/
address stakingRewardsManager;
}
/**
* @notice Data structure for the rebalance event
* @param fromArk The address of the Ark from which assets are moved
* @param toArk The address of the Ark to which assets are moved
* @param amount The amount of assets being moved
* @param boardData The data to be passed to the `board` function of the `toArk`
* @param disembarkData The data to be passed to the `disembark` function of the `fromArk`
* @dev if the `boardData` or `disembarkData` is not needed, it should be an empty byte array
*/
struct RebalanceData {
address fromArk;
address toArk;
uint256 amount;
bytes boardData;
bytes disembarkData;
}
/**
* @title ArkData
* @dev Struct to store information about an Ark.
* This struct holds the address of the Ark and the total assets it holds.
* @dev used in the caching mechanism for the FleetCommander
*/
struct ArkData {
/// @notice The address of the Ark.
address arkAddress;
/// @notice The total assets held by the Ark.
uint256 totalAssets;
}{
"optimizer": {
"enabled": true,
"runs": 25
},
"evmVersion": "cancun",
"viaIR": true,
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"_metaMorpho","type":"address"},{"internalType":"address","name":"_urdFactory","type":"address"},{"components":[{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"details","type":"string"},{"internalType":"address","name":"accessManager","type":"address"},{"internalType":"address","name":"configurationManager","type":"address"},{"internalType":"address","name":"asset","type":"address"},{"internalType":"uint256","name":"depositCap","type":"uint256"},{"internalType":"uint256","name":"maxRebalanceOutflow","type":"uint256"},{"internalType":"uint256","name":"maxRebalanceInflow","type":"uint256"},{"internalType":"bool","name":"requiresKeeperData","type":"bool"},{"internalType":"Percentage","name":"maxDepositPercentageOfTVL","type":"uint256"}],"internalType":"struct ArkParams","name":"_params","type":"tuple"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotAdmin","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotAuthorizedToBoard","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotCommander","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"},{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"CallerIsNotContractSpecificRole","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotCurator","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotDecayController","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotFoundation","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotGovernor","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotGuardian","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotGuardianOrGovernor","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotKeeper","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotRaft","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotRaftOrCommander","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotSuperKeeper","type":"error"},{"inputs":[],"name":"CannotAddCommanderToArkWithCommander","type":"error"},{"inputs":[],"name":"CannotDeployArkWithEmptyName","type":"error"},{"inputs":[],"name":"CannotDeployArkWithoutConfigurationManager","type":"error"},{"inputs":[],"name":"CannotDeployArkWithoutRaft","type":"error"},{"inputs":[],"name":"CannotDeployArkWithoutToken","type":"error"},{"inputs":[],"name":"CannotRemoveCommanderFromArkWithAssets","type":"error"},{"inputs":[],"name":"CannotUseKeeperDataWhenNotRequired","type":"error"},{"inputs":[],"name":"ConfigurationManagerZeroAddress","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"DirectGrantIsDisabled","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"DirectRevokeIsDisabled","type":"error"},{"inputs":[],"name":"ERC4626AssetMismatch","type":"error"},{"inputs":[],"name":"FleetCommanderAlreadyRegistered","type":"error"},{"inputs":[],"name":"FleetCommanderNotRegistered","type":"error"},{"inputs":[{"internalType":"address","name":"invalidAddress","type":"address"}],"name":"InvalidAccessManagerAddress","type":"error"},{"inputs":[],"name":"InvalidBoardData","type":"error"},{"inputs":[],"name":"InvalidDisembarkData","type":"error"},{"inputs":[],"name":"InvalidUrdAddress","type":"error"},{"inputs":[],"name":"InvalidUrdFactoryAddress","type":"error"},{"inputs":[],"name":"InvalidVaultAddress","type":"error"},{"inputs":[],"name":"KeeperDataRequired","type":"error"},{"inputs":[],"name":"MaxDepositPercentageOfTVLTooHigh","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address[]","name":"rewardTokens","type":"address[]"},{"indexed":true,"internalType":"uint256[]","name":"rewardAmounts","type":"uint256[]"}],"name":"ArkHarvested","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"currentPrice","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"ArkPoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address[]","name":"sweptTokens","type":"address[]"},{"indexed":true,"internalType":"uint256[]","name":"sweptAmounts","type":"uint256[]"}],"name":"ArkSwept","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"commander","type":"address"},{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Boarded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newCap","type":"uint256"}],"name":"DepositCapUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"commander","type":"address"},{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Disembarked","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"commander","type":"address"}],"name":"FleetCommanderRegistered","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"commander","type":"address"}],"name":"FleetCommanderUnregistered","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"Percentage","name":"newMaxDepositPercentageOfTVL","type":"uint256"}],"name":"MaxDepositPercentageOfTVLUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newMaxInflow","type":"uint256"}],"name":"MaxRebalanceInflowUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newMaxOutflow","type":"uint256"}],"name":"MaxRebalanceOutflowUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Moved","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newRaft","type":"address"}],"name":"RaftUpdated","type":"event"},{"inputs":[],"name":"ADMIRALS_QUARTERS_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DECAY_CONTROLLER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"GOVERNOR_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"GUARDIAN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SUPER_KEEPER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"URD_FACTORY","outputs":[{"internalType":"contract IUrdFactory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"asset","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"boardData","type":"bytes"}],"name":"board","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"commander","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"config","outputs":[{"internalType":"address","name":"commander","type":"address"},{"internalType":"address","name":"raft","type":"address"},{"internalType":"contract IERC20","name":"asset","type":"address"},{"internalType":"uint256","name":"depositCap","type":"uint256"},{"internalType":"uint256","name":"maxRebalanceOutflow","type":"uint256"},{"internalType":"uint256","name":"maxRebalanceInflow","type":"uint256"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"details","type":"string"},{"internalType":"bool","name":"requiresKeeperData","type":"bool"},{"internalType":"Percentage","name":"maxDepositPercentageOfTVL","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"configurationManager","outputs":[{"internalType":"contract IConfigurationManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"depositCap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"details","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"disembarkData","type":"bytes"}],"name":"disembark","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"fleetCommanderRewardsManagerFactory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"enum ContractSpecificRoles","name":"roleName","type":"uint8"},{"internalType":"address","name":"roleTargetContract","type":"address"}],"name":"generateRole","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"getConfig","outputs":[{"components":[{"internalType":"address","name":"commander","type":"address"},{"internalType":"address","name":"raft","type":"address"},{"internalType":"contract IERC20","name":"asset","type":"address"},{"internalType":"uint256","name":"depositCap","type":"uint256"},{"internalType":"uint256","name":"maxRebalanceOutflow","type":"uint256"},{"internalType":"uint256","name":"maxRebalanceInflow","type":"uint256"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"details","type":"string"},{"internalType":"bool","name":"requiresKeeperData","type":"bool"},{"internalType":"Percentage","name":"maxDepositPercentageOfTVL","type":"uint256"}],"internalType":"struct ArkConfig","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"harborCommand","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"additionalData","type":"bytes"}],"name":"harvest","outputs":[{"internalType":"address[]","name":"rewardTokens","type":"address[]"},{"internalType":"uint256[]","name":"rewardAmounts","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"hasAdmiralsQuartersRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxDepositPercentageOfTVL","outputs":[{"internalType":"Percentage","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxRebalanceInflow","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxRebalanceOutflow","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"metaMorpho","outputs":[{"internalType":"contract IMetaMorpho","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"receiverArk","type":"address"},{"internalType":"bytes","name":"boardData","type":"bytes"},{"internalType":"bytes","name":"disembarkData","type":"bytes"}],"name":"move","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"raft","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"registerFleetCommander","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"requiresKeeperData","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"newDepositCap","type":"uint256"}],"name":"setDepositCap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"Percentage","name":"newMaxDepositPercentageOfTVL","type":"uint256"}],"name":"setMaxDepositPercentageOfTVL","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newMaxRebalanceInflow","type":"uint256"}],"name":"setMaxRebalanceInflow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newMaxRebalanceOutflow","type":"uint256"}],"name":"setMaxRebalanceOutflow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"tokens","type":"address[]"}],"name":"sweep","outputs":[{"internalType":"address[]","name":"sweptTokens","type":"address[]"},{"internalType":"uint256[]","name":"sweptAmounts","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"tipJar","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalAssets","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"treasury","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unregisterFleetCommander","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"}],"name":"whitelistMerklOperator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"withdrawableTotalAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]Contract Creation Code
61010080604052346106c4576132e6803803809161001d828561070a565b833981016060828203126106c4576100348261072d565b906100416020840161072d565b604084015190936001600160401b0382116106c4570190610140828203126106c45760405190610070826106ee565b82516001600160401b0381116106c4578161008c918501610741565b82526020830151906001600160401b0382116106c4576100ad918401610741565b91602082019283526100c16040820161072d565b928360408401526100d46060830161072d565b928360608201526100e76080840161072d565b946080820195865260a08401519560a0830196875260c08501519060c0840191825260e08601519260e085019384526101206101266101008901610796565b61010087019081529701516101208601908152976001600160a01b03908116911680156106db576040516301ffc9a760e01b815263261c910560e21b6004820152602081602481855afa9081156106d0575f91610692575b50156106805760805280156106715760a05280516001600160a01b0316156106625783515115610653576001600160a01b036101b86107a3565b16156106445768056bc75e2d6310000087511161063557516001600160a01b03166101e16107a3565b975191519251935194519551151596519761012060405191610202836106ee565b5f8084526001600160a01b03919091166020840181905260408401859052606084018690526080840187905260a0840188905260c0840189905260e08401998a5261010084019a8b5291909201998a5281546001600160a01b031990811690925560018054831690911790556002805490911690911790556003556004556005558051906001600160401b0382116105385760065490600182811c9216801561062b575b602083101461051a5781601f8493116105bd575b50602090601f8311600114610557575f9261054c575b50508160011b915f199060031b1c1916176006555b518051906001600160401b0382116105385760075490600182811c9216801561052e575b602083101461051a5781601f8493116104ac575b50602090601f8311600114610446575f9261043b575b50508160011b915f199060031b1c1916176007555b51151560ff8019600854169116176008555160095560018060a01b031690811561042c576001600160a01b0316801561041d5760e05260c052604051612ad5908161081182396080518181816103430152818161104b0152611f66015260a0518181816101f7015281816109ec015281816111980152818161185b015281816118cd01526125ef015260c051818181610c3601528181610e1201528181610ef201528181611b0201528181611d5101528181611e75015281816124c80152612759015260e0518181816103e1015261061a0152f35b6302fe89d560e11b5f5260045ffd5b630306120160e01b5f5260045ffd5b015190505f80610333565b60075f9081528281209350601f198516905b818110610494575090846001959493921061047c575b505050811b01600755610348565b01515f1960f88460031b161c191690555f808061046e565b92936020600181928786015181550195019301610458565b60075f529091507fa66cc928b5edb82af9bd49922954155ab7b0942694bea4ce44661d9a8736c688601f840160051c81019160208510610510575b90601f859493920160051c01905b818110610502575061031d565b5f81558493506001016104f5565b90915081906104e7565b634e487b7160e01b5f52602260045260245ffd5b91607f1691610309565b634e487b7160e01b5f52604160045260245ffd5b015190505f806102d0565b60065f9081528281209350601f198516905b8181106105a5575090846001959493921061058d575b505050811b016006556102e5565b01515f1960f88460031b161c191690555f808061057f565b92936020600181928786015181550195019301610569565b60065f529091507ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f601f840160051c81019160208510610621575b90601f859493920160051c01905b81811061061357506102ba565b5f8155849350600101610606565b90915081906105f8565b91607f16916102a6565b634ef9dfe360e01b5f5260045ffd5b633a4f9cdb60e21b5f5260045ffd5b63268c072960e01b5f5260045ffd5b637ff57ef160e11b5f5260045ffd5b63f1634df960e01b5f5260045ffd5b6347bd7c1d60e01b5f5260045260245ffd5b90506020813d6020116106c8575b816106ad6020938361070a565b810103126106c4576106be90610796565b5f61017e565b5f80fd5b3d91506106a0565b6040513d5f823e3d90fd5b6347bd7c1d60e01b5f525f60045260245ffd5b61014081019081106001600160401b0382111761053857604052565b601f909101601f19168101906001600160401b0382119082101761053857604052565b51906001600160a01b03821682036106c457565b81601f820112156106c4578051906001600160401b0382116105385760405192610775601f8401601f19166020018561070a565b828452602083830101116106c457815f9260208093018386015e8301015290565b519081151582036106c457565b60a051604051628bec5760e51b815290602090829060049082906001600160a01b03165afa9081156106d0575f916107d9575090565b90506020813d602011610808575b816107f46020938361070a565b810103126106c4576108059061072d565b90565b3d91506107e756fe60806040526004361015610011575f80fd5b5f5f3560e01c806301e1d114146120f857806306fdde03146120dd5780630af02e5014611f23578063117d8ae014611ef657806313c408f814611cea57806324ea54f414611caf5780632db6d39914611a52578063303dbaf314611a2f5780633194549e14611a1157806337270936146119ea57806338d52e0f146119c15780634fc7fac314611949578063565974d3146119195780635b0f83f3146118a757806361d027b31461183557806361f5cd8b146117dc57806366e943f1146117b457806369b3054b14611750578063780469bb1461129557806379502c55146111e45780637aaceb951461117257806386651203146111195780638a8b997614610fd357806392f5e83214610f67578063a89f38a314610f3f578063ad5a356f14610f21578063b6042b3414610edc578063bdcdd88214610ebe578063c0b534c214610e83578063c38a6f0b14610b95578063c3f909d414610a1b578063c9c667e3146109d6578063ccc574901461099b578063ce5c7f6114610433578063d570ee4714610410578063dbb7cbc5146103cb578063dbd5edc7146103ad578063ebc136d0146102ec578063ebf311311461027f5763f7e533ec146101d2575f80fd5b3461027c578060031936011261027c57604051633df94cfb60e21b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa9081156102715760209291610244575b506040516001600160a01b039091168152f35b6102649150823d841161026a575b61025c81836121f2565b8101906125bc565b5f610231565b503d610252565b6040513d84823e3d90fd5b80fd5b503461027c578060031936011261027c5780546001600160a01b03811633036102dd576001600160a01b03191681556040513381527f7cb941d7b1708e5b3bcd35ca960d6c6311188cec18886e5b67630552676b048790602090a180f35b63430da47160e01b8252600482fd5b503461027c57602036600319011261027c57610306612136565b604051632474521560e21b81525f516020612a005f395f51905f5260048201526001600160a01b03918216602482015290602090829060449082907f0000000000000000000000000000000000000000000000000000000000000000165afa9081156102715760209291610380575b506040519015158152f35b6103a09150823d84116103a6575b61039881836121f2565b8101906125a4565b5f610375565b503d61038e565b503461027c578060031936011261027c576020600354604051908152f35b503461027c578060031936011261027c576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b503461027c578060031936011261027c57602061042b612738565b604051908152f35b503461027c57602036600319011261027c576004356001600160401b03811161095a57610464903690600401612162565b604051628bec5760e51b8152919291602081600481305afa908115610990578391610971575b506001600160a01b0316330361095e576104a261280a565b82019160208184031261095a578035906001600160401b03821161094257019060808284031261027c5760405191608083018381106001600160401b038211176109465760405280356001600160401b038111610942578461050591830161222a565b835260208101356001600160401b038111610942578461052691830161222a565b936020840194855260408201356001600160401b03811161092a5782019181601f8401121561092a5782359261055b84612213565b9361056960405195866121f2565b80855260208086019160051b8301019184831161092657602001905b82821061093257505050604085019283526060810135906001600160401b03821161092e57019080601f8301121561092a578135916105c383612213565b926105d160405194856121f2565b80845260208085019160051b830101918383116109265760208101915b83831061089e5750505050506060840190815261060c855151612661565b90610618865151612661565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031695909390855b8851518110156108305781516001600160a01b0390610668908390612693565b516040516309bf142360e01b8152911660048201526020816024818c5afa9081156107d9578891610812575b50156108035781516001600160a01b03906106b0908390612693565b51169060018060a01b036106c5828c51612693565b5116916106d3828651612693565b516106df838851612693565b51918a604051958693637d5f6a0960e11b8552608485019130600487015260248601526044850152608060648501528451809152602060a4850195019082905b8082106107e45750505082908160209503925af19182156107d95788926107a0575b50895160019261079a916001600160a01b039061075f908590612693565b511661076b848a612693565b5280610777848b612693565b528b61078a84868060a01b039251612693565b51166107946125db565b906128b0565b01610648565b91506020823d82116107d1575b816107ba602093836121f2565b810103126107cd5790519061079a610741565b5f80fd5b3d91506107ad565b6040513d8a823e3d90fd5b825187526020968701968996508f94509092019160019091019061071f565b63a953048960e01b8752600487fd5b61082a915060203d81116103a65761039881836121f2565b5f610694565b868561089a8861083f836126bb565b610848826126fe565b905f516020612a805f395f51905f528680a3610863836126bb565b9261086d826126fe565b946040519586955f516020612a805f395f51905f528380a35f516020612a605f395f51905f525d83612298565b0390f35b82356001600160401b03811161092257820185603f82011215610922576020810135906108ca82612213565b916108d860405193846121f2565b8083526020808085019260051b840101019188831161091e57604001905b82821061090e575050508152602092830192016105ee565b81358152602091820191016108f6565b8b80fd5b8880fd5b8680fd5b8380fd5b8480fd5b8135815260209182019101610585565b8280fd5b634e487b7160e01b83526041600452602483fd5b5080fd5b631184b31b60e21b825233600452602482fd5b61098a915060203d60201161026a5761025c81836121f2565b5f61048a565b6040513d85823e3d90fd5b503461027c578060031936011261027c5760206040517f7935bd0ae54bc31f548c14dba4d37c5c64b3f8ca900cb468fb8abd54d5894f558152f35b503461027c578060031936011261027c576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b503461027c578060031936011261027c5780610120604051610a3c816121c2565b8281528260208201528260408201528260608201528260808201528260a0820152606060c0820152606060e082015282610100820152015260405190610a81826121c2565b546001600160a01b03908116825260015481166020830190815260025490911660408301908152600354606084019081526004546080850190815260055460a08601908152939493919291610b809190610b6c90610add612313565b9060c08801918252610aed6123f5565b60e089810191825260085460ff1615156101008b019081526009546101208c019081526040805160208082529d516001600160a01b039081169e82019e909e529d518d16908e01529851909a1660608c0152975160808b0152935160a08a01525160c08901525161014095880195909552869594610160870190612112565b9051858203601f1901610100870152612112565b91511515610120840152516101408301520390f35b503461027c57608036600319011261027c57600435610bb261214c565b6044356001600160401b03811161092a57610bd1903690600401612162565b6064939193356001600160401b038111610e7f57610bf3903690600401612162565b86549091906001600160a01b03163303610e6c57869291610c139161283f565b610c1b6124b0565b8303610ded576040516370a0823160e01b81523060048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690602081602481855afa908115610de2578491610da9575b50610c9f8492602092604051948580948193635d043b2960e11b83523090309060048501612890565b03925af1801561099057610d7a575b505b6002546001600160a01b031693610cc88482876128ea565b6001600160a01b031694853b156109425781606484926040519485938492632db6d39960e01b845289600485015260406024850152816044850152848401378181018301859052601f01601f1916810103018183895af1801561027157610d65575b5050610d5f7f9f784fc02a186f1c98b2d9f15fda084da27cdd291a3785d978f91911d880516b91604051918291309583612646565b0390a380f35b81610d6f916121f2565b61092a57835f610d2a565b610d9b9060203d602011610da2575b610d9381836121f2565b8101906124a1565b505f610cae565b503d610d89565b919350506020813d602011610dda575b81610dc6602093836121f2565b810103126107cd5751869290610c9f610c76565b3d9150610db9565b6040513d86823e3d90fd5b604051632d182be560e21b815260208180610e0d30808960048501612890565b0381867f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165af1801561099057610e4d575b50610cb0565b610e659060203d602011610da257610d9381836121f2565b505f610e47565b631564c0e160e11b875233600452602487fd5b8580fd5b503461027c578060031936011261027c5760206040517f025d8bbf3268be680d2605ebf6da15063b9915615bf1087dab336efc1bf970cb8152f35b503461027c578060031936011261027c576020600954604051908152f35b503461027c578060031936011261027c576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b503461027c578060031936011261027c576020600554604051908152f35b503461027c578060031936011261027c5760206040515f516020612a005f395f51905f528152f35b503461027c57602036600319011261027c578054600435906001600160a01b03163303610fc0576020817fb6ac66853c4e59c71e118d25ab494bb847c4e5eb0c8894898c5343e6f61afc1292600555604051908152a180f35b631564c0e160e11b825233600452602482fd5b503461027c578060031936011261027c57604051600160f91b60208281019182523060601b6001600160601b0319166021840152601583526110479290919061101d6035826121f2565b519020604051632474521560e21b8152600481019190915233602482015291829081906044820190565b03817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa9081156102715782916110fa575b50156110e75780546001600160a01b0381166110d8576001600160a01b0319163390811782556040519081527f55489ce0259bd691120d8860861be1c401c7c16a3cd268d21045756af4ecc5ca90602090a180f35b636a79b97d60e11b8252600482fd5b631564c0e160e11b815233600452602490fd5b611113915060203d6020116103a65761039881836121f2565b5f611083565b503461027c57602036600319011261027c578054600435906001600160a01b03163303610fc0576020817f333b26cca69716ad4680ddb07663f5bfb4f06045671f336af9a83690a3ae00f992600355604051908152a180f35b503461027c578060031936011261027c57604051637aaceb9560e01b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610271576020929161024457506040516001600160a01b039091168152f35b503461027c578060031936011261027c57546001546002546003546004546005546001600160a01b039485169585169492939092169161128291906112749061122b612313565b906112346123f5565b9360ff6008541697600954976040519b8c9b8c5260208c015260408b015260608a0152608089015260a088015261014060c0880152610140870190612112565b9085820360e0870152612112565b9115156101008401526101208301520390f35b503461027c57602036600319011261027c576004356001600160401b03811161095a576112c690369060040161222a565b604051628bec5760e51b8152602081600481305afa908115610990578391611731575b506001600160a01b0316330361095e5761130161280a565b61130b8151612661565b906113168151612661565b600254845460405163c8169aa160e01b81529294926001600160a01b0392831692909160209183916004918391165afa9081156114f5578691611712575b506040516370a0823160e01b8152306004820152602081602481865afa9081156116c25787916116e0575b501515806116cd575b611559575b5050835b82518110156115005760249060206001600160a01b036113b18387612693565b5116604051938480926370a0823160e01b82523060048301525afa9182156114f55786926114c2575b50816113eb575b6001915001611391565b6001600160a01b036113fd8286612693565b511691602461140a6125db565b9360206001600160a01b0361141f868a612693565b5116604051938480926370a0823160e01b82523060048301525afa9182156114b7578992611483575b5090600194611456926128b0565b828060a01b036114668387612693565b51166114728386612693565b5261147d8287612693565b526113e1565b91506020823d82116114af575b8161149d602093836121f2565b810103126107cd579051906001611448565b3d9150611490565b6040513d8b823e3d90fd5b9091506020813d82116114ed575b816114dd602093836121f2565b810103126107cd5751905f6113da565b3d91506114d0565b6040513d88823e3d90fd5b848261089a8661150f836126bb565b92611519826126fe565b946040519586957f46b8771620f6acf56cb03d3e835ea8024c7dcbcf05fcc3f6ade9e19d1a3e212b8380a35f516020612a605f395f51905f525d83612298565b6040516370a0823160e01b8152306004820152602081602481865afa9081156116c257879161168f575b5081611594602092602494866128ea565b6040516370a0823160e01b81523060048201526001600160a01b0391909116939092839182905afa9081156114f557869161165d575b50604051602081018181106001600160401b038211176116495760405286815286929190823b1561092a5761162592849283604051809681958294632db6d39960e01b84526004840152604060248401526044830190612112565b03925af18015610271571561138d578161163e916121f2565b61092a57835f61138d565b634e487b7160e01b88526041600452602488fd5b90506020813d602011611687575b81611678602093836121f2565b810103126107cd57515f6115ca565b3d915061166b565b90506020813d6020116116ba575b816116aa602093836121f2565b810103126107cd57516024611583565b3d915061169d565b6040513d89823e3d90fd5b50306001600160a01b0382161415611388565b90506020813d60201161170a575b816116fb602093836121f2565b810103126107cd57515f61137f565b3d91506116ee565b61172b915060203d60201161026a5761025c81836121f2565b5f611354565b61174a915060203d60201161026a5761025c81836121f2565b5f6112e9565b503461027c57604036600319011261027c57600435600381101561095a5760209161177961214c565b9050604051908382019260f81b835260018060601b03199060601b166021820152601581526117a96035826121f2565b519020604051908152f35b503461027c578060031936011261027c5760206040515f516020612a205f395f51905f528152f35b503461027c57602036600319011261027c578054600435906001600160a01b03163303610fc0576020817ffbe2d5c01ea8ba5596d6c4e6c82c6d4a0a0ee1128689993a4a5ba0169273d69f92600455604051908152a180f35b503461027c578060031936011261027c576040516361d027b360e01b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610271576020929161024457506040516001600160a01b039091168152f35b503461027c578060031936011261027c57604051635b0f83f360e01b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610271576020929161024457506040516001600160a01b039091168152f35b503461027c578060031936011261027c5761089a6119356123f5565b604051918291602083526020830190612112565b503461027c57602036600319011261027c578054600435906001600160a01b03163303610fc05768056bc75e2d6310000081116119b2576020817fd3c6d0ab315f2f1352f036cd9f401b49e38e1b90907e195225e8105f9a0b6f0292600955604051908152a180f35b634ef9dfe360e01b8252600482fd5b503461027c578060031936011261027c576002546040516001600160a01b039091168152602090f35b503461027c578060031936011261027c57546040516001600160a01b039091168152602090f35b503461027c578060031936011261027c576020600454604051908152f35b503461027c578060031936011261027c57602060ff600854166040519015158152f35b503461027c57611a613661218f565b90611a6a61280a565b604051631b93849b60e11b8152602081600481305afa908115611c66578591611c90575b506001600160a01b0316338103611bc9575b5090611aab9161283f565b8160018060a01b036002541691611af26040516323b872dd60e01b602082015233602482015230604482015282606482015260648152611aec6084826121f2565b846129a7565b6002546020906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811691611b329185918491166128ea565b604460405180958193636e553f6560e01b83528660048401523060248401525af1908115610de2577fcbaa1442ac205415c9d69643e7b60ec73d1de35dbc807c21ec288c70ddc4207b92611b9492611baa575b50604051918291339583612646565b0390a2805f516020612a605f395f51905f525d80f35b611bc29060203d602011610da257610d9381836121f2565b505f611b85565b604051628bec5760e51b8152602081600481305afa9081156114f5578691611c71575b506001600160a01b03163314611aa05760206024916040519283809263d206a05960e01b82523360048301525afa908115611c66578591611c47575b5015611c34575f611aa0565b638f7a567d60e01b845233600452602484fd5b611c60915060203d6020116103a65761039881836121f2565b5f611c28565b6040513d87823e3d90fd5b611c8a915060203d60201161026a5761025c81836121f2565b5f611bec565b611ca9915060203d60201161026a5761025c81836121f2565b5f611a8e565b503461027c578060031936011261027c5760206040517f55435dd261a4b9b3364963f7738a7a662ad9c84396d64be3365284bb7f0a50418152f35b503461027c57611cf93661218f565b83549091906001600160a01b03163303611ee35790611d1f91611d1a61280a565b61283f565b6002546001600160a01b0316908290611d366124b0565b8103611e4e576040516370a0823160e01b81523060048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690602081602481855afa908115610de2578491611e16575b50602091611db991604051958680948193635d043b2960e11b83523090309060048501612890565b03925af1908115610de2575f516020612a405f395f51905f5292611b9492611df7575b505b611de98133866128b0565b604051918291339583612646565b611e0f9060203d602011610da257610d9381836121f2565b505f611ddc565b9350506020833d602011611e46575b81611e32602093836121f2565b810103126107cd5791518492906020611d91565b3d9150611e25565b604051632d182be560e21b8152915060208280611e7030808660048501612890565b0381877f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165af1908115610de2575f516020612a405f395f51905f5292611b9492611ec4575b50611dde565b611edc9060203d602011610da257610d9381836121f2565b505f611ebe565b631564c0e160e11b845233600452602484fd5b503461027c578060031936011261027c576020611f116125db565b6040516001600160a01b039091168152f35b50346107cd5760203660031901126107cd57611f3d612136565b604051600160f81b60208281019182523060601b6001600160601b0319166021840152601583527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031692611f9f929061101d6035826121f2565b0381855afa908115612037575f916120be575b50159081612055575b5061204257733ef3d8ba38ebe18db133cec108f4d14ce00dd9ae3b156107cd5760405163bdac7ca360e01b81523060048201526001600160a01b0390911660248201525f8160448183733ef3d8ba38ebe18db133cec108f4d14ce00dd9ae5af1801561203757612029575080f35b61203591505f906121f2565b005b6040513d5f823e3d90fd5b6329068e8160e21b5f523360045260245ffd5b604051632474521560e21b81525f516020612a205f395f51905f5260048201523360248201529150602090829060449082905afa908115612037575f9161209f575b50155f611fbb565b6120b8915060203d6020116103a65761039881836121f2565b5f612097565b6120d7915060203d6020116103a65761039881836121f2565b5f611fb2565b346107cd575f3660031901126107cd5761089a611935612313565b346107cd575f3660031901126107cd57602061042b6124b0565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b600435906001600160a01b03821682036107cd57565b602435906001600160a01b03821682036107cd57565b9181601f840112156107cd578235916001600160401b0383116107cd57602083818601950101116107cd57565b9060406003198301126107cd5760043591602435906001600160401b0382116107cd576121be91600401612162565b9091565b61014081019081106001600160401b038211176121de57604052565b634e487b7160e01b5f52604160045260245ffd5b90601f801991011681019081106001600160401b038211176121de57604052565b6001600160401b0381116121de5760051b60200190565b9080601f830112156107cd5781359061224282612213565b9261225060405194856121f2565b82845260208085019360051b8201019182116107cd57602001915b8183106122785750505090565b82356001600160a01b03811681036107cd5781526020928301920161226b565b604081016040825282518091526020606083019301905f5b8181106122f4575050506020818303910152602080835192838152019201905f5b8181106122de5750505090565b82518452602093840193909201916001016122d1565b82516001600160a01b03168552602094850194909201916001016122b0565b604051905f6006548060011c91600182169182156123eb575b6020841083146123d75783865285929081156123b85750600114612359575b612357925003836121f2565b565b5060065f90815290917ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f5b81831061239c5750509060206123579282010161234b565b6020919350806001915483858901015201910190918492612384565b6020925061235794915060ff191682840152151560051b82010161234b565b634e487b7160e01b5f52602260045260245ffd5b92607f169261232c565b604051905f6007548060011c9160018216918215612497575b6020841083146123d75783865285929081156123b8575060011461243857612357925003836121f2565b5060075f90815290917fa66cc928b5edb82af9bd49922954155ab7b0942694bea4ce44661d9a8736c6885b81831061247b5750509060206123579282010161234b565b6020919350806001915483858901015201910190918492612463565b92607f169261240e565b908160209103126107cd575190565b6040516370a0823160e01b81523060048201525f91907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690602081602481855afa908115612037575f91612572575b5080612512575050565b6020919293506024604051809481936303d1689d60e11b835260048301525afa908115612037575f91612543575090565b90506020813d60201161256a575b8161255e602093836121f2565b810103126107cd575190565b3d9150612551565b90506020813d60201161259c575b8161258d602093836121f2565b810103126107cd57515f612508565b3d9150612580565b908160209103126107cd575180151581036107cd5790565b908160209103126107cd57516001600160a01b03811681036107cd5790565b604051628bec5760e51b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115612037575f9161262a575090565b612643915060203d60201161026a5761025c81836121f2565b90565b6001600160a01b039091168152602081019190915260400190565b9061266b82612213565b61267860405191826121f2565b8281528092612689601f1991612213565b0190602036910137565b80518210156126a75760209160051b010190565b634e487b7160e01b5f52603260045260245ffd5b6040518091829160208251919201905f5b8181106126dc5750505003902090565b82516001600160a01b03168452859450602093840193909201916001016126cc565b6040518091829160208251919201905f5b81811061271f5750505003902090565b825184528594506020938401939092019160010161270f565b60ff60085416612806576040516370a0823160e01b81523060048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690602081602481855afa908115612037575f916127d4575b506127a2575090565b60405163ce96cb7760e01b81523060048201529150602090829060249082905afa908115612037575f91612543575090565b90506020813d6020116127fe575b816127ef602093836121f2565b810103126107cd57515f612799565b3d91506127e2565b5f90565b5f516020612a605f395f51905f525c6128305760015f516020612a605f395f51905f525d565b633ee5aeb560e01b5f5260045ffd5b5015801580612883575b6128745780612868575b61285957565b63332863a960e11b5f5260045ffd5b5060ff60085416612853565b630cd0fdf960e01b5f5260045ffd5b5060ff6008541615612849565b9081526001600160a01b0391821660208201529116604082015260600190565b6128e561235793926128d760405194859263a9059cbb60e01b602085015260248401612646565b03601f1981018452836121f2565b6129a7565b91909160205f60405193612921856129138582019363095ea7b360e01b85528960248401612646565b03601f1981018752866121f2565b84519082855af15f513d82612982575b50501561293d57505050565b60405163095ea7b360e01b60208201526001600160a01b0390931660248401525f6044808501919091528352612357926128e59061297c6064826121f2565b826129a7565b90915061299f57506001600160a01b0381163b15155b5f80612931565b600114612998565b905f602091828151910182855af115612037575f513d6129f657506001600160a01b0381163b155b6129d65750565b635274afe760e01b5f9081526001600160a01b0391909116600452602490fd5b600114156129cf56feb00be3d6a5434b97b328543d1486d56adcb7e74080170d1cdd7e0306c3d9ba3d0d186688925976bbe6755ae984501c8e3e2b103a7af59fd803ab9c6d891ae7e0d5e872c5ecfb1bb8820b2e6a20e31b883682282da886621541f71e31ec11947e9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f003e3e7958121b3e39c7a49392d1aa9cdce870c2a059744f9e15cf66fff7865455a2646970667358221220eb43e901a8e2ac3e06c6d0eb48e69fd16802db5273d8edabfcb4b4044c9b146864736f6c634300081c00330000000000000000000000008a862fd6c12f9ad34c9c2ff45ab2b6712e8cea27000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000140000000000000000000000000000000000000000000000000000000000000018000000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f0000000000000000000000005a4ac204864a36e9820a3663836299ed963f0857000000000000000000000000b88339cb7199b77e23db6e890353e22632ba630f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001f4d6f7270686f5661756c742d757364632d46656c69785f555344432d3939390000000000000000000000000000000000000000000000000000000000000000ef7b2270726f746f636f6c223a224d6f7270686f222c2274797065223a225661756c74222c226173736574223a22307862383833333963623731393962373765323364623665383930333533653232363332626136333066222c226d61726b65744173736574223a22307862383833333963623731393962373765323364623665383930333533653232363332626136333066222c22706f6f6c223a22307838613836326664366331326639616433346339633266663435616232623637313265386365613237222c22636861696e4964223a3939392c227661756c744e616d65223a2246656c69785f55534443227d0000000000000000000000000000000000
Deployed Bytecode
0x60806040526004361015610011575f80fd5b5f5f3560e01c806301e1d114146120f857806306fdde03146120dd5780630af02e5014611f23578063117d8ae014611ef657806313c408f814611cea57806324ea54f414611caf5780632db6d39914611a52578063303dbaf314611a2f5780633194549e14611a1157806337270936146119ea57806338d52e0f146119c15780634fc7fac314611949578063565974d3146119195780635b0f83f3146118a757806361d027b31461183557806361f5cd8b146117dc57806366e943f1146117b457806369b3054b14611750578063780469bb1461129557806379502c55146111e45780637aaceb951461117257806386651203146111195780638a8b997614610fd357806392f5e83214610f67578063a89f38a314610f3f578063ad5a356f14610f21578063b6042b3414610edc578063bdcdd88214610ebe578063c0b534c214610e83578063c38a6f0b14610b95578063c3f909d414610a1b578063c9c667e3146109d6578063ccc574901461099b578063ce5c7f6114610433578063d570ee4714610410578063dbb7cbc5146103cb578063dbd5edc7146103ad578063ebc136d0146102ec578063ebf311311461027f5763f7e533ec146101d2575f80fd5b3461027c578060031936011261027c57604051633df94cfb60e21b81526020816004817f0000000000000000000000005a4ac204864a36e9820a3663836299ed963f08576001600160a01b03165afa9081156102715760209291610244575b506040516001600160a01b039091168152f35b6102649150823d841161026a575b61025c81836121f2565b8101906125bc565b5f610231565b503d610252565b6040513d84823e3d90fd5b80fd5b503461027c578060031936011261027c5780546001600160a01b03811633036102dd576001600160a01b03191681556040513381527f7cb941d7b1708e5b3bcd35ca960d6c6311188cec18886e5b67630552676b048790602090a180f35b63430da47160e01b8252600482fd5b503461027c57602036600319011261027c57610306612136565b604051632474521560e21b81525f516020612a005f395f51905f5260048201526001600160a01b03918216602482015290602090829060449082907f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f165afa9081156102715760209291610380575b506040519015158152f35b6103a09150823d84116103a6575b61039881836121f2565b8101906125a4565b5f610375565b503d61038e565b503461027c578060031936011261027c576020600354604051908152f35b503461027c578060031936011261027c576040517f00000000000000000000000000000000000000000000000000000000000000016001600160a01b03168152602090f35b503461027c578060031936011261027c57602061042b612738565b604051908152f35b503461027c57602036600319011261027c576004356001600160401b03811161095a57610464903690600401612162565b604051628bec5760e51b8152919291602081600481305afa908115610990578391610971575b506001600160a01b0316330361095e576104a261280a565b82019160208184031261095a578035906001600160401b03821161094257019060808284031261027c5760405191608083018381106001600160401b038211176109465760405280356001600160401b038111610942578461050591830161222a565b835260208101356001600160401b038111610942578461052691830161222a565b936020840194855260408201356001600160401b03811161092a5782019181601f8401121561092a5782359261055b84612213565b9361056960405195866121f2565b80855260208086019160051b8301019184831161092657602001905b82821061093257505050604085019283526060810135906001600160401b03821161092e57019080601f8301121561092a578135916105c383612213565b926105d160405194856121f2565b80845260208085019160051b830101918383116109265760208101915b83831061089e5750505050506060840190815261060c855151612661565b90610618865151612661565b7f00000000000000000000000000000000000000000000000000000000000000016001600160a01b031695909390855b8851518110156108305781516001600160a01b0390610668908390612693565b516040516309bf142360e01b8152911660048201526020816024818c5afa9081156107d9578891610812575b50156108035781516001600160a01b03906106b0908390612693565b51169060018060a01b036106c5828c51612693565b5116916106d3828651612693565b516106df838851612693565b51918a604051958693637d5f6a0960e11b8552608485019130600487015260248601526044850152608060648501528451809152602060a4850195019082905b8082106107e45750505082908160209503925af19182156107d95788926107a0575b50895160019261079a916001600160a01b039061075f908590612693565b511661076b848a612693565b5280610777848b612693565b528b61078a84868060a01b039251612693565b51166107946125db565b906128b0565b01610648565b91506020823d82116107d1575b816107ba602093836121f2565b810103126107cd5790519061079a610741565b5f80fd5b3d91506107ad565b6040513d8a823e3d90fd5b825187526020968701968996508f94509092019160019091019061071f565b63a953048960e01b8752600487fd5b61082a915060203d81116103a65761039881836121f2565b5f610694565b868561089a8861083f836126bb565b610848826126fe565b905f516020612a805f395f51905f528680a3610863836126bb565b9261086d826126fe565b946040519586955f516020612a805f395f51905f528380a35f516020612a605f395f51905f525d83612298565b0390f35b82356001600160401b03811161092257820185603f82011215610922576020810135906108ca82612213565b916108d860405193846121f2565b8083526020808085019260051b840101019188831161091e57604001905b82821061090e575050508152602092830192016105ee565b81358152602091820191016108f6565b8b80fd5b8880fd5b8680fd5b8380fd5b8480fd5b8135815260209182019101610585565b8280fd5b634e487b7160e01b83526041600452602483fd5b5080fd5b631184b31b60e21b825233600452602482fd5b61098a915060203d60201161026a5761025c81836121f2565b5f61048a565b6040513d85823e3d90fd5b503461027c578060031936011261027c5760206040517f7935bd0ae54bc31f548c14dba4d37c5c64b3f8ca900cb468fb8abd54d5894f558152f35b503461027c578060031936011261027c576040517f0000000000000000000000005a4ac204864a36e9820a3663836299ed963f08576001600160a01b03168152602090f35b503461027c578060031936011261027c5780610120604051610a3c816121c2565b8281528260208201528260408201528260608201528260808201528260a0820152606060c0820152606060e082015282610100820152015260405190610a81826121c2565b546001600160a01b03908116825260015481166020830190815260025490911660408301908152600354606084019081526004546080850190815260055460a08601908152939493919291610b809190610b6c90610add612313565b9060c08801918252610aed6123f5565b60e089810191825260085460ff1615156101008b019081526009546101208c019081526040805160208082529d516001600160a01b039081169e82019e909e529d518d16908e01529851909a1660608c0152975160808b0152935160a08a01525160c08901525161014095880195909552869594610160870190612112565b9051858203601f1901610100870152612112565b91511515610120840152516101408301520390f35b503461027c57608036600319011261027c57600435610bb261214c565b6044356001600160401b03811161092a57610bd1903690600401612162565b6064939193356001600160401b038111610e7f57610bf3903690600401612162565b86549091906001600160a01b03163303610e6c57869291610c139161283f565b610c1b6124b0565b8303610ded576040516370a0823160e01b81523060048201527f0000000000000000000000008a862fd6c12f9ad34c9c2ff45ab2b6712e8cea276001600160a01b031690602081602481855afa908115610de2578491610da9575b50610c9f8492602092604051948580948193635d043b2960e11b83523090309060048501612890565b03925af1801561099057610d7a575b505b6002546001600160a01b031693610cc88482876128ea565b6001600160a01b031694853b156109425781606484926040519485938492632db6d39960e01b845289600485015260406024850152816044850152848401378181018301859052601f01601f1916810103018183895af1801561027157610d65575b5050610d5f7f9f784fc02a186f1c98b2d9f15fda084da27cdd291a3785d978f91911d880516b91604051918291309583612646565b0390a380f35b81610d6f916121f2565b61092a57835f610d2a565b610d9b9060203d602011610da2575b610d9381836121f2565b8101906124a1565b505f610cae565b503d610d89565b919350506020813d602011610dda575b81610dc6602093836121f2565b810103126107cd5751869290610c9f610c76565b3d9150610db9565b6040513d86823e3d90fd5b604051632d182be560e21b815260208180610e0d30808960048501612890565b0381867f0000000000000000000000008a862fd6c12f9ad34c9c2ff45ab2b6712e8cea276001600160a01b03165af1801561099057610e4d575b50610cb0565b610e659060203d602011610da257610d9381836121f2565b505f610e47565b631564c0e160e11b875233600452602487fd5b8580fd5b503461027c578060031936011261027c5760206040517f025d8bbf3268be680d2605ebf6da15063b9915615bf1087dab336efc1bf970cb8152f35b503461027c578060031936011261027c576020600954604051908152f35b503461027c578060031936011261027c576040517f0000000000000000000000008a862fd6c12f9ad34c9c2ff45ab2b6712e8cea276001600160a01b03168152602090f35b503461027c578060031936011261027c576020600554604051908152f35b503461027c578060031936011261027c5760206040515f516020612a005f395f51905f528152f35b503461027c57602036600319011261027c578054600435906001600160a01b03163303610fc0576020817fb6ac66853c4e59c71e118d25ab494bb847c4e5eb0c8894898c5343e6f61afc1292600555604051908152a180f35b631564c0e160e11b825233600452602482fd5b503461027c578060031936011261027c57604051600160f91b60208281019182523060601b6001600160601b0319166021840152601583526110479290919061101d6035826121f2565b519020604051632474521560e21b8152600481019190915233602482015291829081906044820190565b03817f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f6001600160a01b03165afa9081156102715782916110fa575b50156110e75780546001600160a01b0381166110d8576001600160a01b0319163390811782556040519081527f55489ce0259bd691120d8860861be1c401c7c16a3cd268d21045756af4ecc5ca90602090a180f35b636a79b97d60e11b8252600482fd5b631564c0e160e11b815233600452602490fd5b611113915060203d6020116103a65761039881836121f2565b5f611083565b503461027c57602036600319011261027c578054600435906001600160a01b03163303610fc0576020817f333b26cca69716ad4680ddb07663f5bfb4f06045671f336af9a83690a3ae00f992600355604051908152a180f35b503461027c578060031936011261027c57604051637aaceb9560e01b81526020816004817f0000000000000000000000005a4ac204864a36e9820a3663836299ed963f08576001600160a01b03165afa908115610271576020929161024457506040516001600160a01b039091168152f35b503461027c578060031936011261027c57546001546002546003546004546005546001600160a01b039485169585169492939092169161128291906112749061122b612313565b906112346123f5565b9360ff6008541697600954976040519b8c9b8c5260208c015260408b015260608a0152608089015260a088015261014060c0880152610140870190612112565b9085820360e0870152612112565b9115156101008401526101208301520390f35b503461027c57602036600319011261027c576004356001600160401b03811161095a576112c690369060040161222a565b604051628bec5760e51b8152602081600481305afa908115610990578391611731575b506001600160a01b0316330361095e5761130161280a565b61130b8151612661565b906113168151612661565b600254845460405163c8169aa160e01b81529294926001600160a01b0392831692909160209183916004918391165afa9081156114f5578691611712575b506040516370a0823160e01b8152306004820152602081602481865afa9081156116c25787916116e0575b501515806116cd575b611559575b5050835b82518110156115005760249060206001600160a01b036113b18387612693565b5116604051938480926370a0823160e01b82523060048301525afa9182156114f55786926114c2575b50816113eb575b6001915001611391565b6001600160a01b036113fd8286612693565b511691602461140a6125db565b9360206001600160a01b0361141f868a612693565b5116604051938480926370a0823160e01b82523060048301525afa9182156114b7578992611483575b5090600194611456926128b0565b828060a01b036114668387612693565b51166114728386612693565b5261147d8287612693565b526113e1565b91506020823d82116114af575b8161149d602093836121f2565b810103126107cd579051906001611448565b3d9150611490565b6040513d8b823e3d90fd5b9091506020813d82116114ed575b816114dd602093836121f2565b810103126107cd5751905f6113da565b3d91506114d0565b6040513d88823e3d90fd5b848261089a8661150f836126bb565b92611519826126fe565b946040519586957f46b8771620f6acf56cb03d3e835ea8024c7dcbcf05fcc3f6ade9e19d1a3e212b8380a35f516020612a605f395f51905f525d83612298565b6040516370a0823160e01b8152306004820152602081602481865afa9081156116c257879161168f575b5081611594602092602494866128ea565b6040516370a0823160e01b81523060048201526001600160a01b0391909116939092839182905afa9081156114f557869161165d575b50604051602081018181106001600160401b038211176116495760405286815286929190823b1561092a5761162592849283604051809681958294632db6d39960e01b84526004840152604060248401526044830190612112565b03925af18015610271571561138d578161163e916121f2565b61092a57835f61138d565b634e487b7160e01b88526041600452602488fd5b90506020813d602011611687575b81611678602093836121f2565b810103126107cd57515f6115ca565b3d915061166b565b90506020813d6020116116ba575b816116aa602093836121f2565b810103126107cd57516024611583565b3d915061169d565b6040513d89823e3d90fd5b50306001600160a01b0382161415611388565b90506020813d60201161170a575b816116fb602093836121f2565b810103126107cd57515f61137f565b3d91506116ee565b61172b915060203d60201161026a5761025c81836121f2565b5f611354565b61174a915060203d60201161026a5761025c81836121f2565b5f6112e9565b503461027c57604036600319011261027c57600435600381101561095a5760209161177961214c565b9050604051908382019260f81b835260018060601b03199060601b166021820152601581526117a96035826121f2565b519020604051908152f35b503461027c578060031936011261027c5760206040515f516020612a205f395f51905f528152f35b503461027c57602036600319011261027c578054600435906001600160a01b03163303610fc0576020817ffbe2d5c01ea8ba5596d6c4e6c82c6d4a0a0ee1128689993a4a5ba0169273d69f92600455604051908152a180f35b503461027c578060031936011261027c576040516361d027b360e01b81526020816004817f0000000000000000000000005a4ac204864a36e9820a3663836299ed963f08576001600160a01b03165afa908115610271576020929161024457506040516001600160a01b039091168152f35b503461027c578060031936011261027c57604051635b0f83f360e01b81526020816004817f0000000000000000000000005a4ac204864a36e9820a3663836299ed963f08576001600160a01b03165afa908115610271576020929161024457506040516001600160a01b039091168152f35b503461027c578060031936011261027c5761089a6119356123f5565b604051918291602083526020830190612112565b503461027c57602036600319011261027c578054600435906001600160a01b03163303610fc05768056bc75e2d6310000081116119b2576020817fd3c6d0ab315f2f1352f036cd9f401b49e38e1b90907e195225e8105f9a0b6f0292600955604051908152a180f35b634ef9dfe360e01b8252600482fd5b503461027c578060031936011261027c576002546040516001600160a01b039091168152602090f35b503461027c578060031936011261027c57546040516001600160a01b039091168152602090f35b503461027c578060031936011261027c576020600454604051908152f35b503461027c578060031936011261027c57602060ff600854166040519015158152f35b503461027c57611a613661218f565b90611a6a61280a565b604051631b93849b60e11b8152602081600481305afa908115611c66578591611c90575b506001600160a01b0316338103611bc9575b5090611aab9161283f565b8160018060a01b036002541691611af26040516323b872dd60e01b602082015233602482015230604482015282606482015260648152611aec6084826121f2565b846129a7565b6002546020906001600160a01b037f0000000000000000000000008a862fd6c12f9ad34c9c2ff45ab2b6712e8cea27811691611b329185918491166128ea565b604460405180958193636e553f6560e01b83528660048401523060248401525af1908115610de2577fcbaa1442ac205415c9d69643e7b60ec73d1de35dbc807c21ec288c70ddc4207b92611b9492611baa575b50604051918291339583612646565b0390a2805f516020612a605f395f51905f525d80f35b611bc29060203d602011610da257610d9381836121f2565b505f611b85565b604051628bec5760e51b8152602081600481305afa9081156114f5578691611c71575b506001600160a01b03163314611aa05760206024916040519283809263d206a05960e01b82523360048301525afa908115611c66578591611c47575b5015611c34575f611aa0565b638f7a567d60e01b845233600452602484fd5b611c60915060203d6020116103a65761039881836121f2565b5f611c28565b6040513d87823e3d90fd5b611c8a915060203d60201161026a5761025c81836121f2565b5f611bec565b611ca9915060203d60201161026a5761025c81836121f2565b5f611a8e565b503461027c578060031936011261027c5760206040517f55435dd261a4b9b3364963f7738a7a662ad9c84396d64be3365284bb7f0a50418152f35b503461027c57611cf93661218f565b83549091906001600160a01b03163303611ee35790611d1f91611d1a61280a565b61283f565b6002546001600160a01b0316908290611d366124b0565b8103611e4e576040516370a0823160e01b81523060048201527f0000000000000000000000008a862fd6c12f9ad34c9c2ff45ab2b6712e8cea276001600160a01b031690602081602481855afa908115610de2578491611e16575b50602091611db991604051958680948193635d043b2960e11b83523090309060048501612890565b03925af1908115610de2575f516020612a405f395f51905f5292611b9492611df7575b505b611de98133866128b0565b604051918291339583612646565b611e0f9060203d602011610da257610d9381836121f2565b505f611ddc565b9350506020833d602011611e46575b81611e32602093836121f2565b810103126107cd5791518492906020611d91565b3d9150611e25565b604051632d182be560e21b8152915060208280611e7030808660048501612890565b0381877f0000000000000000000000008a862fd6c12f9ad34c9c2ff45ab2b6712e8cea276001600160a01b03165af1908115610de2575f516020612a405f395f51905f5292611b9492611ec4575b50611dde565b611edc9060203d602011610da257610d9381836121f2565b505f611ebe565b631564c0e160e11b845233600452602484fd5b503461027c578060031936011261027c576020611f116125db565b6040516001600160a01b039091168152f35b50346107cd5760203660031901126107cd57611f3d612136565b604051600160f81b60208281019182523060601b6001600160601b0319166021840152601583527f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f6001600160a01b031692611f9f929061101d6035826121f2565b0381855afa908115612037575f916120be575b50159081612055575b5061204257733ef3d8ba38ebe18db133cec108f4d14ce00dd9ae3b156107cd5760405163bdac7ca360e01b81523060048201526001600160a01b0390911660248201525f8160448183733ef3d8ba38ebe18db133cec108f4d14ce00dd9ae5af1801561203757612029575080f35b61203591505f906121f2565b005b6040513d5f823e3d90fd5b6329068e8160e21b5f523360045260245ffd5b604051632474521560e21b81525f516020612a205f395f51905f5260048201523360248201529150602090829060449082905afa908115612037575f9161209f575b50155f611fbb565b6120b8915060203d6020116103a65761039881836121f2565b5f612097565b6120d7915060203d6020116103a65761039881836121f2565b5f611fb2565b346107cd575f3660031901126107cd5761089a611935612313565b346107cd575f3660031901126107cd57602061042b6124b0565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b600435906001600160a01b03821682036107cd57565b602435906001600160a01b03821682036107cd57565b9181601f840112156107cd578235916001600160401b0383116107cd57602083818601950101116107cd57565b9060406003198301126107cd5760043591602435906001600160401b0382116107cd576121be91600401612162565b9091565b61014081019081106001600160401b038211176121de57604052565b634e487b7160e01b5f52604160045260245ffd5b90601f801991011681019081106001600160401b038211176121de57604052565b6001600160401b0381116121de5760051b60200190565b9080601f830112156107cd5781359061224282612213565b9261225060405194856121f2565b82845260208085019360051b8201019182116107cd57602001915b8183106122785750505090565b82356001600160a01b03811681036107cd5781526020928301920161226b565b604081016040825282518091526020606083019301905f5b8181106122f4575050506020818303910152602080835192838152019201905f5b8181106122de5750505090565b82518452602093840193909201916001016122d1565b82516001600160a01b03168552602094850194909201916001016122b0565b604051905f6006548060011c91600182169182156123eb575b6020841083146123d75783865285929081156123b85750600114612359575b612357925003836121f2565b565b5060065f90815290917ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f5b81831061239c5750509060206123579282010161234b565b6020919350806001915483858901015201910190918492612384565b6020925061235794915060ff191682840152151560051b82010161234b565b634e487b7160e01b5f52602260045260245ffd5b92607f169261232c565b604051905f6007548060011c9160018216918215612497575b6020841083146123d75783865285929081156123b8575060011461243857612357925003836121f2565b5060075f90815290917fa66cc928b5edb82af9bd49922954155ab7b0942694bea4ce44661d9a8736c6885b81831061247b5750509060206123579282010161234b565b6020919350806001915483858901015201910190918492612463565b92607f169261240e565b908160209103126107cd575190565b6040516370a0823160e01b81523060048201525f91907f0000000000000000000000008a862fd6c12f9ad34c9c2ff45ab2b6712e8cea276001600160a01b031690602081602481855afa908115612037575f91612572575b5080612512575050565b6020919293506024604051809481936303d1689d60e11b835260048301525afa908115612037575f91612543575090565b90506020813d60201161256a575b8161255e602093836121f2565b810103126107cd575190565b3d9150612551565b90506020813d60201161259c575b8161258d602093836121f2565b810103126107cd57515f612508565b3d9150612580565b908160209103126107cd575180151581036107cd5790565b908160209103126107cd57516001600160a01b03811681036107cd5790565b604051628bec5760e51b81526020816004817f0000000000000000000000005a4ac204864a36e9820a3663836299ed963f08576001600160a01b03165afa908115612037575f9161262a575090565b612643915060203d60201161026a5761025c81836121f2565b90565b6001600160a01b039091168152602081019190915260400190565b9061266b82612213565b61267860405191826121f2565b8281528092612689601f1991612213565b0190602036910137565b80518210156126a75760209160051b010190565b634e487b7160e01b5f52603260045260245ffd5b6040518091829160208251919201905f5b8181106126dc5750505003902090565b82516001600160a01b03168452859450602093840193909201916001016126cc565b6040518091829160208251919201905f5b81811061271f5750505003902090565b825184528594506020938401939092019160010161270f565b60ff60085416612806576040516370a0823160e01b81523060048201525f907f0000000000000000000000008a862fd6c12f9ad34c9c2ff45ab2b6712e8cea276001600160a01b031690602081602481855afa908115612037575f916127d4575b506127a2575090565b60405163ce96cb7760e01b81523060048201529150602090829060249082905afa908115612037575f91612543575090565b90506020813d6020116127fe575b816127ef602093836121f2565b810103126107cd57515f612799565b3d91506127e2565b5f90565b5f516020612a605f395f51905f525c6128305760015f516020612a605f395f51905f525d565b633ee5aeb560e01b5f5260045ffd5b5015801580612883575b6128745780612868575b61285957565b63332863a960e11b5f5260045ffd5b5060ff60085416612853565b630cd0fdf960e01b5f5260045ffd5b5060ff6008541615612849565b9081526001600160a01b0391821660208201529116604082015260600190565b6128e561235793926128d760405194859263a9059cbb60e01b602085015260248401612646565b03601f1981018452836121f2565b6129a7565b91909160205f60405193612921856129138582019363095ea7b360e01b85528960248401612646565b03601f1981018752866121f2565b84519082855af15f513d82612982575b50501561293d57505050565b60405163095ea7b360e01b60208201526001600160a01b0390931660248401525f6044808501919091528352612357926128e59061297c6064826121f2565b826129a7565b90915061299f57506001600160a01b0381163b15155b5f80612931565b600114612998565b905f602091828151910182855af115612037575f513d6129f657506001600160a01b0381163b155b6129d65750565b635274afe760e01b5f9081526001600160a01b0391909116600452602490fd5b600114156129cf56feb00be3d6a5434b97b328543d1486d56adcb7e74080170d1cdd7e0306c3d9ba3d0d186688925976bbe6755ae984501c8e3e2b103a7af59fd803ab9c6d891ae7e0d5e872c5ecfb1bb8820b2e6a20e31b883682282da886621541f71e31ec11947e9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f003e3e7958121b3e39c7a49392d1aa9cdce870c2a059744f9e15cf66fff7865455a2646970667358221220eb43e901a8e2ac3e06c6d0eb48e69fd16802db5273d8edabfcb4b4044c9b146864736f6c634300081c0033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
0000000000000000000000008a862fd6c12f9ad34c9c2ff45ab2b6712e8cea27000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000140000000000000000000000000000000000000000000000000000000000000018000000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f0000000000000000000000005a4ac204864a36e9820a3663836299ed963f0857000000000000000000000000b88339cb7199b77e23db6e890353e22632ba630f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001f4d6f7270686f5661756c742d757364632d46656c69785f555344432d3939390000000000000000000000000000000000000000000000000000000000000000ef7b2270726f746f636f6c223a224d6f7270686f222c2274797065223a225661756c74222c226173736574223a22307862383833333963623731393962373765323364623665383930333533653232363332626136333066222c226d61726b65744173736574223a22307862383833333963623731393962373765323364623665383930333533653232363332626136333066222c22706f6f6c223a22307838613836326664366331326639616433346339633266663435616232623637313265386365613237222c22636861696e4964223a3939392c227661756c744e616d65223a2246656c69785f55534443227d0000000000000000000000000000000000
-----Decoded View---------------
Arg [0] : _metaMorpho (address): 0x8A862fD6c12f9ad34C9c2ff45AB2b6712e8CEa27
Arg [1] : _urdFactory (address): 0x0000000000000000000000000000000000000001
Arg [2] : _params (tuple):
Arg [1] : name (string): MorphoVault-usdc-Felix_USDC-999
Arg [2] : details (string): {"protocol":"Morpho","type":"Vault","asset":"0xb88339cb7199b77e23db6e890353e22632ba630f","marketAsset":"0xb88339cb7199b77e23db6e890353e22632ba630f","pool":"0x8a862fd6c12f9ad34c9c2ff45ab2b6712e8cea27","chainId":999,"vaultName":"Felix_USDC"}
Arg [3] : accessManager (address): 0x38fB5a7fa70103dCd9e8A969f3975A77E0fE755f
Arg [4] : configurationManager (address): 0x5A4ac204864a36e9820A3663836299ed963F0857
Arg [5] : asset (address): 0xb88339CB7199b77E23DB6E890353E22632Ba630f
Arg [6] : depositCap (uint256): 0
Arg [7] : maxRebalanceOutflow (uint256): 0
Arg [8] : maxRebalanceInflow (uint256): 0
Arg [9] : requiresKeeperData (bool): False
Arg [10] : maxDepositPercentageOfTVL (uint256): 0
-----Encoded View---------------
24 Constructor Arguments found :
Arg [0] : 0000000000000000000000008a862fd6c12f9ad34c9c2ff45ab2b6712e8cea27
Arg [1] : 0000000000000000000000000000000000000000000000000000000000000001
Arg [2] : 0000000000000000000000000000000000000000000000000000000000000060
Arg [3] : 0000000000000000000000000000000000000000000000000000000000000140
Arg [4] : 0000000000000000000000000000000000000000000000000000000000000180
Arg [5] : 00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f
Arg [6] : 0000000000000000000000005a4ac204864a36e9820a3663836299ed963f0857
Arg [7] : 000000000000000000000000b88339cb7199b77e23db6e890353e22632ba630f
Arg [8] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [9] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [10] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [11] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [12] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [13] : 000000000000000000000000000000000000000000000000000000000000001f
Arg [14] : 4d6f7270686f5661756c742d757364632d46656c69785f555344432d39393900
Arg [15] : 00000000000000000000000000000000000000000000000000000000000000ef
Arg [16] : 7b2270726f746f636f6c223a224d6f7270686f222c2274797065223a22566175
Arg [17] : 6c74222c226173736574223a2230786238383333396362373139396237376532
Arg [18] : 3364623665383930333533653232363332626136333066222c226d61726b6574
Arg [19] : 4173736574223a22307862383833333963623731393962373765323364623665
Arg [20] : 383930333533653232363332626136333066222c22706f6f6c223a2230783861
Arg [21] : 3836326664366331326639616433346339633266663435616232623637313265
Arg [22] : 386365613237222c22636861696e4964223a3939392c227661756c744e616d65
Arg [23] : 223a2246656c69785f55534443227d0000000000000000000000000000000000
Loading...
Loading
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in HYPE
Multichain Portfolio | 35 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.