// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple ERC20 + EIP-2612 implementation.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol)
///
/// @dev Note:
/// - The ERC20 standard allows minting and transferring to and from the zero address,
/// minting and transferring zero tokens, as well as self-approvals.
/// For performance, this implementation WILL NOT revert for such actions.
/// Please add any checks with overrides if desired.
/// - The `permit` function uses the ecrecover precompile (0x1).
///
/// If you are overriding:
/// - NEVER violate the ERC20 invariant:
/// the total sum of all balances must be equal to `totalSupply()`.
/// - Check that the overridden function is actually used in the function you want to
/// change the behavior of. Much of the code has been manually inlined for performance.
abstract contract ERC20 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The total supply has overflowed.
error TotalSupplyOverflow();
/// @dev The allowance has overflowed.
error AllowanceOverflow();
/// @dev The allowance has underflowed.
error AllowanceUnderflow();
/// @dev Insufficient balance.
error InsufficientBalance();
/// @dev Insufficient allowance.
error InsufficientAllowance();
/// @dev The permit is invalid.
error InvalidPermit();
/// @dev The permit has expired.
error PermitExpired();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Emitted when `amount` tokens is transferred from `from` to `to`.
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @dev Emitted when `amount` tokens is approved by `owner` to be used by `spender`.
event Approval(address indexed owner, address indexed spender, uint256 amount);
/// @dev `keccak256(bytes("Transfer(address,address,uint256)"))`.
uint256 private constant _TRANSFER_EVENT_SIGNATURE =
0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
/// @dev `keccak256(bytes("Approval(address,address,uint256)"))`.
uint256 private constant _APPROVAL_EVENT_SIGNATURE =
0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The storage slot for the total supply.
uint256 private constant _TOTAL_SUPPLY_SLOT = 0x05345cdf77eb68f44c;
/// @dev The balance slot of `owner` is given by:
/// ```
/// mstore(0x0c, _BALANCE_SLOT_SEED)
/// mstore(0x00, owner)
/// let balanceSlot := keccak256(0x0c, 0x20)
/// ```
uint256 private constant _BALANCE_SLOT_SEED = 0x87a211a2;
/// @dev The allowance slot of (`owner`, `spender`) is given by:
/// ```
/// mstore(0x20, spender)
/// mstore(0x0c, _ALLOWANCE_SLOT_SEED)
/// mstore(0x00, owner)
/// let allowanceSlot := keccak256(0x0c, 0x34)
/// ```
uint256 private constant _ALLOWANCE_SLOT_SEED = 0x7f5e9f20;
/// @dev The nonce slot of `owner` is given by:
/// ```
/// mstore(0x0c, _NONCES_SLOT_SEED)
/// mstore(0x00, owner)
/// let nonceSlot := keccak256(0x0c, 0x20)
/// ```
uint256 private constant _NONCES_SLOT_SEED = 0x38377508;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev `(_NONCES_SLOT_SEED << 16) | 0x1901`.
uint256 private constant _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX = 0x383775081901;
/// @dev `keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")`.
bytes32 private constant _DOMAIN_TYPEHASH =
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @dev `keccak256("1")`.
bytes32 private constant _VERSION_HASH =
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6;
/// @dev `keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")`.
bytes32 private constant _PERMIT_TYPEHASH =
0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 METADATA */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the name of the token.
function name() public view virtual returns (string memory);
/// @dev Returns the symbol of the token.
function symbol() public view virtual returns (string memory);
/// @dev Returns the decimals places of the token.
function decimals() public view virtual returns (uint8) {
return 18;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the amount of tokens in existence.
function totalSupply() public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
result := sload(_TOTAL_SUPPLY_SLOT)
}
}
/// @dev Returns the amount of tokens owned by `owner`.
function balanceOf(address owner) public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x20))
}
}
/// @dev Returns the amount of tokens that `spender` can spend on behalf of `owner`.
function allowance(address owner, address spender)
public
view
virtual
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
mstore(0x20, spender)
mstore(0x0c, _ALLOWANCE_SLOT_SEED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x34))
}
}
/// @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
///
/// Emits a {Approval} event.
function approve(address spender, uint256 amount) public virtual returns (bool) {
/// @solidity memory-safe-assembly
assembly {
// Compute the allowance slot and store the amount.
mstore(0x20, spender)
mstore(0x0c, _ALLOWANCE_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x34), amount)
// Emit the {Approval} event.
mstore(0x00, amount)
log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c)))
}
return true;
}
/// @dev Transfer `amount` tokens from the caller to `to`.
///
/// Requirements:
/// - `from` must at least have `amount`.
///
/// Emits a {Transfer} event.
function transfer(address to, uint256 amount) public virtual returns (bool) {
_beforeTokenTransfer(msg.sender, to, amount);
/// @solidity memory-safe-assembly
assembly {
// Compute the balance slot and load its value.
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, caller())
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, caller(), shr(96, mload(0x0c)))
}
_afterTokenTransfer(msg.sender, to, amount);
return true;
}
/// @dev Transfers `amount` tokens from `from` to `to`.
///
/// Note: Does not update the allowance if it is the maximum uint256 value.
///
/// Requirements:
/// - `from` must at least have `amount`.
/// - The caller must have at least `amount` of allowance to transfer the tokens of `from`.
///
/// Emits a {Transfer} event.
function transferFrom(address from, address to, uint256 amount) public virtual returns (bool) {
_beforeTokenTransfer(from, to, amount);
/// @solidity memory-safe-assembly
assembly {
let from_ := shl(96, from)
// Compute the allowance slot and load its value.
mstore(0x20, caller())
mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED))
let allowanceSlot := keccak256(0x0c, 0x34)
let allowance_ := sload(allowanceSlot)
// If the allowance is not the maximum uint256 value.
if add(allowance_, 1) {
// Revert if the amount to be transferred exceeds the allowance.
if gt(amount, allowance_) {
mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated allowance.
sstore(allowanceSlot, sub(allowance_, amount))
}
// Compute the balance slot and load its value.
mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
}
_afterTokenTransfer(from, to, amount);
return true;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EIP-2612 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev For more performance, override to return the constant value
/// of `keccak256(bytes(name()))` if `name()` will never change.
function _constantNameHash() internal view virtual returns (bytes32 result) {}
/// @dev Returns the current nonce for `owner`.
/// This value is used to compute the signature for EIP-2612 permit.
function nonces(address owner) public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
// Compute the nonce slot and load its value.
mstore(0x0c, _NONCES_SLOT_SEED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x20))
}
}
/// @dev Sets `value` as the allowance of `spender` over the tokens of `owner`,
/// authorized by a signed approval by `owner`.
///
/// Emits a {Approval} event.
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
bytes32 nameHash = _constantNameHash();
// We simply calculate it on-the-fly to allow for cases where the `name` may change.
if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name()));
/// @solidity memory-safe-assembly
assembly {
// Revert if the block timestamp is greater than `deadline`.
if gt(timestamp(), deadline) {
mstore(0x00, 0x1a15a3cc) // `PermitExpired()`.
revert(0x1c, 0x04)
}
let m := mload(0x40) // Grab the free memory pointer.
// Clean the upper 96 bits.
owner := shr(96, shl(96, owner))
spender := shr(96, shl(96, spender))
// Compute the nonce slot and load its value.
mstore(0x0e, _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX)
mstore(0x00, owner)
let nonceSlot := keccak256(0x0c, 0x20)
let nonceValue := sload(nonceSlot)
// Prepare the domain separator.
mstore(m, _DOMAIN_TYPEHASH)
mstore(add(m, 0x20), nameHash)
mstore(add(m, 0x40), _VERSION_HASH)
mstore(add(m, 0x60), chainid())
mstore(add(m, 0x80), address())
mstore(0x2e, keccak256(m, 0xa0))
// Prepare the struct hash.
mstore(m, _PERMIT_TYPEHASH)
mstore(add(m, 0x20), owner)
mstore(add(m, 0x40), spender)
mstore(add(m, 0x60), value)
mstore(add(m, 0x80), nonceValue)
mstore(add(m, 0xa0), deadline)
mstore(0x4e, keccak256(m, 0xc0))
// Prepare the ecrecover calldata.
mstore(0x00, keccak256(0x2c, 0x42))
mstore(0x20, and(0xff, v))
mstore(0x40, r)
mstore(0x60, s)
let t := staticcall(gas(), 1, 0, 0x80, 0x20, 0x20)
// If the ecrecover fails, the returndatasize will be 0x00,
// `owner` will be checked if it equals the hash at 0x00,
// which evaluates to false (i.e. 0), and we will revert.
// If the ecrecover succeeds, the returndatasize will be 0x20,
// `owner` will be compared against the returned address at 0x20.
if iszero(eq(mload(returndatasize()), owner)) {
mstore(0x00, 0xddafbaef) // `InvalidPermit()`.
revert(0x1c, 0x04)
}
// Increment and store the updated nonce.
sstore(nonceSlot, add(nonceValue, t)) // `t` is 1 if ecrecover succeeds.
// Compute the allowance slot and store the value.
// The `owner` is already at slot 0x20.
mstore(0x40, or(shl(160, _ALLOWANCE_SLOT_SEED), spender))
sstore(keccak256(0x2c, 0x34), value)
// Emit the {Approval} event.
log3(add(m, 0x60), 0x20, _APPROVAL_EVENT_SIGNATURE, owner, spender)
mstore(0x40, m) // Restore the free memory pointer.
mstore(0x60, 0) // Restore the zero pointer.
}
}
/// @dev Returns the EIP-712 domain separator for the EIP-2612 permit.
function DOMAIN_SEPARATOR() public view virtual returns (bytes32 result) {
bytes32 nameHash = _constantNameHash();
// We simply calculate it on-the-fly to allow for cases where the `name` may change.
if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name()));
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Grab the free memory pointer.
mstore(m, _DOMAIN_TYPEHASH)
mstore(add(m, 0x20), nameHash)
mstore(add(m, 0x40), _VERSION_HASH)
mstore(add(m, 0x60), chainid())
mstore(add(m, 0x80), address())
result := keccak256(m, 0xa0)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL MINT FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Mints `amount` tokens to `to`, increasing the total supply.
///
/// Emits a {Transfer} event.
function _mint(address to, uint256 amount) internal virtual {
_beforeTokenTransfer(address(0), to, amount);
/// @solidity memory-safe-assembly
assembly {
let totalSupplyBefore := sload(_TOTAL_SUPPLY_SLOT)
let totalSupplyAfter := add(totalSupplyBefore, amount)
// Revert if the total supply overflows.
if lt(totalSupplyAfter, totalSupplyBefore) {
mstore(0x00, 0xe5cfe957) // `TotalSupplyOverflow()`.
revert(0x1c, 0x04)
}
// Store the updated total supply.
sstore(_TOTAL_SUPPLY_SLOT, totalSupplyAfter)
// Compute the balance slot and load its value.
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, 0, shr(96, mload(0x0c)))
}
_afterTokenTransfer(address(0), to, amount);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL BURN FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Burns `amount` tokens from `from`, reducing the total supply.
///
/// Emits a {Transfer} event.
function _burn(address from, uint256 amount) internal virtual {
_beforeTokenTransfer(from, address(0), amount);
/// @solidity memory-safe-assembly
assembly {
// Compute the balance slot and load its value.
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, from)
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Subtract and store the updated total supply.
sstore(_TOTAL_SUPPLY_SLOT, sub(sload(_TOTAL_SUPPLY_SLOT), amount))
// Emit the {Transfer} event.
mstore(0x00, amount)
log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, shl(96, from)), 0)
}
_afterTokenTransfer(from, address(0), amount);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL TRANSFER FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Moves `amount` of tokens from `from` to `to`.
function _transfer(address from, address to, uint256 amount) internal virtual {
_beforeTokenTransfer(from, to, amount);
/// @solidity memory-safe-assembly
assembly {
let from_ := shl(96, from)
// Compute the balance slot and load its value.
mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
}
_afterTokenTransfer(from, to, amount);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL ALLOWANCE FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Updates the allowance of `owner` for `spender` based on spent `amount`.
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
/// @solidity memory-safe-assembly
assembly {
// Compute the allowance slot and load its value.
mstore(0x20, spender)
mstore(0x0c, _ALLOWANCE_SLOT_SEED)
mstore(0x00, owner)
let allowanceSlot := keccak256(0x0c, 0x34)
let allowance_ := sload(allowanceSlot)
// If the allowance is not the maximum uint256 value.
if add(allowance_, 1) {
// Revert if the amount to be transferred exceeds the allowance.
if gt(amount, allowance_) {
mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated allowance.
sstore(allowanceSlot, sub(allowance_, amount))
}
}
}
/// @dev Sets `amount` as the allowance of `spender` over the tokens of `owner`.
///
/// Emits a {Approval} event.
function _approve(address owner, address spender, uint256 amount) internal virtual {
/// @solidity memory-safe-assembly
assembly {
let owner_ := shl(96, owner)
// Compute the allowance slot and store the amount.
mstore(0x20, spender)
mstore(0x0c, or(owner_, _ALLOWANCE_SLOT_SEED))
sstore(keccak256(0x0c, 0x34), amount)
// Emit the {Approval} event.
mstore(0x00, amount)
log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, shr(96, owner_), shr(96, mload(0x2c)))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HOOKS TO OVERRIDE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Hook that is called before any transfer of tokens.
/// This includes minting and burning.
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/// @dev Hook that is called after any transfer of tokens.
/// This includes minting and burning.
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {ERC20} from "./ERC20.sol";
import {FixedPointMathLib} from "../utils/FixedPointMathLib.sol";
import {SafeTransferLib} from "../utils/SafeTransferLib.sol";
/// @notice Simple ERC4626 tokenized Vault implementation.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC4626.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/mixins/ERC4626.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/ERC4626.sol)
abstract contract ERC4626 is ERC20 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The default underlying decimals.
uint8 internal constant _DEFAULT_UNDERLYING_DECIMALS = 18;
/// @dev The default decimals offset.
uint8 internal constant _DEFAULT_DECIMALS_OFFSET = 0;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Cannot deposit more than the max limit.
error DepositMoreThanMax();
/// @dev Cannot mint more than the max limit.
error MintMoreThanMax();
/// @dev Cannot withdraw more than the max limit.
error WithdrawMoreThanMax();
/// @dev Cannot redeem more than the max limit.
error RedeemMoreThanMax();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Emitted during a mint call or deposit call.
event Deposit(address indexed by, address indexed owner, uint256 assets, uint256 shares);
/// @dev Emitted during a withdraw call or redeem call.
event Withdraw(
address indexed by,
address indexed to,
address indexed owner,
uint256 assets,
uint256 shares
);
/// @dev `keccak256(bytes("Deposit(address,address,uint256,uint256)"))`.
uint256 private constant _DEPOSIT_EVENT_SIGNATURE =
0xdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7;
/// @dev `keccak256(bytes("Withdraw(address,address,address,uint256,uint256)"))`.
uint256 private constant _WITHDRAW_EVENT_SIGNATURE =
0xfbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC4626 CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev To be overridden to return the address of the underlying asset.
///
/// - MUST be an ERC20 token contract.
/// - MUST NOT revert.
function asset() public view virtual returns (address);
/// @dev To be overridden to return the number of decimals of the underlying asset.
/// Default: 18.
///
/// - MUST NOT revert.
function _underlyingDecimals() internal view virtual returns (uint8) {
return _DEFAULT_UNDERLYING_DECIMALS;
}
/// @dev Override to return a non-zero value to make the inflation attack even more unfeasible.
/// Only used when {_useVirtualShares} returns true.
/// Default: 0.
///
/// - MUST NOT revert.
function _decimalsOffset() internal view virtual returns (uint8) {
return _DEFAULT_DECIMALS_OFFSET;
}
/// @dev Returns whether virtual shares will be used to mitigate the inflation attack.
/// See: https://github.com/OpenZeppelin/openzeppelin-contracts/issues/3706
/// Override to return true or false.
/// Default: true.
///
/// - MUST NOT revert.
function _useVirtualShares() internal view virtual returns (bool) {
return true;
}
/// @dev Returns the decimals places of the token.
///
/// - MUST NOT revert.
function decimals() public view virtual override(ERC20) returns (uint8) {
if (!_useVirtualShares()) return _underlyingDecimals();
return _underlyingDecimals() + _decimalsOffset();
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ASSET DECIMALS GETTER HELPER */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Helper function to get the decimals of the underlying asset.
/// Useful for setting the return value of `_underlyingDecimals` during initialization.
/// If the retrieval succeeds, `success` will be true, and `result` will hold the result.
/// Otherwise, `success` will be false, and `result` will be zero.
///
/// Example usage:
/// ```
/// (bool success, uint8 result) = _tryGetAssetDecimals(underlying);
/// _decimals = success ? result : _DEFAULT_UNDERLYING_DECIMALS;
/// ```
function _tryGetAssetDecimals(address underlying)
internal
view
returns (bool success, uint8 result)
{
/// @solidity memory-safe-assembly
assembly {
// Store the function selector of `decimals()`.
mstore(0x00, 0x313ce567)
// Arguments are evaluated last to first.
success :=
and(
// Returned value is less than 256, at left-padded to 32 bytes.
and(lt(mload(0x00), 0x100), gt(returndatasize(), 0x1f)),
// The staticcall succeeds.
staticcall(gas(), underlying, 0x1c, 0x04, 0x00, 0x20)
)
result := mul(mload(0x00), success)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ACCOUNTING LOGIC */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the total amount of the underlying asset managed by the Vault.
///
/// - SHOULD include any compounding that occurs from the yield.
/// - MUST be inclusive of any fees that are charged against assets in the Vault.
/// - MUST NOT revert.
function totalAssets() public view virtual returns (uint256 assets) {
assets = SafeTransferLib.balanceOf(asset(), address(this));
}
/// @dev Returns the amount of shares that the Vault will exchange for the amount of
/// assets provided, in an ideal scenario where all 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, during 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, i.e. what the average user should
/// expect to see when exchanging to and from.
function convertToShares(uint256 assets) public view virtual returns (uint256 shares) {
if (!_useVirtualShares()) {
uint256 supply = totalSupply();
return _eitherIsZero(assets, supply)
? _initialConvertToShares(assets)
: FixedPointMathLib.fullMulDiv(assets, supply, totalAssets());
}
uint256 o = _decimalsOffset();
if (o == 0) {
return FixedPointMathLib.fullMulDiv(assets, totalSupply() + 1, _inc(totalAssets()));
}
return FixedPointMathLib.fullMulDiv(assets, totalSupply() + 10 ** o, _inc(totalAssets()));
}
/// @dev Returns the amount of assets that the Vault will exchange for the amount of
/// shares provided, in an ideal scenario where all 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, during 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, i.e. what the average user should
/// expect to see when exchanging to and from.
function convertToAssets(uint256 shares) public view virtual returns (uint256 assets) {
if (!_useVirtualShares()) {
uint256 supply = totalSupply();
return supply == 0
? _initialConvertToAssets(shares)
: FixedPointMathLib.fullMulDiv(shares, totalAssets(), supply);
}
uint256 o = _decimalsOffset();
if (o == 0) {
return FixedPointMathLib.fullMulDiv(shares, totalAssets() + 1, _inc(totalSupply()));
}
return FixedPointMathLib.fullMulDiv(shares, totalAssets() + 1, totalSupply() + 10 ** o);
}
/// @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
/// will be minted in a deposit call in the same transaction, i.e. deposit should
/// return the same or more shares as `previewDeposit` if call in the same transaction.
/// - MUST NOT account for deposit limits like those returned from `maxDeposit` and should
/// always act as if the deposit will be accepted, regardless of approvals, etc.
/// - MUST be inclusive of deposit fees. Integrators should be aware of this.
/// - 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) public view virtual returns (uint256 shares) {
shares = convertToShares(assets);
}
/// @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
/// will 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 if the mint will be accepted, regardless of approvals, etc.
/// - MUST be inclusive of deposit fees. Integrators should be aware of this.
/// - 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) public view virtual returns (uint256 assets) {
if (!_useVirtualShares()) {
uint256 supply = totalSupply();
return supply == 0
? _initialConvertToAssets(shares)
: FixedPointMathLib.fullMulDivUp(shares, totalAssets(), supply);
}
uint256 o = _decimalsOffset();
if (o == 0) {
return FixedPointMathLib.fullMulDivUp(shares, totalAssets() + 1, _inc(totalSupply()));
}
return FixedPointMathLib.fullMulDivUp(shares, totalAssets() + 1, totalSupply() + 10 ** o);
}
/// @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal
/// at the current block, given the current on-chain conditions.
///
/// - MUST return as close to and no fewer than the exact amount of Vault shares that
/// will be burned in a withdraw call in the same transaction, i.e. withdraw should
/// return the same or fewer shares as `previewWithdraw` if call in the same transaction.
/// - MUST NOT account for withdrawal limits like those returned from `maxWithdraw` and should
/// always act as if the withdrawal will be accepted, regardless of share balance, etc.
/// - MUST be inclusive of withdrawal fees. Integrators should be aware of this.
/// - 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) public view virtual returns (uint256 shares) {
if (!_useVirtualShares()) {
uint256 supply = totalSupply();
return _eitherIsZero(assets, supply)
? _initialConvertToShares(assets)
: FixedPointMathLib.fullMulDivUp(assets, supply, totalAssets());
}
uint256 o = _decimalsOffset();
if (o == 0) {
return FixedPointMathLib.fullMulDivUp(assets, totalSupply() + 1, _inc(totalAssets()));
}
return FixedPointMathLib.fullMulDivUp(assets, totalSupply() + 10 ** o, _inc(totalAssets()));
}
/// @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
/// will 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 if the redemption will be accepted, regardless of approvals, etc.
/// - MUST be inclusive of withdrawal fees. Integrators should be aware of this.
/// - 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 depositing.
function previewRedeem(uint256 shares) public view virtual returns (uint256 assets) {
assets = convertToAssets(shares);
}
/// @dev Private helper to return if either value is zero.
function _eitherIsZero(uint256 a, uint256 b) private pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := or(iszero(a), iszero(b))
}
}
/// @dev Private helper to return `x + 1` without the overflow check.
/// Used for computing the denominator input to `FixedPointMathLib.fullMulDiv(a, b, x + 1)`.
/// When `x == type(uint256).max`, we get `x + 1 == 0` (mod 2**256 - 1),
/// and `FixedPointMathLib.fullMulDiv` will revert as the denominator is zero.
function _inc(uint256 x) private pure returns (uint256) {
unchecked {
return x + 1;
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DEPOSIT / WITHDRAWAL LIMIT LOGIC */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the maximum amount of the underlying asset that can be deposited
/// into the Vault for `to`, via a deposit call.
///
/// - MUST return a limited value if `to` is subject to some deposit limit.
/// - MUST return `2**256-1` if there is no maximum limit.
/// - MUST NOT revert.
function maxDeposit(address to) public view virtual returns (uint256 maxAssets) {
to = to; // Silence unused variable warning.
maxAssets = type(uint256).max;
}
/// @dev Returns the maximum amount of the Vault shares that can be minter for `to`,
/// via a mint call.
///
/// - MUST return a limited value if `to` is subject to some mint limit.
/// - MUST return `2**256-1` if there is no maximum limit.
/// - MUST NOT revert.
function maxMint(address to) public view virtual returns (uint256 maxShares) {
to = to; // Silence unused variable warning.
maxShares = type(uint256).max;
}
/// @dev Returns the maximum amount of the underlying asset that can be withdrawn
/// from the `owner`'s balance in the Vault, via 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) public view virtual returns (uint256 maxAssets) {
maxAssets = convertToAssets(balanceOf(owner));
}
/// @dev Returns the maximum amount of Vault shares that can be redeemed
/// from the `owner`'s balance in the Vault, via a redeem call.
///
/// - MUST return a limited value if `owner` is subject to some withdrawal limit or timelock.
/// - MUST return `balanceOf(owner)` otherwise.
/// - MUST NOT revert.
function maxRedeem(address owner) public view virtual returns (uint256 maxShares) {
maxShares = balanceOf(owner);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DEPOSIT / WITHDRAWAL LOGIC */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Mints `shares` Vault shares to `to` by depositing exactly `assets`
/// 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, such as due to deposit limit,
/// slippage, insufficient approval, etc.
///
/// Note: Most implementations will require pre-approval of the Vault with the
/// Vault's underlying `asset` token.
function deposit(uint256 assets, address to) public virtual returns (uint256 shares) {
if (assets > maxDeposit(to)) _revert(0xb3c61a83); // `DepositMoreThanMax()`.
shares = previewDeposit(assets);
_deposit(msg.sender, to, assets, shares);
}
/// @dev Mints exactly `shares` Vault shares to `to` by depositing `assets`
/// 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 deposited, such as due to deposit limit,
/// slippage, insufficient approval, etc.
///
/// Note: Most implementations will require pre-approval of the Vault with the
/// Vault's underlying `asset` token.
function mint(uint256 shares, address to) public virtual returns (uint256 assets) {
if (shares > maxMint(to)) _revert(0x6a695959); // `MintMoreThanMax()`.
assets = previewMint(shares);
_deposit(msg.sender, to, assets, shares);
}
/// @dev Burns `shares` from `owner` and sends exactly `assets` of underlying tokens to `to`.
///
/// - 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, such as due to withdrawal limit,
/// slippage, insufficient balance, etc.
///
/// Note: 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 to, address owner)
public
virtual
returns (uint256 shares)
{
if (assets > maxWithdraw(owner)) _revert(0x936941fc); // `WithdrawMoreThanMax()`.
shares = previewWithdraw(assets);
_withdraw(msg.sender, to, owner, assets, shares);
}
/// @dev Burns exactly `shares` from `owner` and sends `assets` of underlying tokens to `to`.
///
/// - 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, such as due to withdrawal limit,
/// slippage, insufficient balance, etc.
///
/// Note: Some implementations will require pre-requesting to the Vault before a redeem
/// may be performed. Those methods should be performed separately.
function redeem(uint256 shares, address to, address owner)
public
virtual
returns (uint256 assets)
{
if (shares > maxRedeem(owner)) _revert(0x4656425a); // `RedeemMoreThanMax()`.
assets = previewRedeem(shares);
_withdraw(msg.sender, to, owner, assets, shares);
}
/// @dev Internal helper for reverting efficiently.
function _revert(uint256 s) private pure {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, s)
revert(0x1c, 0x04)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev For deposits and mints.
///
/// Emits a {Deposit} event.
function _deposit(address by, address to, uint256 assets, uint256 shares) internal virtual {
SafeTransferLib.safeTransferFrom(asset(), by, address(this), assets);
_mint(to, shares);
/// @solidity memory-safe-assembly
assembly {
// Emit the {Deposit} event.
mstore(0x00, assets)
mstore(0x20, shares)
let m := shr(96, not(0))
log3(0x00, 0x40, _DEPOSIT_EVENT_SIGNATURE, and(m, by), and(m, to))
}
_afterDeposit(assets, shares);
}
/// @dev For withdrawals and redemptions.
///
/// Emits a {Withdraw} event.
function _withdraw(address by, address to, address owner, uint256 assets, uint256 shares)
internal
virtual
{
if (by != owner) _spendAllowance(owner, by, shares);
_beforeWithdraw(assets, shares);
_burn(owner, shares);
SafeTransferLib.safeTransfer(asset(), to, assets);
/// @solidity memory-safe-assembly
assembly {
// Emit the {Withdraw} event.
mstore(0x00, assets)
mstore(0x20, shares)
let m := shr(96, not(0))
log4(0x00, 0x40, _WITHDRAW_EVENT_SIGNATURE, and(m, by), and(m, to), and(m, owner))
}
}
/// @dev Internal conversion function (from assets to shares) to apply when the Vault is empty.
/// Only used when {_useVirtualShares} returns false.
///
/// Note: Make sure to keep this function consistent with {_initialConvertToAssets}
/// when overriding it.
function _initialConvertToShares(uint256 assets)
internal
view
virtual
returns (uint256 shares)
{
shares = assets;
}
/// @dev Internal conversion function (from shares to assets) to apply when the Vault is empty.
/// Only used when {_useVirtualShares} returns false.
///
/// Note: Make sure to keep this function consistent with {_initialConvertToShares}
/// when overriding it.
function _initialConvertToAssets(uint256 shares)
internal
view
virtual
returns (uint256 assets)
{
assets = shares;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HOOKS TO OVERRIDE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Hook that is called before any withdrawal or redemption.
function _beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}
/// @dev Hook that is called after any deposit or mint.
function _afterDeposit(uint256 assets, uint256 shares) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error ExpOverflow();
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error FactorialOverflow();
/// @dev The operation failed, due to an overflow.
error RPowOverflow();
/// @dev The mantissa is too big to fit.
error MantissaOverflow();
/// @dev The operation failed, due to an multiplication overflow.
error MulWadFailed();
/// @dev The operation failed, due to an multiplication overflow.
error SMulWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error DivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error SDivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error MulDivFailed();
/// @dev The division failed, as the denominator is zero.
error DivFailed();
/// @dev The full precision multiply-divide operation failed, either due
/// to the result being larger than 256 bits, or a division by a zero.
error FullMulDivFailed();
/// @dev The output is undefined, as the input is less-than-or-equal to zero.
error LnWadUndefined();
/// @dev The input outside the acceptable domain.
error OutOfDomain();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The scalar of ETH and most ERC20s.
uint256 internal constant WAD = 1e18;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIMPLIFIED FIXED POINT OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if mul(y, gt(x, div(not(0), y))) {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up.
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if mul(y, gt(x, div(not(0), y))) {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.
if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, WAD)
// Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
if iszero(and(iszero(iszero(y)), eq(sdiv(z, WAD), x))) {
mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up.
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.
if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `x` to the power of `y`.
/// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
function powWad(int256 x, int256 y) internal pure returns (int256) {
// Using `ln(x)` means `x` must be greater than 0.
return expWad((lnWad(x) * y) / int256(WAD));
}
/// @dev Returns `exp(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
function expWad(int256 x) internal pure returns (int256 r) {
unchecked {
// When the result is less than 0.5 we return zero.
// This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
if (x <= -41446531673892822313) return r;
/// @solidity memory-safe-assembly
assembly {
// When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
// an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
if iszero(slt(x, 135305999368893231589)) {
mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
revert(0x1c, 0x04)
}
}
// `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
// for more intermediate precision and a binary basis. This base conversion
// is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
x = (x << 78) / 5 ** 18;
// Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
// of two such that exp(x) = exp(x') * 2**k, where k is an integer.
// Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
x = x - k * 54916777467707473351141471128;
// `k` is in the range `[-61, 195]`.
// Evaluate using a (6, 7)-term rational approximation.
// `p` is made monic, we'll multiply by a scale factor later.
int256 y = x + 1346386616545796478920950773328;
y = ((y * x) >> 96) + 57155421227552351082224309758442;
int256 p = y + x - 94201549194550492254356042504812;
p = ((p * y) >> 96) + 28719021644029726153956944680412240;
p = p * x + (4385272521454847904659076985693276 << 96);
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
int256 q = x - 2855989394907223263936484059900;
q = ((q * x) >> 96) + 50020603652535783019961831881945;
q = ((q * x) >> 96) - 533845033583426703283633433725380;
q = ((q * x) >> 96) + 3604857256930695427073651918091429;
q = ((q * x) >> 96) - 14423608567350463180887372962807573;
q = ((q * x) >> 96) + 26449188498355588339934803723976023;
/// @solidity memory-safe-assembly
assembly {
// Div in assembly because solidity adds a zero check despite the unchecked.
// The q polynomial won't have zeros in the domain as all its roots are complex.
// No scaling is necessary because p is already `2**96` too large.
r := sdiv(p, q)
}
// r should be in the range `(0.09, 0.25) * 2**96`.
// We now need to multiply r by:
// - The scale factor `s ≈ 6.031367120`.
// - The `2**k` factor from the range reduction.
// - The `1e18 / 2**96` factor for base conversion.
// We do this all at once, with an intermediate result in `2**213`
// basis, so the final right shift is always by a positive amount.
r = int256(
(uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
);
}
}
/// @dev Returns `ln(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
function lnWad(int256 x) internal pure returns (int256 r) {
/// @solidity memory-safe-assembly
assembly {
// We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
// We do this by multiplying by `2**96 / 10**18`. But since
// `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
// and add `ln(2**96 / 10**18)` at the end.
// Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// We place the check here for more optimal stack operations.
if iszero(sgt(x, 0)) {
mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
revert(0x1c, 0x04)
}
// forgefmt: disable-next-item
r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))
// Reduce range of x to (1, 2) * 2**96
// ln(2^k * x) = k * ln(2) + ln(x)
x := shr(159, shl(r, x))
// Evaluate using a (8, 8)-term rational approximation.
// `p` is made monic, we will multiply by a scale factor later.
// forgefmt: disable-next-item
let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
sar(96, mul(add(43456485725739037958740375743393,
sar(96, mul(add(24828157081833163892658089445524,
sar(96, mul(add(3273285459638523848632254066296,
x), x))), x))), x)), 11111509109440967052023855526967)
p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
// `q` is monic by convention.
let q := add(5573035233440673466300451813936, x)
q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
q := add(909429971244387300277376558375, sar(96, mul(x, q)))
// `p / q` is in the range `(0, 0.125) * 2**96`.
// Finalization, we need to:
// - Multiply by the scale factor `s = 5.549…`.
// - Add `ln(2**96 / 10**18)`.
// - Add `k * ln(2)`.
// - Multiply by `10**18 / 2**96 = 5**18 >> 78`.
// The q polynomial is known not to have zeros in the domain.
// No scaling required because p is already `2**96` too large.
p := sdiv(p, q)
// Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
p := mul(1677202110996718588342820967067443963516166, p)
// Add `ln(2) * k * 5**18 * 2**192`.
// forgefmt: disable-next-item
p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
// Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
// Base conversion: mul `2**18 / 2**192`.
r := sar(174, p)
}
}
/// @dev Returns `W_0(x)`, denominated in `WAD`.
/// See: https://en.wikipedia.org/wiki/Lambert_W_function
/// a.k.a. Product log function. This is an approximation of the principal branch.
function lambertW0Wad(int256 x) internal pure returns (int256 w) {
// forgefmt: disable-next-item
unchecked {
if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
int256 wad = int256(WAD);
int256 p = x;
uint256 c; // Whether we need to avoid catastrophic cancellation.
uint256 i = 4; // Number of iterations.
if (w <= 0x1ffffffffffff) {
if (-0x4000000000000 <= w) {
i = 1; // Inputs near zero only take one step to converge.
} else if (w <= -0x3ffffffffffffff) {
i = 32; // Inputs near `-1/e` take very long to converge.
}
} else if (w >> 63 == 0) {
/// @solidity memory-safe-assembly
assembly {
// Inline log2 for more performance, since the range is small.
let v := shr(49, w)
let l := shl(3, lt(0xff, v))
l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
c := gt(l, 60)
i := add(2, add(gt(l, 53), c))
}
} else {
int256 ll = lnWad(w = lnWad(w));
/// @solidity memory-safe-assembly
assembly {
// `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
i := add(3, iszero(shr(68, x)))
c := iszero(shr(143, x))
}
if (c == 0) {
do { // If `x` is big, use Newton's so that intermediate values won't overflow.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := mul(w, div(e, wad))
w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
}
if (p <= w) break;
p = w;
} while (--i != 0);
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
return w;
}
}
do { // Otherwise, use Halley's for faster convergence.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := add(w, wad)
let s := sub(mul(w, e), mul(x, wad))
w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
}
if (p <= w) break;
p = w;
} while (--i != c);
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
// For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
// R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
if (c != 0) {
int256 t = w | 1;
/// @solidity memory-safe-assembly
assembly {
x := sdiv(mul(x, wad), t)
}
x = (t * (wad + lnWad(x)));
/// @solidity memory-safe-assembly
assembly {
w := sdiv(x, add(wad, t))
}
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* GENERAL NUMBER UTILITIES */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
for {} 1 {} {
// 512-bit multiply `[p1 p0] = x * y`.
// Compute the product mod `2**256` and mod `2**256 - 1`
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that `product = p1 * 2**256 + p0`.
// Least significant 256 bits of the product.
result := mul(x, y) // Temporarily use `result` as `p0` to save gas.
let mm := mulmod(x, y, not(0))
// Most significant 256 bits of the product.
let p1 := sub(mm, add(result, lt(mm, result)))
// Handle non-overflow cases, 256 by 256 division.
if iszero(p1) {
if iszero(d) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
result := div(result, d)
break
}
// Make sure the result is less than `2**256`. Also prevents `d == 0`.
if iszero(gt(d, p1)) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
/*------------------- 512 by 256 division --------------------*/
// Make division exact by subtracting the remainder from `[p1 p0]`.
// Compute remainder using mulmod.
let r := mulmod(x, y, d)
// `t` is the least significant bit of `d`.
// Always greater or equal to 1.
let t := and(d, sub(0, d))
// Divide `d` by `t`, which is a power of two.
d := div(d, t)
// Invert `d mod 2**256`
// Now that `d` is an odd number, it has an inverse
// modulo `2**256` such that `d * inv = 1 mod 2**256`.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, `d * inv = 1 mod 2**4`.
let inv := xor(2, mul(3, d))
// Now use 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.
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
result :=
mul(
// Divide [p1 p0] by the factors of two.
// Shift in bits from `p1` into `p0`. For this we need
// to flip `t` such that it is `2**256 / t`.
or(
mul(sub(p1, gt(r, result)), add(div(sub(0, t), t), 1)),
div(sub(result, r), t)
),
// inverse mod 2**256
mul(inv, sub(2, mul(d, inv)))
)
break
}
}
}
/// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Uniswap-v3-core under MIT license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {
result = fullMulDiv(x, y, d);
/// @solidity memory-safe-assembly
assembly {
if mulmod(x, y, d) {
result := add(result, 1)
if iszero(result) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
}
}
}
/// @dev Returns `floor(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y))
if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := div(mul(x, y), d)
}
}
/// @dev Returns `ceil(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y))
if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(mul(x, y), d))), div(mul(x, y), d))
}
}
/// @dev Returns `ceil(x / d)`.
/// Reverts if `d` is zero.
function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
if iszero(d) {
mstore(0x00, 0x65244e4e) // `DivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(x, d))), div(x, d))
}
}
/// @dev Returns `max(0, x - y)`.
function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
/// Reverts if the computation overflows.
function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
if x {
z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
let half := shr(1, b) // Divide `b` by 2.
// Divide `y` by 2 every iteration.
for { y := shr(1, y) } y { y := shr(1, y) } {
let xx := mul(x, x) // Store x squared.
let xxRound := add(xx, half) // Round to the nearest number.
// Revert if `xx + half` overflowed, or if `x ** 2` overflows.
if or(lt(xxRound, xx), shr(128, x)) {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
x := div(xxRound, b) // Set `x` to scaled `xxRound`.
// If `y` is odd:
if and(y, 1) {
let zx := mul(z, x) // Compute `z * x`.
let zxRound := add(zx, half) // Round to the nearest number.
// If `z * x` overflowed or `zx + half` overflowed:
if or(xor(div(zx, x), z), lt(zxRound, zx)) {
// Revert if `x` is non-zero.
if iszero(iszero(x)) {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
}
z := div(zxRound, b) // Return properly scaled `zxRound`.
}
}
}
}
}
/// @dev Returns the square root of `x`.
function sqrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
z := 181 // The "correct" value is 1, but this saves a multiplication later.
// This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
// start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
// Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
// but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffffff, shr(r, x))))
z := shl(shr(1, r), z)
// Goal was to get `z*z*y` within a small factor of `x`. More iterations could
// get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
// We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
// That's not possible if `x < 256` but we can just verify those cases exhaustively.
// Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
// Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
// Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.
// For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
// is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
// with largest error when `s = 1` and when `s = 256` or `1/256`.
// Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
// Then we can estimate `sqrt(y)` using
// `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.
// There is no overflow risk here since `y < 2**136` after the first branch above.
z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.
// Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// If `x+1` is a perfect square, the Babylonian method cycles between
// `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
// See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
z := sub(z, lt(div(x, z), z))
}
}
/// @dev Returns the cube root of `x`.
/// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
/// https://github.com/pcaversaccio/snekmate/blob/main/src/utils/Math.vy
function cbrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := sub(z, lt(div(x, mul(z, z)), z))
}
}
/// @dev Returns the square root of `x`, denominated in `WAD`.
function sqrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
z = 10 ** 9;
if (x <= type(uint256).max / 10 ** 36 - 1) {
x *= 10 ** 18;
z = 1;
}
z *= sqrt(x);
}
}
/// @dev Returns the cube root of `x`, denominated in `WAD`.
function cbrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
z = 10 ** 12;
if (x <= (type(uint256).max / 10 ** 36) * 10 ** 18 - 1) {
if (x >= type(uint256).max / 10 ** 36) {
x *= 10 ** 18;
z = 10 ** 6;
} else {
x *= 10 ** 36;
z = 1;
}
}
z *= cbrt(x);
}
}
/// @dev Returns the factorial of `x`.
function factorial(uint256 x) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
if iszero(lt(x, 58)) {
mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
revert(0x1c, 0x04)
}
for { result := 1 } x { x := sub(x, 1) } { result := mul(result, x) }
}
}
/// @dev Returns the log2 of `x`.
/// Equivalent to computing the index of the most significant bit (MSB) of `x`.
/// Returns 0 if `x` is zero.
function log2(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000))
}
}
/// @dev Returns the log2 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log2Up(uint256 x) internal pure returns (uint256 r) {
r = log2(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(r, 1), x))
}
}
/// @dev Returns the log10 of `x`.
/// Returns 0 if `x` is zero.
function log10(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
if iszero(lt(x, 100000000000000000000000000000000000000)) {
x := div(x, 100000000000000000000000000000000000000)
r := 38
}
if iszero(lt(x, 100000000000000000000)) {
x := div(x, 100000000000000000000)
r := add(r, 20)
}
if iszero(lt(x, 10000000000)) {
x := div(x, 10000000000)
r := add(r, 10)
}
if iszero(lt(x, 100000)) {
x := div(x, 100000)
r := add(r, 5)
}
r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
}
}
/// @dev Returns the log10 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log10Up(uint256 x) internal pure returns (uint256 r) {
r = log10(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(exp(10, r), x))
}
}
/// @dev Returns the log256 of `x`.
/// Returns 0 if `x` is zero.
function log256(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(shr(3, r), lt(0xff, shr(r, x)))
}
}
/// @dev Returns the log256 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log256Up(uint256 x) internal pure returns (uint256 r) {
r = log256(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(shl(3, r), 1), x))
}
}
/// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
/// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
/// @solidity memory-safe-assembly
assembly {
mantissa := x
if mantissa {
if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
mantissa := div(mantissa, 1000000000000000000000000000000000)
exponent := 33
}
if iszero(mod(mantissa, 10000000000000000000)) {
mantissa := div(mantissa, 10000000000000000000)
exponent := add(exponent, 19)
}
if iszero(mod(mantissa, 1000000000000)) {
mantissa := div(mantissa, 1000000000000)
exponent := add(exponent, 12)
}
if iszero(mod(mantissa, 1000000)) {
mantissa := div(mantissa, 1000000)
exponent := add(exponent, 6)
}
if iszero(mod(mantissa, 10000)) {
mantissa := div(mantissa, 10000)
exponent := add(exponent, 4)
}
if iszero(mod(mantissa, 100)) {
mantissa := div(mantissa, 100)
exponent := add(exponent, 2)
}
if iszero(mod(mantissa, 10)) {
mantissa := div(mantissa, 10)
exponent := add(exponent, 1)
}
}
}
}
/// @dev Convenience function for packing `x` into a smaller number using `sci`.
/// The `mantissa` will be in bits [7..255] (the upper 249 bits).
/// The `exponent` will be in bits [0..6] (the lower 7 bits).
/// Use `SafeCastLib` to safely ensure that the `packed` number is small
/// enough to fit in the desired unsigned integer type:
/// ```
/// uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
/// ```
function packSci(uint256 x) internal pure returns (uint256 packed) {
(x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
/// @solidity memory-safe-assembly
assembly {
if shr(249, x) {
mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
revert(0x1c, 0x04)
}
packed := or(shl(7, x), packed)
}
}
/// @dev Convenience function for unpacking a packed number from `packSci`.
function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
unchecked {
unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
}
}
/// @dev Returns the average of `x` and `y`.
function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = (x & y) + ((x ^ y) >> 1);
}
}
/// @dev Returns the average of `x` and `y`.
function avg(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = (x >> 1) + (y >> 1) + (x & y & 1);
}
}
/// @dev Returns the absolute value of `x`.
function abs(int256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(sar(255, x), add(sar(255, x), x))
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(int256 x, int256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(mul(xor(sub(y, x), sub(x, y)), sgt(x, y)), sub(y, x))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), lt(y, x)))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), slt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), gt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), sgt(y, x)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(uint256 x, uint256 minValue, uint256 maxValue)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
}
}
/// @dev Returns greatest common divisor of `x` and `y`.
function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
for { z := x } y {} {
let t := y
y := mod(z, y)
z := t
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RAW NUMBER OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(x, y)
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mod(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := smod(x, y)
}
}
/// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := addmod(x, y, d)
}
}
/// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mulmod(x, y, d)
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.19;
import { StrategyData } from "../helpers/VaultTypes.sol";
interface IStrategy {
function ADMIN_ROLE() external view returns (uint256);
function EMERGENCY_ADMIN_ROLE() external view returns (uint256);
function VAULT_ROLE() external view returns (uint256);
function KEEPER_ROLE() external view returns (uint256);
/// Roles
function grantRoles(address user, uint256 roles) external payable;
function revokeRoles(address user, uint256 roles) external payable;
function renounceRoles(uint256 roles) external payable;
function harvest(
uint256 minExpectedBalance,
uint256 minOutputAfterInvestment,
address harvester,
uint256 deadline
)
external;
function setEmergencyExit(uint256 _emergencyExit) external;
function setStrategist(address _newStrategist) external;
function vault() external returns (address);
function underlyingAsset() external returns (address);
function emergencyExit() external returns (uint256);
function liquidate(uint256 amountNeeded) external returns (uint256);
function liquidateExact(uint256 amountNeeded) external returns (uint256);
function delegatedAssets() external view returns (uint256);
function estimatedTotalAssets() external view returns (uint256);
function lastEstimatedTotalAssets() external view returns (uint256);
function strategist() external view returns (address);
function strategyName() external view returns (bytes32);
function isActive() external view returns (bool);
/// View roles
function hasAnyRole(address user, uint256 roles) external view returns (bool result);
function hasAllRoles(address user, uint256 roles) external view returns (bool result);
function rolesOf(address user) external view returns (uint256 roles);
function rolesFromOrdinals(uint8[] memory ordinals) external pure returns (uint256 roles);
function ordinalsFromRoles(uint256 roles) external pure returns (uint8[] memory ordinals);
function previewLiquidate(uint256) external view returns (uint256);
function previewLiquidateExact(uint256) external view returns (uint256);
function maxLiquidate() external view returns (uint256);
function maxLiquidateExact() external view returns (uint256);
function maxSingleTrade() external view returns (uint256);
function minSingleTrade() external view returns (uint256);
function yVault() external view returns (address);
function setMaxSingleTrade(uint256) external;
function setMinSingleTrade(uint256) external;
function unharvestedAmount() external view returns (int256);
function simulateHarvest()
external
returns (
uint256 expectedBalance,
uint256 outputAfterInvestment,
uint256 intendedInvest,
uint256 actualInvest,
uint256 intendedDivest,
uint256 actualDivest
);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.19;
import { StrategyData } from "src/helpers/VaultTypes.sol";
import { OwnableRoles } from "solady/auth/OwnableRoles.sol";
import { IStrategy } from "src/interfaces/IStrategy.sol";
import { IERC20Metadata } from "openzeppelin/token/ERC20/extensions/IERC20Metadata.sol";
import { FixedPointMathLib as Math } from "solady/utils/FixedPointMathLib.sol";
import { SafeTransferLib } from "solady/utils/SafeTransferLib.sol";
import { ReentrancyGuard } from "./lib/ReentrancyGuard.sol";
import { ERC4626, ERC20 } from "solady/tokens/ERC4626.sol";
/*KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK
KKKKK0OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO0KKKKKKK
KK0dcclllllllllllllllllllllllllllllccccccccccccccccccclx0KKK
KOc,dKNWWWWWWWWWWWWWWWWWWWWWWWWWWWWNNNNNNNNNNNNNNNNNXOl';xKK
Kd'oWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMX; ,kK
Ko'xMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNc .dK
Ko'dMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNc .oK
Kd'oWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNc .oK
KO:,xXWWWWWWWWWWWWWWWWWWWWMMMMMMMMMMMMMMMMMMMMMMMMMMMMNc .oK
KKOl,',;;,,,,,,;;,,,,,,,;;cxXMMMMMMMMMMMMMMMMMMMMMMMMMNc .oK
KKKKOoc;;;;;;;;;;;;;;;;;;;,.cXMMMMMMMMMMMMMMMMMMMMMMMMNc .oK
KKKKKKKKKKKKKKKKKKKK00O00K0:,0MMMMMMMMMMMMMMMMMMMMMMMMNc .oK
KKKKKKKKKKKKKKKKKKklcccccld;,0MMMMMMMMMMMMMMMMMMMMMMMMNc .oK
KKKKKKKKKKKKKKKKkl;ckXNXOc. '0MMMMMMMMMMMMMMMMMMMMMMMMNc .oK
KKKKKKKKKKKKKKkc;l0WMMMMMX; .oKNMMMMMMMMMMMMMMMMMMMMMMNc .oK
KKKKKKKKKKKKkc;l0WMMMMMMMWd. .,lddddddxONMMMMMMMMMMMMNc .oK
KKKKKKKKKKkc;l0WMMMMMMMMMMWOl::;'. .....:0WMMMMMMMMMMNc .oK
KKKKKKK0xc;o0WMMMMMMMMMMMMMMMMMWNk'.;xkko'lNMMMMMMMMMMNc .oK
KKKKK0x:;oKWMMMMMMMMMMMMMMMMMMMMMWd..lKKk,lNMMMMMMMMMMNc .oK
KKK0x:;oKWMMMMMMMMMMMMMMMMMMMMMMWO, c0Kk,lNMMMMMMMMMMNc .oK
KKx:;dKWMMMMMMMMMMMMMMMMMMMMMWN0c. ;kKKk,lNMMMMMMMMMMNc .oK
Kx,:KWMMMMMMMMMMMMMMMMMMMMMW0c,. 'oOKKKk,lNMMMMMMMMMMNc .oK
Ko'xMMMMMMMMMMMMMMMMMMMMMW0c. 'oOKKKKKk,lNMMMMMMMMMMNc .oK
Ko'xMMMMMMMMMMMMMMMMMMMW0c. ':oOKKKKKKKk,lNMMMMMMMMMMNc .oK
Ko'xMMMMMMMMMMMMMMMMMW0l. 'oOKKKKKKKKKKk,cNMMMMMMMMMMNc .oK
Ko'xMMMMMMMMMMMMMMMW0l. 'oOKKKKKKKKKKKKk,lNMMMMMMMMMMNc .oK
Ko'dWMMMMMMMMMMMMW0l. 'oOKKKKKKKKKKKKKKk,cNMMMMMMMMMMX: .oK
KO:,xXNWWWWWWWWNOl. 'oOKKKKKKKKKKKKKKKK0c,xNMMMMMMMMNd. .dK
KKOl''',,,,,,,,.. 'oOKKKKKKKKKKKKKKKKKKKOl,,ccccccc:' .c0K
KKKKOoc:;;;;;;;;:ldOKKKKKKKKKKKKKKKKKKKKKKKkl;'......',cx0KK
KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK0OOOOOOO0KKK*/
/// @title MaxApy Vault V2 Contract
/// @notice A ERC4626 vault contract deploying `underlyingAsset` to strategies that earn yield and report gains/losses
/// to the vault
/// @author ERC2626 adaptation of MaxAPYVault:
/// https://github.com/UnlockdFinance/maxapy/blob/development/src/MaxApyVault.sol
contract MaxApyVault is ERC4626, OwnableRoles, ReentrancyGuard {
using SafeTransferLib for address;
////////////////////////////////////////////////////////////////
/// CONSTANTS ///
////////////////////////////////////////////////////////////////
uint256 public constant MAXIMUM_STRATEGIES = 20;
uint256 public constant MAX_BPS = 10_000;
/// 365.2425 days
uint256 public constant SECS_PER_YEAR = 31_556_952;
// every week
uint256 public constant AUTOPILOT_HARVEST_INTERVAL = 1 weeks;
/// Roles
uint256 public constant ADMIN_ROLE = _ROLE_0;
uint256 public constant EMERGENCY_ADMIN_ROLE = _ROLE_1;
uint256 public constant STRATEGY_ROLE = _ROLE_2;
////////////////////////////////////////////////////////////////
/// ERRORS ///
////////////////////////////////////////////////////////////////
error QueueIsFull();
error VaultInEmergencyShutdownMode();
error StrategyInEmergencyExitMode();
error InvalidZeroAddress();
error StrategyAlreadyActive();
error StrategyNotActive();
error InvalidStrategyVault();
error InvalidStrategyUnderlying();
error InvalidDebtRatio();
error InvalidMinDebtPerHarvest();
error InvalidPerformanceFee();
error InvalidManagementFee();
error StrategyDebtRatioAlreadyZero();
error InvalidQueueOrder();
error VaultDepositLimitExceeded();
error InvalidZeroAmount();
error InvalidZeroShares();
error LossGreaterThanStrategyTotalDebt();
error InvalidReportedGainAndDebtPayment();
error FeesAlreadyAssesed();
////////////////////////////////////////////////////////////////
/// EVENTS ///
////////////////////////////////////////////////////////////////
/// @notice Emitted when a strategy is newly added to the protocol
event StrategyAdded(
address indexed newStrategy,
uint16 strategyDebtRatio,
uint128 strategyMaxDebtPerHarvest,
uint128 strategyMinDebtPerHarvest,
uint16 strategyPerformanceFee
);
/// @notice Emitted when a strategy is removed from the protocol
event StrategyRemoved(address indexed strategy);
/// @notice Emitted when a vault's emergency shutdown state is switched
event EmergencyShutdownUpdated(bool emergencyShutdown);
/// @notice Emitted when a vault's autopilot mode is enabled or disabled
event AutopilotEnabled(bool isEnabled);
/// @notice Emitted when a strategy is revoked from the vault
event StrategyRevoked(address indexed strategy);
/// @notice Emitted when a strategy parameters are updated
event StrategyUpdated(
address indexed strategy,
uint16 newDebtRatio,
uint128 newMaxDebtPerHarvest,
uint128 newMinDebtPerHarvest,
uint16 newPerformanceFee
);
/// @notice Emitted when a strategy is exited
event StrategyExited(address indexed strategy, uint256 withdrawn);
/// @notice Emitted when the withdrawal queue is updated
event WithdrawalQueueUpdated(address[MAXIMUM_STRATEGIES] withdrawalQueue);
/// @notice Emitted when the vault's performance fee is updated
event PerformanceFeeUpdated(uint16 newPerformanceFee);
/// @notice Emitted when the vault's management fee is updated
event ManagementFeeUpdated(uint256 newManagementFee);
/// @notice Emitted when the vault's deposit limit is updated
event DepositLimitUpdated(uint256 newDepositLimit);
/// @notice Emitted when the vault's treasury addresss is updated
event TreasuryUpdated(address treasury);
/// @notice Emitted on withdrawal strategy withdrawals
event WithdrawFromStrategy(address indexed strategy, uint128 strategyTotalDebt, uint128 loss);
/// @notice Emitted after assessing protocol fees
event FeesReported(uint256 managementFee, uint16 performanceFee, uint256 strategistFee, uint256 duration);
/// @notice Emitted after a forced harvest fails unexpectedly
event ForceHarvestFailed(address indexed strategy, bytes reason);
/// @notice Emitted after a strategy reports to the vault
event StrategyReported(
address indexed strategy,
uint256 unrealizedGain,
uint256 loss,
uint256 debtPayment,
uint128 strategyTotalUnrealizedGain,
uint128 strategyTotalLoss,
uint128 strategyTotalDebt,
uint256 credit,
uint16 strategyDebtRatio
);
// EVENT SIGNATURES
uint256 internal constant _STRATEGY_ADDED_EVENT_SIGNATURE =
0x66277e61c003f7703009ad857a4c4900f9cd3ee44535afe5905f98d53922e0f4;
uint256 internal constant _STRATEGY_REMOVED_EVENT_SIGNATURE =
0x09a1db4b80c32706328728508c941a6b954f31eb5affd32f236c1fd405f8fea4;
uint256 internal constant _EMERGENCY_SHUTDOWN_UPDATED_EVENT_SIGNATURE =
0xa63137c77816d51f856c11ffb11e84757ac9db0ce2569f94edd04c91fe2250a1;
uint256 internal constant _AUTOPILOT_ENABLED_EVENT_SIGNATURE =
0xba59cddbbe4aad399b09d7f484fdd0a4bc54da6a697a48549cbe72d79c66fcb3;
uint256 internal constant _STRATEGY_REVOKED_EVENT_SIGNATURE =
0x4201c688d84c01154d321afa0c72f1bffe9eef53005c9de9d035074e71e9b32a;
uint256 internal constant _STRATEGY_UPDATED_EVENT_SIGNATURE =
0x102a33a8369310733322056f2c0f753209cd77c65b1ce5775c2d6f181e38778f;
uint256 internal constant _WITHDRAWAL_QUEUE_UPDATED_EVENT_SIGNATURE =
0x92fa0b6a2861480bf8c9977f0f9fe1d95c535ba23cbf234f2716fc765aec3be8;
uint256 internal constant _PERFORMANCE_FEE_UPDATED_EVENT_SIGNATURE =
0x0632b4ddf7c06e7e3bc19b7ce92862c7de91b312a392142116fb574a06a47cfd;
uint256 internal constant _MANAGEMENT_FEE_UPDATED_EVENT_SIGNATURE =
0x2147e2bc8c39e67f74b1a9e08896ea1485442096765942206af1f4bc8bcde917;
uint256 internal constant _DEPOSIT_LIMIT_UPDATED_EVENT_SIGNATURE =
0xc512617347fd848ec9d7347c99c10e4fa7059132c92d0445930a7fb0c8252ff5;
uint256 internal constant _TREASURY_UPDATED_EVENT_SIGNATURE =
0x7dae230f18360d76a040c81f050aa14eb9d6dc7901b20fc5d855e2a20fe814d1;
uint256 internal constant _WITHDRAW_FROM_STRATEGY_EVENT_SIGNATURE =
0x8c1171ccd065c6769e1540f65c3c0874e5f7173ccdff7ca293238e69d000bf20;
uint256 internal constant _FEES_REPORTED_EVENT_SIGNATURE =
0x25bf703141a84375d04ea08a0c4a21c7406f300f133e12aef555607b4f3ff238;
uint256 internal constant _STRATEGY_REPORTED_EVENT_SIGNATURE =
0xc2d7e1173e37528dce423c72b129fa1ad2c5d51e50974c64fe13f1928eb27f89;
uint256 private constant _DEPOSIT_EVENT_SIGNATURE =
0xdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7;
uint256 private constant _WITHDRAW_EVENT_SIGNATURE =
0xfbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db;
uint256 private constant _STRATEGY_EXITED_EVENT_SIGNATURE =
0x2e8aac9e73a32a1b5926e2c5a2820a51deb01ed40212b6346d96db2a178cf433;
////////////////////////////////////////////////////////////////
/// VAULT GLOBAL STATE VARIABLES ///
////////////////////////////////////////////////////////////////
/// @notice Vault state stating if vault is in emergency shutdown mode
bool public emergencyShutdown;
/// @notice Vault state stating if vault allows for automated harvesting of strategies
bool public autoPilotEnabled;
/// @notice the decimals of the underlying ERC20 token
uint8 private immutable _decimals;
/// @notice the index in {withdrawalQueue} of the next strategy to be harvested from the autopilot
uint8 public nexHarvestStrategyIndex;
/// @notice Limit for totalAssets the Vault can hold
uint256 public depositLimit;
/// @notice Debt ratio for the Vault across all strategies (in BPS, <= 10k)
uint256 public debtRatio;
/// @notice Amount of tokens that are in the vault
uint256 public totalIdle;
/// @notice Amount of tokens that all strategies have borrowed
uint256 public totalDebt;
/// @notice block.timestamp of last report
uint256 public lastReport;
/// @notice Rewards address where performance and management fees are sent to
address public treasury;
/// @notice Record of all the strategies that are allowed to receive assets from the vault
mapping(address => StrategyData) public strategies;
/// @notice Ordering that `withdraw` uses to determine which strategies to pull funds from
address[MAXIMUM_STRATEGIES] public withdrawalQueue;
/// @notice Fee minted to the treasury and deducted from yield earned every time the vault harvests a strategy
uint256 public performanceFee;
/// @notice Flat rate taken from vault yield over a year
uint256 public managementFee;
/// @notice name of the vault shares ERC20 token
string private _name;
/// @notice symbol of the vault shares ERC20 token
string private _symbol;
/// @notice the assets in which the vault earns interest
address private immutable _underlyingAsset;
////////////////////////////////////////////////////////////////
/// MODIFIERS ///
////////////////////////////////////////////////////////////////
modifier checkRoles(uint256 roles) {
_checkRoles(roles);
_;
}
modifier noEmergencyShutdown() {
if (emergencyShutdown) {
revert VaultInEmergencyShutdownMode();
}
_;
}
constructor(
address admin,
address underlyingAsset_,
string memory name_,
string memory symbol_,
address _treasury
) {
_initializeOwner(admin);
_grantRoles(admin, ADMIN_ROLE);
performanceFee = 1000; // 10% of reported yield (per Strategy)
managementFee = 200; // 2% of reported yield (per Strategy)
lastReport = block.timestamp;
(bool success, uint8 result) = _tryGetAssetDecimals(underlyingAsset_);
_decimals = success ? result : _DEFAULT_UNDERLYING_DECIMALS;
// deposit limit is 10M tokens
depositLimit = 10_000_000 * 10 ** _decimals;
treasury = _treasury;
_underlyingAsset = underlyingAsset_;
_name = name_;
_symbol = symbol_;
}
////////////////////////////////////////////////////////////////
/// INTERNAL FUNCTIONS ///
////////////////////////////////////////////////////////////////
/// @notice Forces the harvest of a
/// @param harvester user that will get extra shares for harvesting
/// @dev it should never revert to ensure users can always deposit
function _forceOneHarvest(address harvester)
internal
returns (address strategy, bool success, bytes memory reason)
{
uint256 l = withdrawalQueue.length;
address[MAXIMUM_STRATEGIES] memory strats = withdrawalQueue;
// find the first strategy that is in autopilot
uint8 i = nexHarvestStrategyIndex > l - 1 ? 0 : nexHarvestStrategyIndex;
bool strategyFound;
for (i; i < l;) {
if (strategies[strats[i]].autoPilot) {
strategy = strats[i];
strategyFound = true;
break;
}
unchecked {
++i;
}
}
// if the strategy we will harvest is the last of the array or its out of bounds
// because of some change in the withdrawal queue
// set it back to the first index(0) of the array
unchecked {
if (i >= l - 1 || strats[i + 1] == address(0)) {
nexHarvestStrategyIndex = 0;
} else {
nexHarvestStrategyIndex = ++i;
}
}
// if there are no strategies to harvest return
if (!strategyFound) return (strategy, true, reason);
// use try/catch so deposits always succeed
// and next index is updated
try IStrategy(strategy).harvest(0, 0, harvester, block.timestamp) {
success = true;
} catch (bytes memory _reason) {
reason = _reason;
success = false;
}
}
/// @notice Reports a strategy loss, adjusting the corresponding vault and strategy parameters
/// to minimize trust in the strategy
/// @param strategy The strategy reporting the loss
/// @param loss The amount of loss to report
function _reportLoss(address strategy, uint256 loss) internal {
// Strategy data
uint128 strategyTotalDebt;
uint16 strategyDebtRatio;
// Vault data
uint256 totalDebt_;
uint256 debtRatio_;
// Slot data
uint256 strategiesSlot;
uint256 slot0Content;
uint256 slot2Content;
assembly ("memory-safe") {
// Get strategies slot
mstore(0x00, strategy)
mstore(0x20, strategies.slot)
strategiesSlot := keccak256(0x00, 0x40)
// Obtain strategy slot 0 data
slot0Content := sload(strategiesSlot)
// Obtain strategy slot 2 data
slot2Content := sload(add(strategiesSlot, 2))
// Cache strategy data
strategyDebtRatio := shr(240, shl(240, slot0Content))
strategyTotalDebt := shr(128, shl(128, slot2Content))
// if loss > strategyData.strategyTotalDebt
if gt(loss, strategyTotalDebt) { loss := strategyTotalDebt }
// Obtain vault debtRatio
debtRatio_ := sload(debtRatio.slot)
// Obtain vault totalDebt
totalDebt_ := sload(totalDebt.slot)
}
uint256 ratioChange;
if (totalDebt_ > 0) {
// Reduce trust in this strategy by the amount of loss, lowering the corresponding strategy debt ratio
ratioChange = Math.min((loss * debtRatio_) / totalDebt_, strategyDebtRatio);
}
assembly {
// Overflow checks
if gt(ratioChange, debtRatio_) {
// throw `Overflow` error
revert(0, 0)
}
if gt(loss, totalDebt_) {
// throw `Overflow` error
revert(0, 0)
}
if gt(ratioChange, strategyDebtRatio) {
// throw `Overflow` error
revert(0, 0)
}
// Update vault data
// debtRatio -= ratioChange;
// totalDebt -= loss;
sstore(debtRatio.slot, sub(debtRatio_, ratioChange)) // debtRatio -= ratioChange
sstore(totalDebt.slot, sub(totalDebt_, loss)) // totalDebt -= loss
// Update strategy debt ratio
// strategies[strategy].strategyDebtRatio -= ratioChange
sstore(
strategiesSlot,
or(
shr(240, shl(240, sub(strategyDebtRatio, ratioChange))), // Compute
// strategies[strategy].strategyDebtRatio - ratioChange
shl(16, shr(16, slot0Content)) // Obtain previous slot data, removing `strategyDebtRatio`
)
)
// Adjust final strategy parameters by the loss
let strategyTotalLoss := shr(128, slot2Content)
// strategyTotalLoss += loss
strategyTotalLoss := add(strategyTotalLoss, loss)
if lt(strategyTotalLoss, loss) {
// throw `Overflow` error
revert(0, 0)
}
// Pack strategyTotalLoss and strategyTotalDebt into slot2Content
slot2Content :=
or(
shl(128, strategyTotalLoss),
shr(128, shl(128, sub(strategyTotalDebt, loss))) // Compute strategies[strategy].strategyTotalDebt
// -=
// loss;
)
// Update strategy total loss and total debt, store in slot 2
sstore(add(strategiesSlot, 2), slot2Content)
}
}
/// @notice Issues new shares to cover performance, management and strategist fees
/// @param strategy The strategy reporting the gain
/// @return the total fees (performance + management + strategist) extracted from the gain
function _assessFees(address strategy, uint256 gain, address managementFeeReceiver) internal returns (uint256) {
bool success;
uint256 slot0Content;
assembly ("memory-safe") {
// Get strategies[strategy] slot
mstore(0x00, strategy)
mstore(0x20, strategies.slot)
// Get strategies[strategy] data
slot0Content := sload(keccak256(0x00, 0x40))
// If strategy was just added or no gains were reported, return 0 as fees
// if (strategyData.strategyActivation == block.timestamp || gain == 0)
if or(eq(shr(208, shl(176, slot0Content)), timestamp()), eq(gain, 0)) { success := 1 }
}
if (success) {
return 0;
}
// Stack variables to cache
uint256 duration;
uint256 strategyPerformanceFee;
uint256 computedManagementFee;
uint256 computedStrategistFee;
uint256 computedPerformanceFee;
uint256 totalFee;
assembly ("memory-safe") {
// duration = block.timestamp - strategyData.strategyLastReport;
duration := sub(timestamp(), shr(208, shl(128, slot0Content)))
// if duration == 0
if iszero(duration) {
// throw the `FeesAlreadyAssesed` error
mstore(0x00, 0x17de0c6e)
revert(0x1c, 0x04)
}
// Cache strategy performance fee
strategyPerformanceFee := shr(240, shl(224, slot0Content))
// Load vault fees
let managementFee_ := sload(managementFee.slot)
let performanceFee_ := sload(performanceFee.slot)
// Overflow check equivalent to require(managementFee_ == 0 || gain <= type(uint256).max / managementFee_)
if iszero(iszero(mul(managementFee_, gt(gain, div(not(0), managementFee_))))) { revert(0, 0) }
// Compute vault management fee
// computedManagementFee = (gain * managementFee) / MAX_BPS
computedManagementFee := div(mul(gain, managementFee_), MAX_BPS)
// Overflow check equivalent to require(strategyPerformanceFee == 0 || gain <= type(uint256).max /
// strategyPerformanceFee)
if iszero(iszero(mul(strategyPerformanceFee, gt(gain, div(not(0), strategyPerformanceFee))))) {
revert(0, 0)
}
// Compute strategist fee
// computedStrategistFee = (gain * strategyData.strategyPerformanceFee) / MAX_BPS;
computedStrategistFee := div(mul(gain, strategyPerformanceFee), MAX_BPS)
// Overflow check equivalent to require(performanceFee_ == 0 || gain <= type(uint256).max / performanceFee_)
if iszero(iszero(mul(performanceFee_, gt(gain, div(not(0), performanceFee_))))) { revert(0, 0) }
// Compute vault performance fee
// computedPerformanceFee = (gain * performanceFee) / MAX_BPS;
computedPerformanceFee := div(mul(gain, performanceFee_), MAX_BPS)
// totalFee = computedManagementFee + computedStrategistFee + computedPerformanceFee
totalFee := add(add(computedManagementFee, computedStrategistFee), computedPerformanceFee)
// Ensure total fee is not greater than the gain, set total fee to become the actual gain otherwise
// if totalFee > gain
if gt(totalFee, gain) {
// totalFee = gain
totalFee := gain
}
}
// Only transfer shares if there are actual shares to transfer
if (totalFee != 0) {
// Compute corresponding shares and mint rewards to vault
uint256 reward = _issueSharesForAmount(address(this), totalFee);
// Transfer corresponding rewards in shares to strategist
if (computedStrategistFee != 0) {
uint256 strategistReward;
assembly {
// Overflow check equivalent to require(reward == 0 || computedStrategistFee <= type(uint256).max /
// reward)
// No need to check for totalFee == 0 since it is checked in the if clause above
if iszero(iszero(mul(reward, gt(computedStrategistFee, div(not(0), reward))))) { revert(0, 0) }
// Compute strategist reward
// strategistReward = (computedStrategistFee * reward) / totalFee;
strategistReward := div(mul(computedStrategistFee, reward), totalFee)
}
// Transfer corresponding reward to strategist
address(this).safeTransfer(IStrategy(strategy).strategist(), strategistReward);
}
// Treasury earns remaining shares (performance fee + management fee + any dust leftover from flooring math
// above)
uint256 cachedBalance = balanceOf(address(this));
if (cachedBalance != 0) {
// if the harvest was triggered by a regular user send management fee to
// the user that endured the harvest
if (managementFeeReceiver != address(0)) {
address(this).safeTransfer(managementFeeReceiver, cachedBalance * computedManagementFee / totalFee);
cachedBalance = balanceOf(address(this));
}
// transfer the rest of it to the treasury
if (cachedBalance != 0) {
address(this).safeTransfer(treasury, cachedBalance);
}
}
}
assembly ("memory-safe") {
// Emit the `FeesReported` event
let m := mload(0x40)
mstore(0x00, computedManagementFee)
mstore(0x20, computedPerformanceFee)
mstore(0x40, computedStrategistFee)
mstore(0x60, duration)
log1(0x00, 0x80, _FEES_REPORTED_EVENT_SIGNATURE)
mstore(0x40, m)
mstore(0x60, 0)
}
return totalFee;
}
/// @notice Amount of tokens in Vault a Strategy has access to as a credit line.
/// This will check the Strategy's debt limit, as well as the tokens available in the
/// Vault, and determine the maximum amount of tokens (if any) the Strategy may draw on
/// @param strategy The strategy to check
/// @return The quantity of tokens available for the Strategy to draw on
function _creditAvailable(address strategy) internal view returns (uint256) {
if (emergencyShutdown) return 0;
// Compute necessary data regarding current state of the vault
uint256 vaultTotalAssets = _totalDeposits();
uint256 vaultDebtLimit = _computeDebtLimit(debtRatio, vaultTotalAssets);
uint256 vaultTotalDebt = totalDebt;
// Stack variables to cache
bool success;
uint256 slot;
uint256 slot0Content;
uint256 strategyTotalDebt;
uint256 strategyDebtLimit;
assembly ("memory-safe") {
// Compute slot of strategies[strategy]
mstore(0x00, strategy)
mstore(0x20, strategies.slot)
slot := keccak256(0x00, 0x40)
// Load strategies[strategy].strategyTotalDebt
strategyTotalDebt := shr(128, shl(128, sload(add(slot, 2))))
// Load slot 0 content
slot0Content := sload(slot)
// Extract strategies[strategy].strategyDebtRatio
let strategyDebtRatio := shr(240, shl(240, slot0Content))
// Overflow check equivalent to require(vaultTotalAssets == 0 || strategyDebtRatio <= type(uint256).max /
// vaultTotalAssets)
if iszero(iszero(mul(vaultTotalAssets, gt(strategyDebtRatio, div(not(0), vaultTotalAssets))))) {
revert(0, 0)
}
// Compute necessary data regarding current state of the strategy
// strategyDebtLimit = (strategies[strategy].strategyDebtRatio * vaultTotalAssets) / MAX_BPS;
strategyDebtLimit := div(mul(strategyDebtRatio, vaultTotalAssets), MAX_BPS)
// If strategy current debt is already greater than the configured debt limit for that strategy,
// or if the vault's current debt is already greater than the configured debt limit for that vault,
// no credit should be given to the strategy
// if strategies[strategy].strategyTotalDebt > strategyDebtLimit || vaultTotalDebt > vaultDebtLimit
if or(gt(strategyTotalDebt, strategyDebtLimit), gt(vaultTotalDebt, vaultDebtLimit)) { success := 1 }
}
if (success) return 0;
// Adjust by the vault debt limit left
uint256 available;
unchecked {
available = Math.min(strategyDebtLimit - strategyTotalDebt, vaultDebtLimit - vaultTotalDebt);
}
// Adjust by the idle amount of underlying the vault has
available = Math.min(available, totalIdle);
assembly {
// Adjust by min and max borrow limits per harvest
// if (available < strategies[strategy].strategyMinDebtPerHarvest) return 0;
if lt(available, shr(128, shl(128, sload(add(slot, 1))))) { success := 1 }
}
if (success) return 0;
// Obtain strategies[strategy].strategyMaxDebtPerHarvest from the previously loaded slot0Content, this saves one
// SLOAD
uint256 strategyMaxDebtPerHarvest;
assembly {
strategyMaxDebtPerHarvest := shr(128, slot0Content)
}
return Math.min(available, strategyMaxDebtPerHarvest);
}
/// @notice Performs the debt limit calculation
/// @param _debtRatio The debt ratio to use for computation
/// @param totalAssets_ The amount of assets
/// @return debtLimit The limit amount of assets allowed for the strategy, given the current debt ratio and total
/// assets
function _computeDebtLimit(uint256 _debtRatio, uint256 totalAssets_) internal pure returns (uint256 debtLimit) {
assembly {
// Overflow check equivalent to require(totalAssets_ == 0 || _debtRatio <= type(uint256).max / totalAssets_)
if iszero(iszero(mul(totalAssets_, gt(_debtRatio, div(not(0), totalAssets_))))) { revert(0, 0) }
// _debtRatio * totalAssets_ / MAX_BPS
debtLimit := div(mul(_debtRatio, totalAssets_), MAX_BPS)
}
}
/// @notice Determines if `strategy` is past its debt limit and if any tokens should be withdrawn to the Vault
/// @param strategy The Strategy to check
/// @return _debtOutstanding_ The quantity of tokens to withdraw
function _debtOutstanding(address strategy) internal view returns (uint256 _debtOutstanding_) {
uint256 strategyTotalDebt;
uint256 strategyDebtRatio;
assembly ("memory-safe") {
// Get strategies[strategy] slot
mstore(0x00, strategy)
mstore(0x20, strategies.slot)
let slot := keccak256(0x00, 0x40)
// Obtain strategies[strategy].strategyTotalDebt from slot 2
strategyTotalDebt := shr(128, shl(128, sload(add(slot, 2))))
// Obtain strategies[strategy].strategyDebtRatio from slot 0
strategyDebtRatio := shr(240, shl(240, sload(slot)))
}
// If debt ratio configured in vault is zero or emergency shutdown, any amount of debt in the strategy should be
// returned
if (debtRatio == 0 || emergencyShutdown) return strategyTotalDebt;
uint256 strategyDebtLimit = _computeDebtLimit(strategyDebtRatio, _totalDeposits());
// There will not be debt outstanding if strategy total debt is smaller or equal to the current debt limit
if (strategyDebtLimit >= strategyTotalDebt) {
return 0;
}
unchecked {
_debtOutstanding_ = strategyTotalDebt - strategyDebtLimit;
}
}
/// @notice Reorganize `withdrawalQueue` based on premise that if there is an
/// empty value between two actual values, then the empty value should be
/// replaced by the later value.
/// @dev Relative ordering of non-zero values is maintained.
function _organizeWithdrawalQueue() internal {
uint256 offset;
for (uint256 i; i < MAXIMUM_STRATEGIES;) {
address strategy = withdrawalQueue[i];
if (strategy == address(0)) {
unchecked {
++offset;
}
} else if (offset > 0) {
withdrawalQueue[i - offset] = strategy;
withdrawalQueue[i] = address(0);
}
unchecked {
++i;
}
}
}
/// @notice Revoke a Strategy, setting its debt limit to 0 and preventing any future deposits
/// @param strategy The strategy to revoke
/// @param strategyDebtRatio The strategy debt ratio
function _revokeStrategy(address strategy, uint256 strategyDebtRatio) internal {
debtRatio -= strategyDebtRatio;
strategies[strategy].strategyDebtRatio = 0;
assembly {
log2(0x00, 0x00, _STRATEGY_REVOKED_EVENT_SIGNATURE, strategy)
}
}
/// @notice Issues `amount` Vault shares to `to`
/// @dev Shares must be issued prior to taking on new collateral, or calculation will be wrong
/// This means that only *trusted* tokens (with no capability for exploitative behavior) can be used
/// @param to The shares recipient
/// @param amount The amount considered to compute the shares
/// @return shares The amount of shares computed from the amount
function _issueSharesForAmount(address to, uint256 amount) internal returns (uint256 shares) {
shares = convertToShares(amount);
assembly ("memory-safe") {
// if shares == 0
if iszero(shares) {
// Throw the `InvalidZeroShares` error
mstore(0x00, 0x5a870a25)
revert(0x1c, 0x04)
}
}
_mint(to, shares);
}
/// @dev Private helper to return if either value is zero.
function _eitherIsZero_(uint256 a, uint256 b) internal pure virtual returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := or(iszero(a), iszero(b))
}
}
/// @dev Private helper to return the value plus one.
function _inc_(uint256 x) internal pure virtual returns (uint256) {
unchecked {
return x + 1;
}
}
/// @dev Private helper to substract a - b or return 0 if it underflows
function _sub0(uint256 a, uint256 b) internal pure virtual returns (uint256) {
unchecked {
return a - b > a ? 0 : a - b;
}
}
////////////////////////////////////////////////////////////////
/// INTERNAL VIEW FUNCTIONS ///
////////////////////////////////////////////////////////////////
/// @notice the number of decimals of the underlying token
function _underlyingDecimals() internal view override returns (uint8) {
return _decimals;
}
/// @dev Override to return a non-zero value to make the inflation attack even more unfeasible.
function _decimalsOffset() internal pure override returns (uint8) {
return 6;
}
/// @notice Returns the estimate amount of assets held by the vault and strategy positions,
/// including unrealised profit or losses
/// @return totalAssets_ The total assets under control of this Vault
function _totalAssets() internal view returns (uint256 totalAssets_) {
// use accounted assets for the vault balance, prevents inflation attacks or similar
totalAssets_ = totalIdle;
address[MAXIMUM_STRATEGIES] memory _withdrawalQueue = withdrawalQueue;
for (uint256 i; i < MAXIMUM_STRATEGIES;) {
address strategy = _withdrawalQueue[i];
// Check if we have exhausted the queue
if (strategy == address(0)) break;
totalAssets_ += IStrategy(strategy).estimatedTotalAssets();
unchecked {
++i;
}
}
}
/// @notice Returns the total quantity of all assets under control of this Vault,
/// whether they're loaned out to a Strategy, or currently held in the Vault
/// @return totalAssets_ The total assets under control of this Vault
function _totalDeposits() internal view returns (uint256 totalAssets_) {
assembly {
let totalDebt_ := sload(totalDebt.slot)
totalAssets_ := add(sload(totalIdle.slot), totalDebt_)
// Perform overflow check
if lt(totalAssets_, totalDebt_) { revert(0, 0) }
}
}
////////////////////////////////////////////////////////////////
/// EXTERNAL VIEW FUNCTIONS ///
////////////////////////////////////////////////////////////////
/// @notice Returns the name of the vault shares token.
function name() public view override returns (string memory) {
return _name;
}
/// @notice Returns the symbol of the token.
function symbol() public view override returns (string memory) {
return _symbol;
}
/// @notice Returns the address of the underlying asset.
function asset() public view override returns (address) {
return _underlyingAsset;
}
/// @notice Returns the total amount of the underlying asset managed by the Vault.
function totalAssets() public view override returns (uint256) {
return _totalAssets();
}
/// @notice Returns the total amount of accounted idle and strategy debt assets
function totalDeposits() public view returns (uint256) {
return _totalDeposits();
}
/// @notice Returns the maximum amount of the underlying asset that can be deposited
/// into the Vault for `to`, via a deposit call.
function maxDeposit(address /*to*/ ) public view override returns (uint256 maxAssets) {
/// @dev use sub0 to prevent underflow
return _sub0(depositLimit, totalAssets());
}
/// @notice Returns the maximum amount of the Vault shares that can be minter for `to`,
/// via a mint call.
function maxMint(address /*to*/ ) public view override returns (uint256 maxShares) {
return convertToShares(maxDeposit(address(0)));
}
/// @notice Returns the maximum amount of the underlying asset that can be withdrawn
/// from the `owner`'s balance in the Vault, via a withdraw call.
function maxWithdraw(address owner) public view override returns (uint256 maxAssets) {
return previewRedeem(maxRedeem(owner) * 99 / 100);
}
/// @notice Returns the estimate price of 1 vault share
function sharePrice() external view returns (uint256) {
return convertToAssets(10 ** decimals());
}
/// @notice Returns the amount of shares that the Vault will exchange for the amount of
/// assets provided, in an ideal scenario where all conditions are met.
/// @dev some the virtual shares and decimal offset checks have been removed for further
/// gas optimization
function convertToShares(uint256 assets) public view override returns (uint256 shares) {
uint256 o = _decimalsOffset();
return Math.fullMulDiv(assets, totalSupply() + 10 ** o, _inc_(_totalAssets()));
}
/// @dev Returns the amount of assets that the Vault will exchange for the amount of
/// shares provided, in an ideal scenario where all conditions are met.
/// @dev some the virtual shares and decimal offset checks have been removed for further
/// gas optimization
function convertToAssets(uint256 shares) public view override returns (uint256 assets) {
uint256 o = _decimalsOffset();
return Math.fullMulDiv(shares, _totalAssets() + 1, totalSupply() + 10 ** o);
}
/// @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.
function previewMint(uint256 shares) public view override returns (uint256 assets) {
uint256 o = _decimalsOffset();
return Math.fullMulDivUp(shares, _totalAssets() + 1, totalSupply() + 10 ** o);
}
/// @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal
/// at the current block, given the current on-chain conditions.
function previewWithdraw(uint256 assets) public view override returns (uint256 shares) {
if (assets == 0) return 0;
if (assets == type(uint256).max) assets = convertToAssets(balanceOf(msg.sender));
uint256 _totalAssets_ = _totalAssets();
uint256 vaultBalance = totalIdle;
uint256 o = _decimalsOffset();
// convert the assets to shares without any losses
// very important: ROUND UP
shares = Math.fullMulDivUp(assets, totalSupply() + 10 ** o, _inc_(_totalAssets_));
// in case the vault's balance doesn't cover the requested `assets`
if (assets > vaultBalance) {
// Vault balance is not enough to cover withdrawal. We need to perform forced withdrawals
// from strategies until requested value amount is covered.
// During forced withdrawal, the vault will do exact amount requests to the strategies
// and account the losses needed to achieve those amounts. Those
// losses are reported back to the vault This will affect the withdrawer, affecting the amount of shares
// that will
// burn in order to withdraw exactly @param assets assets
uint256 totalLoss;
// Iterate over strategies
for (uint256 i; i < MAXIMUM_STRATEGIES;) {
address strategy = withdrawalQueue[i];
// Check if we have exhausted the queue
if (strategy == address(0)) break;
// Check if the vault balance is finally enough to cover the requested withdrawal
if (vaultBalance >= assets) break;
// Compute remaining amount to request considering the current balance of the vault
uint256 amountRequested = assets - vaultBalance;
// Can't request more than allowed by the strategy
amountRequested = Math.min(amountRequested, IStrategy(strategy).maxLiquidateExact());
// Try the next strategy if the current strategy has no debt to be withdrawn
if (amountRequested == 0) {
unchecked {
++i;
}
continue;
}
// Withdraw from strategy. Compute amount withdrawn(should be requestedAmount)
// considering the difference between balances pre/post withdrawal
uint256 withdrawn = IStrategy(strategy).previewLiquidateExact(amountRequested);
uint256 loss = withdrawn - amountRequested;
// increase the vault balance by requested amount
vaultBalance += amountRequested;
// If loss has been realised, withdrawer will incur it, affecting to the amount
// of shares that the user will burn
if (loss != 0) {
totalLoss += loss;
}
unchecked {
++i;
}
}
// Increase the shares if there are any losses
shares += Math.fullMulDivUp(totalLoss, totalSupply() + 10 ** o, _inc_(_totalAssets_));
}
// if there are more assets to cover(when requesting more assets then total)
// we add the extra shares needed, even though it would revert if someone tries
// to withdraw that much since they wouln't have the needed shares
if (vaultBalance < assets) {
shares += Math.fullMulDivUp(assets - vaultBalance, totalSupply() + 10 ** o, _inc_(_totalAssets_));
}
}
/// @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.
function previewRedeem(uint256 shares) public view override returns (uint256 assets) {
if (shares == 0) return 0;
if (shares == type(uint256).max) shares = balanceOf(msg.sender);
assets = convertToAssets(shares);
uint256 vaultBalance = totalIdle;
if (vaultBalance >= assets) {
return assets;
} else {
// Iterate over strategies
for (uint256 i; i < MAXIMUM_STRATEGIES;) {
address strategy = withdrawalQueue[i];
// Check if we have exhausted the queue
if (strategy == address(0)) break;
// Check if the vault balance is finally enough to cover the requested withdrawal
if (vaultBalance >= assets) break;
// Compute remaining amount to withdraw considering the current balance of the vault
uint256 amountRequested;
assembly ("memory-safe") {
// amountRequested = assets - vaultBalance;
amountRequested := sub(assets, vaultBalance)
}
// ask for the min between the needed amount and max withdraw of the strategy
amountRequested = Math.min(amountRequested, IStrategy(strategy).maxLiquidate());
// Try the next strategy if the current strategy has no debt to be withdrawn
if (amountRequested == 0) {
unchecked {
++i;
}
continue;
}
// Withdraw from strategy. Compute amount withdrawn
// considering the difference between balances pre/post withdrawal
uint256 withdrawn = IStrategy(strategy).previewLiquidate(amountRequested);
uint256 loss = amountRequested - withdrawn;
// Increase cached vault balance to track the newly withdrawn amount
vaultBalance += withdrawn;
if (loss != 0) {
assets -= loss;
}
unchecked {
++i;
}
}
}
}
////////////////////////////////////////////////////////////////
/// DEPOSIT/WITHDRAWAL LOGIC ///
////////////////////////////////////////////////////////////////
/// @notice Mints `shares` Vault shares to `to` by depositing exactly `assets`
/// of underlying tokens.
/// @dev overriden to add the `noEmergencyShutdown` & `nonReentrant` modifiers
/// @dev reverts with custom `VaultDepositLimitExceeded` error instead of Solady's `DepositMoreThanMax`
function deposit(
uint256 assets,
address receiver
)
public
virtual
override
noEmergencyShutdown
nonReentrant
returns (uint256 shares)
{
uint256 _maxDeposit = maxDeposit(msg.sender);
assembly ("memory-safe") {
if gt(assets, _maxDeposit) {
// throw the `VaultDepositLimitExceeded` error
mstore(0x00, 0x0c11966b)
revert(0x1c, 0x04)
}
}
_deposit(msg.sender, receiver, assets, shares = previewDeposit(assets));
}
/// @notice Mints exactly `shares` Vault shares to `to` by depositing `assets`
/// of underlying tokens.
/// @dev overriden to add the `noEmergencyShutdown` & `nonReentrant` modifiers
/// @dev reverts with custom `VaultDepositLimitExceeded` error instead of Solady's `MinttMoreThanMax`
function mint(
uint256 shares,
address receiver
)
public
virtual
override
noEmergencyShutdown
nonReentrant
returns (uint256 assets)
{
uint256 _maxMint = maxMint(msg.sender);
assembly ("memory-safe") {
if gt(shares, _maxMint) {
// throw the `VaultDepositLimitExceeded` error
mstore(0x00, 0x0c11966b)
revert(0x1c, 0x04)
}
}
_deposit(msg.sender, receiver, assets = previewMint(shares), shares);
}
/// @dev override the Solady's internal function to add extra checks
function _deposit(address by, address to, uint256 assets, uint256 shares) internal override {
asset().safeTransferFrom(by, address(this), assets);
uint256 totalIdle_;
assembly ("memory-safe") {
// if to == address(0)
if iszero(shl(96, to)) {
// throw the `InvalidZeroAddress` error
mstore(0x00, 0xf6b2911f)
revert(0x1c, 0x04)
}
// if assets == 0
if iszero(assets) {
// throw the `InvalidZeroAmount` error
mstore(0x00, 0xdd484e70)
revert(0x1c, 0x04)
}
// Get totalDeposits
totalIdle_ := sload(totalIdle.slot)
let totalAssets_ := add(totalIdle_, sload(totalDebt.slot))
if lt(totalAssets_, totalIdle_) { revert(0, 0) }
// check if totalDeposits + assets overflows
let total := add(totalAssets_, assets)
if lt(total, totalAssets_) { revert(0, 0) }
}
assembly ("memory-safe") {
// if shares == 0
if iszero(shares) {
// Throw the `InvalidZeroShares` error
mstore(0x00, 0x5a870a25)
revert(0x1c, 0x04)
}
}
_mint(to, shares);
assembly ("memory-safe") {
sstore(totalIdle.slot, add(totalIdle_, assets))
// Emit the {Deposit} event.
mstore(0x00, assets)
mstore(0x20, shares)
let m := shr(96, not(0))
log3(0x00, 0x40, _DEPOSIT_EVENT_SIGNATURE, and(m, by), and(m, to))
}
// if autipilot is enabled and > 1 week from last harvest check if there is any strategy in autopilot
// and harvest one strategy
if (autoPilotEnabled && lastReport + AUTOPILOT_HARVEST_INTERVAL < block.timestamp) {
// `to` will receive the extra shares from the management fees
(address strategy, bool success, bytes memory reason) = _forceOneHarvest(to);
if (!success) {
emit ForceHarvestFailed(strategy, reason);
}
}
}
/// @notice Burns `shares` from `owner` and sends exactly `assets` of underlying tokens to `to`.
/// @dev overriden to add the `noEmergencyShutdown` & `nonReentrant` modifiers
function withdraw(
uint256 assets,
address to,
address owner
)
public
override
nonReentrant
returns (uint256 shares)
{
if (assets == type(uint256).max) assets = maxWithdraw(owner);
if (assets > maxWithdraw(owner)) {
assembly ("memory-safe") {
mstore(0x00, 0x936941fc) // `WithdrawMoreThanMax()`.
revert(0x1c, 0x04)
}
}
shares = _withdraw(msg.sender, to, owner, assets);
}
/// @notice Burns exactly `shares` from `owner` and sends `assets` of underlying tokens to `to`.
/// @dev overriden to add the `noEmergencyShutdown` & `nonReentrant` modifiers
function redeem(uint256 shares, address to, address owner) public override nonReentrant returns (uint256 assets) {
if (shares == type(uint256).max) shares = maxRedeem(owner);
if (shares > maxRedeem(owner)) {
assembly ("memory-safe") {
mstore(0x00, 0x4656425a) // `RedeemMoreThanMax()`.
revert(0x1c, 0x04)
}
}
// substract losses to the total assets
assets = _redeem(msg.sender, to, owner, shares);
}
/// @dev Withdraws the needed amount of assets realising losses such as slippage
/// @return assets the real amount of assets withdrawn
function _redeem(address by, address to, address owner, uint256 shares) private returns (uint256 assets) {
if (by != owner) {
_spendAllowance(owner, by, shares);
}
assembly ("memory-safe") {
// if shares == 0
if iszero(shares) {
// throw the `InvalidZeroShares` error
mstore(0x00, 0x5a870a25)
revert(0x1c, 0x04)
}
}
// Calculate assets from shares
assets = convertToAssets(shares);
// Cache underlying asset
address underlying = asset();
uint256 vaultBalance = totalIdle;
// Check if value to withdraw exceeds vault balance
if (assets > vaultBalance) {
// Vault balance is not enough to cover withdrawal. We need to perform forced withdrawals
// from strategies until requested value amount is covered.
// During forced withdrawal, a Strategy may realize a loss, which is reported back to the
// Vault. This will affect the withdrawer, affecting the amount of tokens they will
// receive in exchange for their shares.
uint256 totalLoss;
// Iterate over strategies
for (uint256 i; i < MAXIMUM_STRATEGIES;) {
address strategy = withdrawalQueue[i];
// Check if we have exhausted the queue
if (strategy == address(0)) break;
// Check if the vault balance is finally enough to cover the requested withdrawal
if (vaultBalance >= assets) break;
uint256 slotStrategies2;
assembly {
// cache slot strategies[strategy].strategyTotalDebt
mstore(0x00, strategy)
mstore(0x20, strategies.slot)
slotStrategies2 := add(keccak256(0x00, 0x40), 2)
}
// Compute remaining amount to withdraw considering the current balance of the vault
uint256 amountRequested;
assembly ("memory-safe") {
// amountRequested = assets - vaultBalance;
amountRequested := sub(assets, vaultBalance)
}
// ask for the min between the needed amount and max withdraw of the strategy
amountRequested = Math.min(amountRequested, IStrategy(strategy).maxLiquidate());
// Try the next strategy if the current strategy has no debt to be withdrawn
if (amountRequested == 0) {
unchecked {
++i;
}
continue;
}
// Withdraw from strategy. Compute amount withdrawn
// considering the difference between balances pre/post withdrawal
uint256 preBalance = SafeTransferLib.balanceOf(underlying, address(this));
uint256 withdrawn;
uint256 loss;
// Use try/catch logic to avoid DoS
try IStrategy(strategy).liquidate(amountRequested) returns (uint256 _loss) {
loss = _loss;
withdrawn = SafeTransferLib.balanceOf(underlying, address(this)) - preBalance;
} catch {
unchecked {
++i;
}
continue;
}
if (withdrawn == 0) {
unchecked {
++i;
}
continue;
}
// Increase cached vault balance to track the newly withdrawn amount
vaultBalance += withdrawn;
// If loss has been realised, withdrawer will incur it, affecting to the amount
// of value they will receive in exchange for their shares
if (loss != 0) {
assets -= loss;
totalLoss += loss;
_reportLoss(strategy, loss);
}
// If the strategy has unharvested profit we could end up withdrawing more than its debt
// Then we will only decrease his debt by the strategy's debt
uint256 debtReduction = Math.min(strategies[strategy].strategyTotalDebt, withdrawn);
unchecked {
totalDebt = totalDebt - debtReduction;
}
uint128 strategyTotalDebt = uint128(strategies[strategy].strategyTotalDebt - debtReduction);
strategies[strategy].strategyTotalDebt = strategyTotalDebt;
assembly ("memory-safe") {
// Emit the `WithdrawFromStrategy` event
mstore(0x00, strategyTotalDebt)
mstore(0x20, loss)
log2(0x00, 0x40, _WITHDRAW_FROM_STRATEGY_EVENT_SIGNATURE, strategy)
}
unchecked {
++i;
}
}
// Update total idle with the actual vault balance that considers the total withdrawn amount
totalIdle = vaultBalance;
assembly ("memory-safe") {
let sum := add(assets, totalLoss)
if lt(sum, assets) {
// throw the `Overflow` error
revert(0, 0)
}
}
}
assembly ("memory-safe") {
if eq(assets, 0x00) {
// throw the `InvalidZeroAmount` error
mstore(0x00, 0xdd484e70)
revert(0x1c, 0x04)
}
}
// Burn shares
_burn(owner, shares);
// Reduce value withdrawn from vault total idle
if (assets > totalIdle) {
assets = totalIdle;
}
assembly ("memory-safe") {
if iszero(assets) {
// throw the `InvalidZeroAmount` error
mstore(0x00, 0xdd484e70)
revert(0x1c, 0x04)
}
}
unchecked {
totalIdle -= assets;
}
// Transfer underlying to `recipient`
SafeTransferLib.safeTransfer(underlying, to, assets);
assembly ("memory-safe") {
// Emit the {Withdraw} event.
mstore(0x00, assets)
mstore(0x20, shares)
let m := shr(96, not(0))
log4(0x00, 0x40, _WITHDRAW_EVENT_SIGNATURE, and(m, by), and(m, to), and(m, owner))
}
return assets;
}
/// @dev Burns the needed amount of shares to withdraw @param assets after realising loses
/// @return shares the real amount shares burnt
function _withdraw(address by, address to, address owner, uint256 assets) private returns (uint256 shares) {
assembly ("memory-safe") {
// if assets == 0
if iszero(assets) {
// throw the `InvalidZeroAmount` error
mstore(0x00, 0xdd484e70)
revert(0x1c, 0x04)
}
}
uint256 _totalAssets_ = _totalAssets();
uint256 vaultBalance = totalIdle;
uint256 o = _decimalsOffset();
address underlying = asset();
// convert the assets to shares without any losses
// very important: ROUND UP
shares = Math.fullMulDivUp(assets, totalSupply() + 10 ** o, _inc_(_totalAssets_));
// in case the vault's balance doesn't cover the requested `assets`
if (assets > vaultBalance) {
// Vault balance is not enough to cover withdrawal. We need to perform forced withdrawals
// from strategies until requested value amount is covered.
// During forced withdrawal, the vault will do exact amount requests to the strategies
// and account the losses needed to achieve those amounts. Those
// losses are reported back to the vault This will affect the withdrawer, affecting the amount of shares
// that will
// burn in order to withdraw exactly @param assets assets
uint256 totalLoss;
// Iterate over strategies
for (uint256 i; i < MAXIMUM_STRATEGIES;) {
address strategy = withdrawalQueue[i];
// Check if we have exhausted the queue
if (strategy == address(0)) break;
// Check if the vault balance is finally enough to cover the requested withdrawal
if (vaultBalance >= assets) break;
// Compute remaining amount to withdraw considering the current balance of the vault
uint256 amountRequested = assets - vaultBalance;
// Can't request more than allowed by the strategy
amountRequested = Math.min(amountRequested, IStrategy(strategy).maxLiquidateExact());
// Try the next strategy if the current strategy has no debt to be withdrawn
if (amountRequested == 0) {
unchecked {
++i;
}
continue;
}
// Withdraw from strategy. Compute amount withdrawn(should be requestedAmount)
// considering the difference between balances pre/post withdrawal
uint256 preBalance = underlying.balanceOf(address(this));
uint256 withdrawn;
uint256 loss;
// Use try/catch logic to avoid DoS
try IStrategy(strategy).liquidateExact(amountRequested) returns (uint256 _loss) {
loss = _loss;
withdrawn = SafeTransferLib.balanceOf(underlying, address(this)) - preBalance;
} catch {
unchecked {
++i;
}
continue;
}
if (withdrawn == 0) {
unchecked {
++i;
}
continue;
}
// increase the vault balance by the needed amount
vaultBalance += withdrawn;
// If loss has been realised, withdrawer will incur it, affecting to the amount
// of shares that the user will burn
if (loss != 0) {
totalLoss += loss;
_reportLoss(strategy, loss);
}
// If the strategy has unharvested profit we could end up withdrawing more than its debt
// Then we will only decrease his debt by the strategy's debt
uint256 debtReduction = Math.min(strategies[strategy].strategyTotalDebt, withdrawn);
unchecked {
totalDebt = totalDebt - debtReduction;
}
uint128 strategyTotalDebt = uint128(strategies[strategy].strategyTotalDebt - debtReduction);
strategies[strategy].strategyTotalDebt = strategyTotalDebt;
assembly ("memory-safe") {
// Emit the `WithdrawFromStrategy` event
mstore(0x00, strategyTotalDebt)
mstore(0x20, loss)
log2(0x00, 0x40, _WITHDRAW_FROM_STRATEGY_EVENT_SIGNATURE, strategy)
}
unchecked {
++i;
}
}
// Update total idle with the actual vault balance that considers the total withdrawn amount
totalIdle = vaultBalance;
// Increase the shares if there are any losses
shares += Math.fullMulDivUp(totalLoss, totalSupply() + 10 ** o, _inc_(_totalAssets_));
// if there are more assets to cover(when requesting more assets then total)
// we add the extra shares needed, even though it would revert if someone tries
// to withdraw that much since they wouln't have the needed shares
if (vaultBalance < assets) {
shares += Math.fullMulDivUp(assets - vaultBalance, totalSupply() + 10 ** o, _inc_(_totalAssets_));
}
}
// spend allowance
if (by != owner) {
_spendAllowance(owner, by, shares);
}
// Burn shares
_burn(owner, shares);
// Reduce value withdrawn from vault total idle
if (assets > totalIdle) {
revert();
}
unchecked {
totalIdle -= assets;
}
// Transfer underlying to `recipient`
SafeTransferLib.safeTransfer(underlying, to, assets);
assembly ("memory-safe") {
// Emit the {Withdraw} event.
mstore(0x00, assets)
mstore(0x20, shares)
let m := shr(96, not(0))
log4(0x00, 0x40, _WITHDRAW_EVENT_SIGNATURE, and(m, by), and(m, to), and(m, owner))
}
}
////////////////////////////////////////////////////////////////
/// REPORT LOGIC ///
////////////////////////////////////////////////////////////////
/// @notice Reports the amount of assets the calling Strategy has free (usually in terms of ROI).
/// The performance fee is determined here, off of the strategy's profits (if any), and sent to governance.
/// The strategist's fee is also determined here (off of profits), to be handled according to the strategist on the
/// next harvest.
/// @dev For approved strategies, this is the most efficient behavior. The Strategy reports back what it has free,
/// then
/// Vault "decides" whether to take some back or give it more.
/// Note that the most it can take is `gain + debtPayment`, and the most it can give is all of the
/// remaining reserves. Anything outside of those bounds is abnormal behavior
/// @param unrealizedGain Amount Strategy accounted as gain on its investment since its last report
/// @param loss Amount Strategy has realized as a loss on its investment since its last report, and should be
/// accounted for on the Vault's balance sheet. The loss will reduce the debtRatio for the strategy and vault.
/// The next time the strategy will harvest, it will pay back the debt in an attempt to adjust to the new debt
/// limit.
/// @param debtPayment Amount Strategy has made available to cover outstanding debt
/// @param managementFeeReceiver Address receiving the protocol fees
/// @return debt Amount of debt outstanding (if totalDebt > debtLimit or emergency shutdown).
function report(
uint128 unrealizedGain,
uint128 loss,
uint128 debtPayment,
address managementFeeReceiver
)
external
checkRoles(STRATEGY_ROLE)
returns (uint256)
{
// Cache underlying asset
address underlying = asset();
// Cache strategy balance
uint256 senderBalance = SafeTransferLib.balanceOf(underlying, msg.sender);
assembly ("memory-safe") {
// if (underlying.balanceOf(msg.sender) < realizedGain + debtPayment)
if lt(senderBalance, debtPayment) {
// throw the `InvalidReportedGainAndDebtPayment` error
mstore(0x00, 0x746feeec)
revert(0x1c, 0x04)
}
}
// If strategy suffered a loss, report it
if (loss > 0) {
_reportLoss(msg.sender, loss);
}
uint256 _totalFees = _assessFees(msg.sender, uint256(unrealizedGain), managementFeeReceiver);
// silence compiler warnings
_totalFees;
// Set reported gains as gains for the vault
strategies[msg.sender].strategyTotalUnrealizedGain += unrealizedGain;
// Compute the line of credit the Vault is able to offer the Strategy (if any)
uint256 credit = _creditAvailable(msg.sender);
// Compute excess of debt the Strategy wants to transfer back to the Vault (if any)
uint256 debt = strategies[msg.sender].strategyTotalDebt;
uint256 totalReportedAmount = debtPayment;
// Adjust excess of reported debt payment by the debt outstanding computed
debtPayment = uint128(Math.min(uint256(debtPayment), debt));
if (debtPayment != 0) {
strategies[msg.sender].strategyTotalDebt -= debtPayment;
totalDebt -= debtPayment;
debt -= debtPayment;
}
// Update the actual debt based on the full credit we are extending to the Strategy
if (credit != 0) {
strategies[msg.sender].strategyTotalDebt += uint128(credit);
totalDebt += credit;
}
// Give/take corresponding amount to/from Strategy, based on the debt needed to be paid off (if any)
unchecked {
if (credit > totalReportedAmount) {
// Credit is greater than the amount reported by the strategy, send funds **to** strategy
totalIdle -= (credit - totalReportedAmount);
SafeTransferLib.safeTransfer(underlying, msg.sender, credit - totalReportedAmount);
} else if (totalReportedAmount > credit) {
// Amount reported by the strategy is greater than the credit, take funds **from** strategy
totalIdle += (totalReportedAmount - credit);
asset().safeTransferFrom(msg.sender, address(this), totalReportedAmount - credit);
}
// else don't do anything (credit and reported amounts are balanced, hence no transfers need to be executed)
}
// Update reporting time
strategies[msg.sender].strategyLastReport = uint48(block.timestamp);
lastReport = block.timestamp;
emit StrategyReported(
msg.sender,
unrealizedGain,
loss,
debtPayment,
strategies[msg.sender].strategyTotalUnrealizedGain,
strategies[msg.sender].strategyTotalLoss,
strategies[msg.sender].strategyTotalDebt,
credit,
strategies[msg.sender].strategyDebtRatio
);
if (strategies[msg.sender].strategyDebtRatio == 0 || emergencyShutdown) {
// Take every last penny the Strategy has (Emergency Exit/revokeStrategy)
return IStrategy(msg.sender).estimatedTotalAssets();
}
// Otherwise, just return what we have as debt outstanding
return _debtOutstanding(msg.sender);
}
////////////////////////////////////////////////////////////////
/// STRATEGIES CONFIGURATION ///
////////////////////////////////////////////////////////////////
/// @notice Adds a new strategy
/// @dev The Strategy will be appended to `withdrawalQueue`, and `_organizeWithdrawalQueue` will reorganize the
/// queue order
/// @param newStrategy The new strategy to add
/// @param strategyDebtRatio The percentage of the total assets in the vault that the `newStrategy` has access to
/// @param strategyMaxDebtPerHarvest Lower limit on the increase of debt since last harvest
/// @param strategyMinDebtPerHarvest Upper limit on the increase of debt since last harvest
/// @param strategyPerformanceFee The fee the strategist will receive based on this Vault's performance
function addStrategy(
address newStrategy,
uint256 strategyDebtRatio,
uint256 strategyMaxDebtPerHarvest,
uint256 strategyMinDebtPerHarvest,
uint256 strategyPerformanceFee
)
external
checkRoles(ADMIN_ROLE)
noEmergencyShutdown
{
uint256 slot; // Slot where strategies[newStrategy] slot will be stored
assembly ("memory-safe") {
// General checks
// if (withdrawalQueue[MAXIMUM_STRATEGIES - 1] != address(0))
if sload(add(withdrawalQueue.slot, sub(MAXIMUM_STRATEGIES, 1))) {
// throw `QueueIsFull()` error
mstore(0x00, 0xa3d0cff3)
revert(0x1c, 0x04)
}
// Strategy checks
// if (newStrategy == address(0))
if iszero(newStrategy) {
// throw `InvalidZeroAddress()` error
mstore(0x00, 0xf6b2911f)
revert(0x1c, 0x04)
}
// Compute strategies[newStrategy] slot
mstore(0x00, newStrategy)
mstore(0x20, strategies.slot)
slot := keccak256(0x00, 0x40)
// if (strategies[newStrategy].strategyActivation != 0)
if shr(208, shl(176, sload(slot))) {
// throw `StrategyAlreadyActive()` error
mstore(0x00, 0xc976754d)
revert(0x1c, 0x04)
}
}
if (IStrategy(newStrategy).vault() != address(this)) {
assembly ("memory-safe") {
// throw `InvalidStrategyVault()` error
mstore(0x00, 0xac4e0773)
revert(0x1c, 0x04)
}
}
if (IStrategy(newStrategy).underlyingAsset() != asset()) {
assembly ("memory-safe") {
// throw `InvalidStrategyUnderlying()` error
mstore(0x00, 0xf083d3f1)
revert(0x1c, 0x04)
}
}
if (IStrategy(newStrategy).strategist() == address(0)) {
assembly ("memory-safe") {
// throw `StrategyMustHaveStrategist()` error
mstore(0x00, 0xeb8bf8b6)
revert(0x1c, 0x04)
}
}
uint256 debtRatio_;
assembly ("memory-safe") {
debtRatio_ := sload(debtRatio.slot)
// Compute debtRatio + strategyDebtRatio
let sum := add(debtRatio_, strategyDebtRatio)
if lt(sum, strategyDebtRatio) {
// throw the `Overflow` error
revert(0, 0)
}
// if (debtRatio + strategyDebtRatio > MAX_BPS)
if gt(sum, MAX_BPS) {
// throw the `InvalidDebtRatio` error
mstore(0x00, 0x79facb0d)
revert(0x1c, 0x04)
}
// if (strategyMinDebtPerHarvest > strategyMaxDebtPerHarvest)
if gt(strategyMinDebtPerHarvest, strategyMaxDebtPerHarvest) {
// throw the `InvalidMinDebtPerHarvest` error
mstore(0x00, 0x5f3bd953)
revert(0x1c, 0x04)
}
// if (strategyPerformanceFee > 5000)
if gt(strategyPerformanceFee, 5000) {
// throw the `InvalidPerformanceFee` error
mstore(0x00, 0xf14508d0)
revert(0x1c, 0x04)
}
// Add strategy to strategies mapping
// Strategy struct
// StrategyData({
// strategyPerformanceFee: uint16(strategyPerformanceFee),
// strategyDebtRatio: uint16(strategyDebtRatio),
// strategyActivation: uint48(block.timestamp),
// strategyLastReport: uint48(block.timestamp),
// strategyMaxDebtPerHarvest: uint128(strategyMaxDebtPerHarvest),
// strategyMinDebtPerHarvest: uint128(strategyMinDebtPerHarvest),
// strategyTotalDebt: 0,
// strategyTotalUnrealizedGain: 0,
// strategyTotalLoss: 0
// });
// Using yul saves 5k gas, bitmasks are used to create the `StrategyData` struct above.
// Slot 0 and slot 1 will be updated. Slot 2 is not updated since it stores `strategyTotalDebt`
// and `strategyTotalLoss`, which will remain with a value of 0 upon strategy addition.
// Store data for slot 0 in strategies[newStrategy]
sstore(
slot,
or(
shl(128, strategyMaxDebtPerHarvest),
or(
shl(80, and(0xffffffffffff, timestamp())), // Set `strategyLastReport` to `block.timestamp`
or(
shl(32, and(0xffffffffffff, timestamp())), // Set `strategyActivation` to `block.timestamp`
or(shl(16, and(0xffff, strategyPerformanceFee)), and(0xffff, strategyDebtRatio))
)
)
)
)
// Store data for slot 1 in strategies[newStrategy]
sstore(add(slot, 1), shr(128, shl(128, strategyMinDebtPerHarvest)))
}
// Grant `STRATEGY_ROLE` to strategy
_grantRoles(newStrategy, STRATEGY_ROLE);
assembly {
// Update vault parameters
// debtRatio += strategyDebtRatio;
sstore(debtRatio.slot, add(debtRatio_, strategyDebtRatio))
// Add strategy to withdrawal queue
// withdrawalQueue[MAXIMUM_STRATEGIES - 1] = newStrategy;
sstore(add(withdrawalQueue.slot, sub(MAXIMUM_STRATEGIES, 1)), newStrategy)
}
_organizeWithdrawalQueue();
assembly ("memory-safe") {
// Emit the `StrategyAdded` event
mstore(0x00, strategyDebtRatio)
mstore(0x20, strategyMaxDebtPerHarvest)
mstore(0x40, strategyMinDebtPerHarvest)
mstore(0x60, strategyPerformanceFee)
log2(0x00, 0x80, _STRATEGY_ADDED_EVENT_SIGNATURE, newStrategy)
}
}
/// @notice Removes a strategy from the queue
/// @dev We don't do this with `revokeStrategy` because it should still be possible to withdraw from the Strategy
/// if it's unwinding.
/// @param strategy The strategy to remove
function removeStrategy(address strategy) external checkRoles(ADMIN_ROLE) noEmergencyShutdown {
address[MAXIMUM_STRATEGIES] memory cachedWithdrawalQueue = withdrawalQueue;
for (uint256 i; i < MAXIMUM_STRATEGIES;) {
if (cachedWithdrawalQueue[i] == strategy) {
// The strategy was found and can be removed
withdrawalQueue[i] = address(0);
_removeRoles(strategy, STRATEGY_ROLE);
// Update withdrawal queue
_organizeWithdrawalQueue();
// Emit the `StrategyRemoved` event
assembly {
log2(0x00, 0x00, _STRATEGY_REMOVED_EVENT_SIGNATURE, strategy)
}
return;
}
unchecked {
++i;
}
}
}
/// @notice Revoke a Strategy, setting its debt limit to 0 and preventing any future deposits
/// @dev This function should only be used in the scenario where the Strategy is being retired but no migration
/// of the positions is possible, or in the extreme scenario that the Strategy needs to be put into "Emergency Exit"
/// mode in order for it to exit as quickly as possible. The latter scenario could be for any reason that is
/// considered
/// "critical" that the Strategy exits its position as fast as possible, such as a sudden change in market
/// conditions leading to losses, or an imminent failure in an external dependency.
/// @param strategy The strategy to revoke
function revokeStrategy(address strategy) external checkRoles(ADMIN_ROLE) {
uint256 cachedStrategyDebtRatio = strategies[strategy].strategyDebtRatio; // Saves an SLOAD if strategy is !=
// addr(0)
assembly ("memory-safe") {
// if (strategies[strategy].strategyActivation == 0)
if iszero(cachedStrategyDebtRatio) {
// throw `StrategyDebtRatioAlreadyZero()` error
mstore(0x00, 0xe3a1d5ed)
revert(0x1c, 0x04)
}
}
// Remove `STRATEGY_ROLE` from strategy
_removeRoles(strategy, STRATEGY_ROLE);
// Revoke the strategy
_revokeStrategy(strategy, cachedStrategyDebtRatio);
}
/// @notice Fully exit a strategy
/// @dev This is the most aggressive strategy exit plan, it liquidates all the positions
/// from the strategy, revoke the strategy role, and remove it from the withdrawal queue
/// as well
/// @param strategy The strategy to revoke
function exitStrategy(address strategy) external checkRoles(ADMIN_ROLE) {
// Liquidate the strategy fully
IStrategy _strategy = IStrategy(strategy);
uint256 _maxWithdraw = _strategy.maxLiquidate();
uint256 loss = _strategy.liquidate(_maxWithdraw);
uint256 withdrawn = _sub0(_maxWithdraw, loss);
uint256 strategyTotalDebt = strategies[strategy].strategyTotalDebt;
uint256 strategyDebtRatio = strategies[strategy].strategyDebtRatio;
totalIdle += withdrawn;
// Cannot underflow
unchecked {
totalDebt -= strategyTotalDebt;
debtRatio -= strategyDebtRatio;
}
// Clear debt of strategy
strategies[strategy].autoPilot = false;
strategies[strategy].strategyActivation = 0;
strategies[strategy].strategyTotalDebt = 0;
strategies[strategy].strategyDebtRatio = 0;
// Remove the strategy from the queue
address[MAXIMUM_STRATEGIES] memory cachedWithdrawalQueue = withdrawalQueue;
for (uint256 i; i < MAXIMUM_STRATEGIES;) {
if (cachedWithdrawalQueue[i] == strategy) {
// The strategy was found and can be removed
withdrawalQueue[i] = address(0);
// Remove `STRATEGY_ROLE` from strategy
_removeRoles(strategy, STRATEGY_ROLE);
// Update withdrawal queue
_organizeWithdrawalQueue();
assembly {
// Emit the `StrategyRemoved` event
log2(0x00, 0x00, _STRATEGY_REMOVED_EVENT_SIGNATURE, strategy)
// Emit the `StrategyExited` event
mstore(0x00, withdrawn)
log2(0x00, 0x20, _STRATEGY_EXITED_EVENT_SIGNATURE, strategy)
}
return;
}
unchecked {
++i;
}
}
}
/// @notice Updates a given strategy configured data
/// @param strategy The strategy to change the data to
/// @param newDebtRatio The new percentage of the total assets in the vault that `strategy` has access to
/// @param newMaxDebtPerHarvest New lower limit on the increase of debt since last harvest
/// @param newMinDebtPerHarvest New upper limit on the increase of debt since last harvest
/// @param newPerformanceFee New fee the strategist will receive based on this Vault's performance
function updateStrategyData(
address strategy,
uint256 newDebtRatio,
uint256 newMaxDebtPerHarvest,
uint256 newMinDebtPerHarvest,
uint256 newPerformanceFee
)
external
checkRoles(ADMIN_ROLE)
{
uint256 slot; // Slot where strategies[strategy] slot will be stored
uint256 slotContent; // Used to store strategies[strategy] slot content
assembly ("memory-safe") {
// Compute strategies[newStrategy] slot
mstore(0x00, strategy)
mstore(0x20, strategies.slot)
slot := keccak256(0x00, 0x40)
// Load strategies[newStrategy] data into `slotContent`
slotContent := sload(slot)
// if (strategyData.strategyActivation == 0)
if iszero(shr(208, shl(176, slotContent))) {
// throw `StrategyNotActive()` error
mstore(0x00, 0xdc974a98)
revert(0x1c, 0x04)
}
}
if (IStrategy(strategy).emergencyExit() == 2) {
assembly ("memory-safe") {
// throw `StrategyInEmergencyExitMode()` error
mstore(0x00, 0x57c7c24f)
revert(0x1c, 0x04)
}
}
assembly ("memory-safe") {
// if (newMinDebtPerHarvest > newMaxDebtPerHarvest)
if gt(newMinDebtPerHarvest, newMaxDebtPerHarvest) {
// throw the `InvalidMinDebtPerHarvest` error
mstore(0x00, 0x5f3bd953)
revert(0x1c, 0x04)
}
// if (strategyPerformanceFee > 5000)
if gt(newPerformanceFee, 5000) {
// throw the `InvalidPerformanceFee` error
mstore(0x00, 0xf14508d0)
revert(0x1c, 0x04)
}
}
uint256 strategyDebtRatio_;
assembly {
// Compute strategies[newStrategy].strategyDebtRatio
strategyDebtRatio_ := shr(240, shl(240, slotContent))
}
uint256 debtRatio_;
unchecked {
// Update `debtRatio` storage as well as cache `debtRatio` final value result in `debtRatio_`
// Underflowing will make maxbps check fail later
debtRatio_ = debtRatio -= strategyDebtRatio_;
}
assembly ("memory-safe") {
let sum := add(debtRatio_, newDebtRatio)
if lt(sum, debtRatio_) {
// throw the `Overflow` error
revert(0, 0)
}
// if (debtRatio_ + newDebtRatio > MAX_BPS)
if gt(sum, MAX_BPS) {
// throw the `InvalidDebtRatio` error
mstore(0x00, 0x79facb0d)
revert(0x1c, 0x04)
}
}
unchecked {
// Add new debt ratio to current `debtRatio`
debtRatio = debtRatio_ + newDebtRatio;
}
assembly ("memory-safe") {
// Update strategies[strategy] with new updated data: debtRatio, maxDebtPerHarvest, minDebtPerHarvest,
// performanceFee
// Slot 0 and slot 1 will be updated with the new values. Slot 2 is not updated since it stores
// `strategyTotalDebt`
// and `strategyTotalLoss`, which are not updated in `updateStrategyData()`.
// Store data for slot 0 in strategies[strategy]
sstore(
slot,
or(
// Obtain old values in slot
and(shl(32, 0xffffffffffffffffffffffff), slotContent), // Extract previously stored
// `strategyActivation` and `strategyLastReport`
// Build new values to store
or(
shl(128, newMaxDebtPerHarvest),
or(shl(16, and(0xffff, newPerformanceFee)), and(0xffff, newDebtRatio))
)
)
)
// Store data for slot 1 in strategies[strategy]
sstore(
add(slot, 1),
or(
// Obtain old values in slot
shl(128, shr(128, sload(add(slot, 1)))), // Extract previously stored `strategyTotalUnrealizedGain`
// Build new values to store
shr(128, shl(128, newMinDebtPerHarvest))
)
)
// Emit the `StrategyUpdated` event
mstore(0x00, newDebtRatio)
mstore(0x20, newMaxDebtPerHarvest)
mstore(0x40, newMinDebtPerHarvest)
mstore(0x60, newPerformanceFee)
log2(0x00, 0x80, _STRATEGY_UPDATED_EVENT_SIGNATURE, strategy)
}
}
////////////////////////////////////////////////////////////////
/// VAULT CONFIGURATION ///
////////////////////////////////////////////////////////////////
/// @notice Updates the withdrawalQueue to match the addresses and order specified by `queue`
/// @dev There can be fewer strategies than the maximum, as well as fewer than the total number
/// of strategies active in the vault.
/// Note This is order sensitive, specify the addresses in the order in which funds should be
/// withdrawn (so `queue`[0] is the first Strategy withdrawn from, `queue`[1] is the second, etc.),
/// and add address(0) only when strategies to be added have occupied first queue positions.
/// This means that the least impactful Strategy (the Strategy that will have its core positions
/// impacted the least by having funds removed) should be at `queue`[0], then the next least
/// impactful at `queue`[1], and so on.
/// @param queue The array of addresses to use as the new withdrawal queue. **This is order sensitive**.
function setWithdrawalQueue(address[MAXIMUM_STRATEGIES] calldata queue) external checkRoles(ADMIN_ROLE) {
address prevStrategy;
// Check queue order is correct
for (uint256 i; i < MAXIMUM_STRATEGIES;) {
assembly ("memory-safe") {
let strategy := calldataload(add(4, mul(i, 0x20)))
// if (prevStrategy == address(0) && queue[i] != address(0) && i != 0)
if and(gt(strategy, 0), and(iszero(prevStrategy), gt(i, 0))) {
// throw the `InvalidQueueOrder` error
mstore(0x00, 0xefb91db4)
revert(0x1c, 0x04)
}
// Store data necessary to compute strategies[newStrategy] slot
mstore(0x00, strategy)
mstore(0x20, strategies.slot)
// if (strategy != address(0) && strategies[strategy].strategyActivation == 0)
if and(iszero(shr(208, shl(176, sload(keccak256(0x00, 0x40))))), gt(strategy, 0)) {
// throw the `StrategyNotActive` error
mstore(0x00, 0xdc974a98)
revert(0x1c, 0x04)
}
prevStrategy := strategy
}
unchecked {
++i;
}
}
withdrawalQueue = queue;
emit WithdrawalQueueUpdated(queue);
}
/// @notice Used to change the value of `performanceFee`
/// @dev Should set this value below the maximum strategist performance fee
/// @param _performanceFee The new performance fee to use
function setPerformanceFee(uint256 _performanceFee) external checkRoles(ADMIN_ROLE) {
assembly ("memory-safe") {
// if (strategyPerformanceFee > 5000)
if gt(_performanceFee, 5000) {
// throw the `InvalidPerformanceFee` error
mstore(0x00, 0xf14508d0)
revert(0x1c, 0x04)
}
}
performanceFee = _performanceFee;
assembly ("memory-safe") {
// Emit the `PerformanceFeeUpdated` event
mstore(0x00, _performanceFee)
log1(0x00, 0x20, _PERFORMANCE_FEE_UPDATED_EVENT_SIGNATURE)
}
}
/// @notice Used to change the value of `managementFee`
/// @param _managementFee The new performance fee to use
function setManagementFee(uint256 _managementFee) external checkRoles(ADMIN_ROLE) {
assembly ("memory-safe") {
// if (_managementFee > MAX_BPS)
if gt(_managementFee, MAX_BPS) {
// throw the `InvalidManagementFee` error
mstore(0x00, 0x8e9b51ff)
revert(0x1c, 0x04)
}
}
managementFee = _managementFee;
assembly {
// Emit the `ManagementFeeUpdated` event
mstore(0x00, _managementFee)
log1(0x00, 0x20, _MANAGEMENT_FEE_UPDATED_EVENT_SIGNATURE)
}
}
/// @notice Changes the maximum amount of tokens that can be deposited in this Vault
/// @dev This is not how much may be deposited by a single depositor,
/// but the maximum amount that may be deposited across all depositors
/// @param _depositLimit The new deposit limit to use
function setDepositLimit(uint256 _depositLimit) external checkRoles(ADMIN_ROLE) {
depositLimit = _depositLimit;
assembly ("memory-safe") {
// Emit the `DepositLimitUpdated` event
mstore(0x00, _depositLimit)
log1(0x00, 0x20, _DEPOSIT_LIMIT_UPDATED_EVENT_SIGNATURE)
}
}
/// @notice Activates or deactivates Vault mode where all Strategies go into full withdrawal.
/// During Emergency Shutdown:
/// 1. No users may deposit into the Vault (but may withdraw as usual)
/// 2. No new Strategies may be added
/// 3. Each Strategy must pay back their debt as quickly as reasonable to minimally affect their position
/// @param _emergencyShutdown If true, the Vault goes into Emergency Shutdown. If false, the Vault goes back into
/// normal operation
function setEmergencyShutdown(bool _emergencyShutdown) external checkRoles(EMERGENCY_ADMIN_ROLE) {
emergencyShutdown = _emergencyShutdown;
assembly ("memory-safe") {
// Emit the `EmergencyShutdownUpdated` event
mstore(0x00, _emergencyShutdown)
log1(0x00, 0x20, _EMERGENCY_SHUTDOWN_UPDATED_EVENT_SIGNATURE)
}
}
/// @notice Updates the treasury address
/// @param _treasury The new treasury address
function setTreasury(address _treasury) external checkRoles(ADMIN_ROLE) {
treasury = _treasury;
assembly ("memory-safe") {
// Emit the `TreasuryUpdated` event
mstore(0x00, _treasury)
log1(0x00, 0x20, _TREASURY_UPDATED_EVENT_SIGNATURE)
}
}
/// @notice Enables or disables the autopilot mode, that allows for automated harvesting
/// of strategies from the vault
/// If autopilot is enabled:
/// 1. Strategies can switch to autopilot mode
/// 2. Every week ,when one user deposits the vault with force the harvest of one strategy every time
/// 3. The depositing user that calls harvest will get extra shares as a reward for paying for the harvest gas
/// @param _autoPilotEnabled If true, it is activated, if false it is disabled
function setAutopilotEnabled(bool _autoPilotEnabled) external checkRoles(ADMIN_ROLE) {
autoPilotEnabled = _autoPilotEnabled;
assembly ("memory-safe") {
// Emit the `AutoPilotEnabled` event
mstore(0x00, _autoPilotEnabled)
log1(0x00, 0x20, _AUTOPILOT_ENABLED_EVENT_SIGNATURE)
}
}
/// @notice Switches the autopilot mode of a strategy
/// @param _autoPilot If true, set the strategy in autiopilot mode
function setAutoPilot(bool _autoPilot) external checkRoles(STRATEGY_ROLE) {
strategies[msg.sender].autoPilot = _autoPilot;
}
////////////////////////////////////////////////////////////////
/// VIEW FUNCTIONS ///
////////////////////////////////////////////////////////////////
/// @notice Amount of tokens in Vault a Strategy has access to as a credit line.
/// This will check the Strategy's debt limit, as well as the tokens available in the
/// Vault, and determine the maximum amount of tokens (if any) the Strategy may draw on
/// @param strategy The strategy to check
/// @return The quantity of tokens available for the Strategy to draw on
function creditAvailable(address strategy) external view returns (uint256) {
return _creditAvailable(strategy);
}
/// @notice Determines if `strategy` is past its debt limit and if any tokens should be withdrawn to the Vault
/// @param strategy The Strategy to check
/// @return The quantity of tokens to withdraw
function debtOutstanding(address strategy) external view returns (uint256) {
return _debtOutstanding(strategy);
}
/// @notice returns stratetegyTotalDebt, saves gas, no need to return the whole struct
/// @param strategy The Strategy to check
/// @return strategyTotalDebt The strategy's total debt
function getStrategyTotalDebt(address strategy) external view returns (uint256 strategyTotalDebt) {
assembly ("memory-safe") {
// Store data necessary to compute strategies[newStrategy] slot
mstore(0x00, strategy)
mstore(0x20, strategies.slot)
// Obtain strategies[strategy].strategyTotalDebt, stored in struct's slot 2
strategyTotalDebt := shr(128, shl(128, sload(add(keccak256(0x00, 0x40), 2))))
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple single owner authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
///
/// @dev Note:
/// This implementation does NOT auto-initialize the owner to `msg.sender`.
/// You MUST call the `_initializeOwner` in the constructor / initializer.
///
/// While the ownable portion follows
/// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
/// the nomenclature for the 2-step ownership handover may be unique to this codebase.
abstract contract Ownable {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The caller is not authorized to call the function.
error Unauthorized();
/// @dev The `newOwner` cannot be the zero address.
error NewOwnerIsZeroAddress();
/// @dev The `pendingOwner` does not have a valid handover request.
error NoHandoverRequest();
/// @dev Cannot double-initialize.
error AlreadyInitialized();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ownership is transferred from `oldOwner` to `newOwner`.
/// This event is intentionally kept the same as OpenZeppelin's Ownable to be
/// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
/// despite it not being as lightweight as a single argument event.
event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);
/// @dev An ownership handover to `pendingOwner` has been requested.
event OwnershipHandoverRequested(address indexed pendingOwner);
/// @dev The ownership handover to `pendingOwner` has been canceled.
event OwnershipHandoverCanceled(address indexed pendingOwner);
/// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;
/// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`.
uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =
0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;
/// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`.
uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =
0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The owner slot is given by:
/// `bytes32(~uint256(uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))))`.
/// It is intentionally chosen to be a high value
/// to avoid collision with lower slots.
/// The choice of manual storage layout is to enable compatibility
/// with both regular and upgradeable contracts.
bytes32 internal constant _OWNER_SLOT =
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff74873927;
/// The ownership handover slot of `newOwner` is given by:
/// ```
/// mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))
/// let handoverSlot := keccak256(0x00, 0x20)
/// ```
/// It stores the expiry timestamp of the two-step ownership handover.
uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Override to return true to make `_initializeOwner` prevent double-initialization.
function _guardInitializeOwner() internal pure virtual returns (bool guard) {}
/// @dev Initializes the owner directly without authorization guard.
/// This function must be called upon initialization,
/// regardless of whether the contract is upgradeable or not.
/// This is to enable generalization to both regular and upgradeable contracts,
/// and to save gas in case the initial owner is not the caller.
/// For performance reasons, this function will not check if there
/// is an existing owner.
function _initializeOwner(address newOwner) internal virtual {
if (_guardInitializeOwner()) {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
if sload(ownerSlot) {
mstore(0x00, 0x0dc149f0) // `AlreadyInitialized()`.
revert(0x1c, 0x04)
}
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Store the new value.
sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
}
} else {
/// @solidity memory-safe-assembly
assembly {
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Store the new value.
sstore(_OWNER_SLOT, newOwner)
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
}
}
}
/// @dev Sets the owner directly without authorization guard.
function _setOwner(address newOwner) internal virtual {
if (_guardInitializeOwner()) {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
// Store the new value.
sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
}
} else {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
// Store the new value.
sstore(ownerSlot, newOwner)
}
}
}
/// @dev Throws if the sender is not the owner.
function _checkOwner() internal view virtual {
/// @solidity memory-safe-assembly
assembly {
// If the caller is not the stored owner, revert.
if iszero(eq(caller(), sload(_OWNER_SLOT))) {
mstore(0x00, 0x82b42900) // `Unauthorized()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Returns how long a two-step ownership handover is valid for in seconds.
/// Override to return a different value if needed.
/// Made internal to conserve bytecode. Wrap it in a public function if needed.
function _ownershipHandoverValidFor() internal view virtual returns (uint64) {
return 48 * 3600;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC UPDATE FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Allows the owner to transfer the ownership to `newOwner`.
function transferOwnership(address newOwner) public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
if iszero(shl(96, newOwner)) {
mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.
revert(0x1c, 0x04)
}
}
_setOwner(newOwner);
}
/// @dev Allows the owner to renounce their ownership.
function renounceOwnership() public payable virtual onlyOwner {
_setOwner(address(0));
}
/// @dev Request a two-step ownership handover to the caller.
/// The request will automatically expire in 48 hours (172800 seconds) by default.
function requestOwnershipHandover() public payable virtual {
unchecked {
uint256 expires = block.timestamp + _ownershipHandoverValidFor();
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to `expires`.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), expires)
// Emit the {OwnershipHandoverRequested} event.
log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())
}
}
}
/// @dev Cancels the two-step ownership handover to the caller, if any.
function cancelOwnershipHandover() public payable virtual {
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to 0.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), 0)
// Emit the {OwnershipHandoverCanceled} event.
log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())
}
}
/// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
/// Reverts if there is no existing ownership handover requested by `pendingOwner`.
function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to 0.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, pendingOwner)
let handoverSlot := keccak256(0x0c, 0x20)
// If the handover does not exist, or has expired.
if gt(timestamp(), sload(handoverSlot)) {
mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.
revert(0x1c, 0x04)
}
// Set the handover slot to 0.
sstore(handoverSlot, 0)
}
_setOwner(pendingOwner);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC READ FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the owner of the contract.
function owner() public view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
result := sload(_OWNER_SLOT)
}
}
/// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
function ownershipHandoverExpiresAt(address pendingOwner)
public
view
virtual
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
// Compute the handover slot.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, pendingOwner)
// Load the handover slot.
result := sload(keccak256(0x0c, 0x20))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* MODIFIERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Marks a function as only callable by the owner.
modifier onlyOwner() virtual {
_checkOwner();
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {Ownable} from "./Ownable.sol";
/// @notice Simple single owner and multiroles authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
/// @dev While the ownable portion follows [EIP-173](https://eips.ethereum.org/EIPS/eip-173)
/// for compatibility, the nomenclature for the 2-step ownership handover and roles
/// may be unique to this codebase.
abstract contract OwnableRoles is Ownable {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The `user`'s roles is updated to `roles`.
/// Each bit of `roles` represents whether the role is set.
event RolesUpdated(address indexed user, uint256 indexed roles);
/// @dev `keccak256(bytes("RolesUpdated(address,uint256)"))`.
uint256 private constant _ROLES_UPDATED_EVENT_SIGNATURE =
0x715ad5ce61fc9595c7b415289d59cf203f23a94fa06f04af7e489a0a76e1fe26;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The role slot of `user` is given by:
/// ```
/// mstore(0x00, or(shl(96, user), _ROLE_SLOT_SEED))
/// let roleSlot := keccak256(0x00, 0x20)
/// ```
/// This automatically ignores the upper bits of the `user` in case
/// they are not clean, as well as keep the `keccak256` under 32-bytes.
///
/// Note: This is equivalent to `uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))`.
uint256 private constant _ROLE_SLOT_SEED = 0x8b78c6d8;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Overwrite the roles directly without authorization guard.
function _setRoles(address user, uint256 roles) internal virtual {
/// @solidity memory-safe-assembly
assembly {
mstore(0x0c, _ROLE_SLOT_SEED)
mstore(0x00, user)
// Store the new value.
sstore(keccak256(0x0c, 0x20), roles)
// Emit the {RolesUpdated} event.
log3(0, 0, _ROLES_UPDATED_EVENT_SIGNATURE, shr(96, mload(0x0c)), roles)
}
}
/// @dev Updates the roles directly without authorization guard.
/// If `on` is true, each set bit of `roles` will be turned on,
/// otherwise, each set bit of `roles` will be turned off.
function _updateRoles(address user, uint256 roles, bool on) internal virtual {
/// @solidity memory-safe-assembly
assembly {
mstore(0x0c, _ROLE_SLOT_SEED)
mstore(0x00, user)
let roleSlot := keccak256(0x0c, 0x20)
// Load the current value.
let current := sload(roleSlot)
// Compute the updated roles if `on` is true.
let updated := or(current, roles)
// Compute the updated roles if `on` is false.
// Use `and` to compute the intersection of `current` and `roles`,
// `xor` it with `current` to flip the bits in the intersection.
if iszero(on) { updated := xor(current, and(current, roles)) }
// Then, store the new value.
sstore(roleSlot, updated)
// Emit the {RolesUpdated} event.
log3(0, 0, _ROLES_UPDATED_EVENT_SIGNATURE, shr(96, mload(0x0c)), updated)
}
}
/// @dev Grants the roles directly without authorization guard.
/// Each bit of `roles` represents the role to turn on.
function _grantRoles(address user, uint256 roles) internal virtual {
_updateRoles(user, roles, true);
}
/// @dev Removes the roles directly without authorization guard.
/// Each bit of `roles` represents the role to turn off.
function _removeRoles(address user, uint256 roles) internal virtual {
_updateRoles(user, roles, false);
}
/// @dev Throws if the sender does not have any of the `roles`.
function _checkRoles(uint256 roles) internal view virtual {
/// @solidity memory-safe-assembly
assembly {
// Compute the role slot.
mstore(0x0c, _ROLE_SLOT_SEED)
mstore(0x00, caller())
// Load the stored value, and if the `and` intersection
// of the value and `roles` is zero, revert.
if iszero(and(sload(keccak256(0x0c, 0x20)), roles)) {
mstore(0x00, 0x82b42900) // `Unauthorized()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Throws if the sender is not the owner,
/// and does not have any of the `roles`.
/// Checks for ownership first, then lazily checks for roles.
function _checkOwnerOrRoles(uint256 roles) internal view virtual {
/// @solidity memory-safe-assembly
assembly {
// If the caller is not the stored owner.
// Note: `_ROLE_SLOT_SEED` is equal to `_OWNER_SLOT_NOT`.
if iszero(eq(caller(), sload(not(_ROLE_SLOT_SEED)))) {
// Compute the role slot.
mstore(0x0c, _ROLE_SLOT_SEED)
mstore(0x00, caller())
// Load the stored value, and if the `and` intersection
// of the value and `roles` is zero, revert.
if iszero(and(sload(keccak256(0x0c, 0x20)), roles)) {
mstore(0x00, 0x82b42900) // `Unauthorized()`.
revert(0x1c, 0x04)
}
}
}
}
/// @dev Throws if the sender does not have any of the `roles`,
/// and is not the owner.
/// Checks for roles first, then lazily checks for ownership.
function _checkRolesOrOwner(uint256 roles) internal view virtual {
/// @solidity memory-safe-assembly
assembly {
// Compute the role slot.
mstore(0x0c, _ROLE_SLOT_SEED)
mstore(0x00, caller())
// Load the stored value, and if the `and` intersection
// of the value and `roles` is zero, revert.
if iszero(and(sload(keccak256(0x0c, 0x20)), roles)) {
// If the caller is not the stored owner.
// Note: `_ROLE_SLOT_SEED` is equal to `_OWNER_SLOT_NOT`.
if iszero(eq(caller(), sload(not(_ROLE_SLOT_SEED)))) {
mstore(0x00, 0x82b42900) // `Unauthorized()`.
revert(0x1c, 0x04)
}
}
}
}
/// @dev Convenience function to return a `roles` bitmap from an array of `ordinals`.
/// This is meant for frontends like Etherscan, and is therefore not fully optimized.
/// Not recommended to be called on-chain.
/// Made internal to conserve bytecode. Wrap it in a public function if needed.
function _rolesFromOrdinals(uint8[] memory ordinals) internal pure returns (uint256 roles) {
/// @solidity memory-safe-assembly
assembly {
for { let i := shl(5, mload(ordinals)) } i { i := sub(i, 0x20) } {
// We don't need to mask the values of `ordinals`, as Solidity
// cleans dirty upper bits when storing variables into memory.
roles := or(shl(mload(add(ordinals, i)), 1), roles)
}
}
}
/// @dev Convenience function to return an array of `ordinals` from the `roles` bitmap.
/// This is meant for frontends like Etherscan, and is therefore not fully optimized.
/// Not recommended to be called on-chain.
/// Made internal to conserve bytecode. Wrap it in a public function if needed.
function _ordinalsFromRoles(uint256 roles) internal pure returns (uint8[] memory ordinals) {
/// @solidity memory-safe-assembly
assembly {
// Grab the pointer to the free memory.
ordinals := mload(0x40)
let ptr := add(ordinals, 0x20)
let o := 0
// The absence of lookup tables, De Bruijn, etc., here is intentional for
// smaller bytecode, as this function is not meant to be called on-chain.
for { let t := roles } 1 {} {
mstore(ptr, o)
// `shr` 5 is equivalent to multiplying by 0x20.
// Push back into the ordinals array if the bit is set.
ptr := add(ptr, shl(5, and(t, 1)))
o := add(o, 1)
t := shr(o, roles)
if iszero(t) { break }
}
// Store the length of `ordinals`.
mstore(ordinals, shr(5, sub(ptr, add(ordinals, 0x20))))
// Allocate the memory.
mstore(0x40, ptr)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC UPDATE FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Allows the owner to grant `user` `roles`.
/// If the `user` already has a role, then it will be an no-op for the role.
function grantRoles(address user, uint256 roles) public payable virtual onlyOwner {
_grantRoles(user, roles);
}
/// @dev Allows the owner to remove `user` `roles`.
/// If the `user` does not have a role, then it will be an no-op for the role.
function revokeRoles(address user, uint256 roles) public payable virtual onlyOwner {
_removeRoles(user, roles);
}
/// @dev Allow the caller to remove their own roles.
/// If the caller does not have a role, then it will be an no-op for the role.
function renounceRoles(uint256 roles) public payable virtual {
_removeRoles(msg.sender, roles);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC READ FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the roles of `user`.
function rolesOf(address user) public view virtual returns (uint256 roles) {
/// @solidity memory-safe-assembly
assembly {
// Compute the role slot.
mstore(0x0c, _ROLE_SLOT_SEED)
mstore(0x00, user)
// Load the stored value.
roles := sload(keccak256(0x0c, 0x20))
}
}
/// @dev Returns whether `user` has any of `roles`.
function hasAnyRole(address user, uint256 roles) public view virtual returns (bool) {
return rolesOf(user) & roles != 0;
}
/// @dev Returns whether `user` has all of `roles`.
function hasAllRoles(address user, uint256 roles) public view virtual returns (bool) {
return rolesOf(user) & roles == roles;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* MODIFIERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Marks a function as only callable by an account with `roles`.
modifier onlyRoles(uint256 roles) virtual {
_checkRoles(roles);
_;
}
/// @dev Marks a function as only callable by the owner or by an account
/// with `roles`. Checks for ownership first, then lazily checks for roles.
modifier onlyOwnerOrRoles(uint256 roles) virtual {
_checkOwnerOrRoles(roles);
_;
}
/// @dev Marks a function as only callable by an account with `roles`
/// or the owner. Checks for roles first, then lazily checks for ownership.
modifier onlyRolesOrOwner(uint256 roles) virtual {
_checkRolesOrOwner(roles);
_;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ROLE CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// IYKYK
uint256 internal constant _ROLE_0 = 1 << 0;
uint256 internal constant _ROLE_1 = 1 << 1;
uint256 internal constant _ROLE_2 = 1 << 2;
uint256 internal constant _ROLE_3 = 1 << 3;
uint256 internal constant _ROLE_4 = 1 << 4;
uint256 internal constant _ROLE_5 = 1 << 5;
uint256 internal constant _ROLE_6 = 1 << 6;
uint256 internal constant _ROLE_7 = 1 << 7;
uint256 internal constant _ROLE_8 = 1 << 8;
uint256 internal constant _ROLE_9 = 1 << 9;
uint256 internal constant _ROLE_10 = 1 << 10;
uint256 internal constant _ROLE_11 = 1 << 11;
uint256 internal constant _ROLE_12 = 1 << 12;
uint256 internal constant _ROLE_13 = 1 << 13;
uint256 internal constant _ROLE_14 = 1 << 14;
uint256 internal constant _ROLE_15 = 1 << 15;
uint256 internal constant _ROLE_16 = 1 << 16;
uint256 internal constant _ROLE_17 = 1 << 17;
uint256 internal constant _ROLE_18 = 1 << 18;
uint256 internal constant _ROLE_19 = 1 << 19;
uint256 internal constant _ROLE_20 = 1 << 20;
uint256 internal constant _ROLE_21 = 1 << 21;
uint256 internal constant _ROLE_22 = 1 << 22;
uint256 internal constant _ROLE_23 = 1 << 23;
uint256 internal constant _ROLE_24 = 1 << 24;
uint256 internal constant _ROLE_25 = 1 << 25;
uint256 internal constant _ROLE_26 = 1 << 26;
uint256 internal constant _ROLE_27 = 1 << 27;
uint256 internal constant _ROLE_28 = 1 << 28;
uint256 internal constant _ROLE_29 = 1 << 29;
uint256 internal constant _ROLE_30 = 1 << 30;
uint256 internal constant _ROLE_31 = 1 << 31;
uint256 internal constant _ROLE_32 = 1 << 32;
uint256 internal constant _ROLE_33 = 1 << 33;
uint256 internal constant _ROLE_34 = 1 << 34;
uint256 internal constant _ROLE_35 = 1 << 35;
uint256 internal constant _ROLE_36 = 1 << 36;
uint256 internal constant _ROLE_37 = 1 << 37;
uint256 internal constant _ROLE_38 = 1 << 38;
uint256 internal constant _ROLE_39 = 1 << 39;
uint256 internal constant _ROLE_40 = 1 << 40;
uint256 internal constant _ROLE_41 = 1 << 41;
uint256 internal constant _ROLE_42 = 1 << 42;
uint256 internal constant _ROLE_43 = 1 << 43;
uint256 internal constant _ROLE_44 = 1 << 44;
uint256 internal constant _ROLE_45 = 1 << 45;
uint256 internal constant _ROLE_46 = 1 << 46;
uint256 internal constant _ROLE_47 = 1 << 47;
uint256 internal constant _ROLE_48 = 1 << 48;
uint256 internal constant _ROLE_49 = 1 << 49;
uint256 internal constant _ROLE_50 = 1 << 50;
uint256 internal constant _ROLE_51 = 1 << 51;
uint256 internal constant _ROLE_52 = 1 << 52;
uint256 internal constant _ROLE_53 = 1 << 53;
uint256 internal constant _ROLE_54 = 1 << 54;
uint256 internal constant _ROLE_55 = 1 << 55;
uint256 internal constant _ROLE_56 = 1 << 56;
uint256 internal constant _ROLE_57 = 1 << 57;
uint256 internal constant _ROLE_58 = 1 << 58;
uint256 internal constant _ROLE_59 = 1 << 59;
uint256 internal constant _ROLE_60 = 1 << 60;
uint256 internal constant _ROLE_61 = 1 << 61;
uint256 internal constant _ROLE_62 = 1 << 62;
uint256 internal constant _ROLE_63 = 1 << 63;
uint256 internal constant _ROLE_64 = 1 << 64;
uint256 internal constant _ROLE_65 = 1 << 65;
uint256 internal constant _ROLE_66 = 1 << 66;
uint256 internal constant _ROLE_67 = 1 << 67;
uint256 internal constant _ROLE_68 = 1 << 68;
uint256 internal constant _ROLE_69 = 1 << 69;
uint256 internal constant _ROLE_70 = 1 << 70;
uint256 internal constant _ROLE_71 = 1 << 71;
uint256 internal constant _ROLE_72 = 1 << 72;
uint256 internal constant _ROLE_73 = 1 << 73;
uint256 internal constant _ROLE_74 = 1 << 74;
uint256 internal constant _ROLE_75 = 1 << 75;
uint256 internal constant _ROLE_76 = 1 << 76;
uint256 internal constant _ROLE_77 = 1 << 77;
uint256 internal constant _ROLE_78 = 1 << 78;
uint256 internal constant _ROLE_79 = 1 << 79;
uint256 internal constant _ROLE_80 = 1 << 80;
uint256 internal constant _ROLE_81 = 1 << 81;
uint256 internal constant _ROLE_82 = 1 << 82;
uint256 internal constant _ROLE_83 = 1 << 83;
uint256 internal constant _ROLE_84 = 1 << 84;
uint256 internal constant _ROLE_85 = 1 << 85;
uint256 internal constant _ROLE_86 = 1 << 86;
uint256 internal constant _ROLE_87 = 1 << 87;
uint256 internal constant _ROLE_88 = 1 << 88;
uint256 internal constant _ROLE_89 = 1 << 89;
uint256 internal constant _ROLE_90 = 1 << 90;
uint256 internal constant _ROLE_91 = 1 << 91;
uint256 internal constant _ROLE_92 = 1 << 92;
uint256 internal constant _ROLE_93 = 1 << 93;
uint256 internal constant _ROLE_94 = 1 << 94;
uint256 internal constant _ROLE_95 = 1 << 95;
uint256 internal constant _ROLE_96 = 1 << 96;
uint256 internal constant _ROLE_97 = 1 << 97;
uint256 internal constant _ROLE_98 = 1 << 98;
uint256 internal constant _ROLE_99 = 1 << 99;
uint256 internal constant _ROLE_100 = 1 << 100;
uint256 internal constant _ROLE_101 = 1 << 101;
uint256 internal constant _ROLE_102 = 1 << 102;
uint256 internal constant _ROLE_103 = 1 << 103;
uint256 internal constant _ROLE_104 = 1 << 104;
uint256 internal constant _ROLE_105 = 1 << 105;
uint256 internal constant _ROLE_106 = 1 << 106;
uint256 internal constant _ROLE_107 = 1 << 107;
uint256 internal constant _ROLE_108 = 1 << 108;
uint256 internal constant _ROLE_109 = 1 << 109;
uint256 internal constant _ROLE_110 = 1 << 110;
uint256 internal constant _ROLE_111 = 1 << 111;
uint256 internal constant _ROLE_112 = 1 << 112;
uint256 internal constant _ROLE_113 = 1 << 113;
uint256 internal constant _ROLE_114 = 1 << 114;
uint256 internal constant _ROLE_115 = 1 << 115;
uint256 internal constant _ROLE_116 = 1 << 116;
uint256 internal constant _ROLE_117 = 1 << 117;
uint256 internal constant _ROLE_118 = 1 << 118;
uint256 internal constant _ROLE_119 = 1 << 119;
uint256 internal constant _ROLE_120 = 1 << 120;
uint256 internal constant _ROLE_121 = 1 << 121;
uint256 internal constant _ROLE_122 = 1 << 122;
uint256 internal constant _ROLE_123 = 1 << 123;
uint256 internal constant _ROLE_124 = 1 << 124;
uint256 internal constant _ROLE_125 = 1 << 125;
uint256 internal constant _ROLE_126 = 1 << 126;
uint256 internal constant _ROLE_127 = 1 << 127;
uint256 internal constant _ROLE_128 = 1 << 128;
uint256 internal constant _ROLE_129 = 1 << 129;
uint256 internal constant _ROLE_130 = 1 << 130;
uint256 internal constant _ROLE_131 = 1 << 131;
uint256 internal constant _ROLE_132 = 1 << 132;
uint256 internal constant _ROLE_133 = 1 << 133;
uint256 internal constant _ROLE_134 = 1 << 134;
uint256 internal constant _ROLE_135 = 1 << 135;
uint256 internal constant _ROLE_136 = 1 << 136;
uint256 internal constant _ROLE_137 = 1 << 137;
uint256 internal constant _ROLE_138 = 1 << 138;
uint256 internal constant _ROLE_139 = 1 << 139;
uint256 internal constant _ROLE_140 = 1 << 140;
uint256 internal constant _ROLE_141 = 1 << 141;
uint256 internal constant _ROLE_142 = 1 << 142;
uint256 internal constant _ROLE_143 = 1 << 143;
uint256 internal constant _ROLE_144 = 1 << 144;
uint256 internal constant _ROLE_145 = 1 << 145;
uint256 internal constant _ROLE_146 = 1 << 146;
uint256 internal constant _ROLE_147 = 1 << 147;
uint256 internal constant _ROLE_148 = 1 << 148;
uint256 internal constant _ROLE_149 = 1 << 149;
uint256 internal constant _ROLE_150 = 1 << 150;
uint256 internal constant _ROLE_151 = 1 << 151;
uint256 internal constant _ROLE_152 = 1 << 152;
uint256 internal constant _ROLE_153 = 1 << 153;
uint256 internal constant _ROLE_154 = 1 << 154;
uint256 internal constant _ROLE_155 = 1 << 155;
uint256 internal constant _ROLE_156 = 1 << 156;
uint256 internal constant _ROLE_157 = 1 << 157;
uint256 internal constant _ROLE_158 = 1 << 158;
uint256 internal constant _ROLE_159 = 1 << 159;
uint256 internal constant _ROLE_160 = 1 << 160;
uint256 internal constant _ROLE_161 = 1 << 161;
uint256 internal constant _ROLE_162 = 1 << 162;
uint256 internal constant _ROLE_163 = 1 << 163;
uint256 internal constant _ROLE_164 = 1 << 164;
uint256 internal constant _ROLE_165 = 1 << 165;
uint256 internal constant _ROLE_166 = 1 << 166;
uint256 internal constant _ROLE_167 = 1 << 167;
uint256 internal constant _ROLE_168 = 1 << 168;
uint256 internal constant _ROLE_169 = 1 << 169;
uint256 internal constant _ROLE_170 = 1 << 170;
uint256 internal constant _ROLE_171 = 1 << 171;
uint256 internal constant _ROLE_172 = 1 << 172;
uint256 internal constant _ROLE_173 = 1 << 173;
uint256 internal constant _ROLE_174 = 1 << 174;
uint256 internal constant _ROLE_175 = 1 << 175;
uint256 internal constant _ROLE_176 = 1 << 176;
uint256 internal constant _ROLE_177 = 1 << 177;
uint256 internal constant _ROLE_178 = 1 << 178;
uint256 internal constant _ROLE_179 = 1 << 179;
uint256 internal constant _ROLE_180 = 1 << 180;
uint256 internal constant _ROLE_181 = 1 << 181;
uint256 internal constant _ROLE_182 = 1 << 182;
uint256 internal constant _ROLE_183 = 1 << 183;
uint256 internal constant _ROLE_184 = 1 << 184;
uint256 internal constant _ROLE_185 = 1 << 185;
uint256 internal constant _ROLE_186 = 1 << 186;
uint256 internal constant _ROLE_187 = 1 << 187;
uint256 internal constant _ROLE_188 = 1 << 188;
uint256 internal constant _ROLE_189 = 1 << 189;
uint256 internal constant _ROLE_190 = 1 << 190;
uint256 internal constant _ROLE_191 = 1 << 191;
uint256 internal constant _ROLE_192 = 1 << 192;
uint256 internal constant _ROLE_193 = 1 << 193;
uint256 internal constant _ROLE_194 = 1 << 194;
uint256 internal constant _ROLE_195 = 1 << 195;
uint256 internal constant _ROLE_196 = 1 << 196;
uint256 internal constant _ROLE_197 = 1 << 197;
uint256 internal constant _ROLE_198 = 1 << 198;
uint256 internal constant _ROLE_199 = 1 << 199;
uint256 internal constant _ROLE_200 = 1 << 200;
uint256 internal constant _ROLE_201 = 1 << 201;
uint256 internal constant _ROLE_202 = 1 << 202;
uint256 internal constant _ROLE_203 = 1 << 203;
uint256 internal constant _ROLE_204 = 1 << 204;
uint256 internal constant _ROLE_205 = 1 << 205;
uint256 internal constant _ROLE_206 = 1 << 206;
uint256 internal constant _ROLE_207 = 1 << 207;
uint256 internal constant _ROLE_208 = 1 << 208;
uint256 internal constant _ROLE_209 = 1 << 209;
uint256 internal constant _ROLE_210 = 1 << 210;
uint256 internal constant _ROLE_211 = 1 << 211;
uint256 internal constant _ROLE_212 = 1 << 212;
uint256 internal constant _ROLE_213 = 1 << 213;
uint256 internal constant _ROLE_214 = 1 << 214;
uint256 internal constant _ROLE_215 = 1 << 215;
uint256 internal constant _ROLE_216 = 1 << 216;
uint256 internal constant _ROLE_217 = 1 << 217;
uint256 internal constant _ROLE_218 = 1 << 218;
uint256 internal constant _ROLE_219 = 1 << 219;
uint256 internal constant _ROLE_220 = 1 << 220;
uint256 internal constant _ROLE_221 = 1 << 221;
uint256 internal constant _ROLE_222 = 1 << 222;
uint256 internal constant _ROLE_223 = 1 << 223;
uint256 internal constant _ROLE_224 = 1 << 224;
uint256 internal constant _ROLE_225 = 1 << 225;
uint256 internal constant _ROLE_226 = 1 << 226;
uint256 internal constant _ROLE_227 = 1 << 227;
uint256 internal constant _ROLE_228 = 1 << 228;
uint256 internal constant _ROLE_229 = 1 << 229;
uint256 internal constant _ROLE_230 = 1 << 230;
uint256 internal constant _ROLE_231 = 1 << 231;
uint256 internal constant _ROLE_232 = 1 << 232;
uint256 internal constant _ROLE_233 = 1 << 233;
uint256 internal constant _ROLE_234 = 1 << 234;
uint256 internal constant _ROLE_235 = 1 << 235;
uint256 internal constant _ROLE_236 = 1 << 236;
uint256 internal constant _ROLE_237 = 1 << 237;
uint256 internal constant _ROLE_238 = 1 << 238;
uint256 internal constant _ROLE_239 = 1 << 239;
uint256 internal constant _ROLE_240 = 1 << 240;
uint256 internal constant _ROLE_241 = 1 << 241;
uint256 internal constant _ROLE_242 = 1 << 242;
uint256 internal constant _ROLE_243 = 1 << 243;
uint256 internal constant _ROLE_244 = 1 << 244;
uint256 internal constant _ROLE_245 = 1 << 245;
uint256 internal constant _ROLE_246 = 1 << 246;
uint256 internal constant _ROLE_247 = 1 << 247;
uint256 internal constant _ROLE_248 = 1 << 248;
uint256 internal constant _ROLE_249 = 1 << 249;
uint256 internal constant _ROLE_250 = 1 << 250;
uint256 internal constant _ROLE_251 = 1 << 251;
uint256 internal constant _ROLE_252 = 1 << 252;
uint256 internal constant _ROLE_253 = 1 << 253;
uint256 internal constant _ROLE_254 = 1 << 254;
uint256 internal constant _ROLE_255 = 1 << 255;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.19;
//Efficient Solidity & assembly version of ReentrancyGuard
abstract contract ReentrancyGuard {
error ReentrantCall();
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private _status = 1;
/**
* @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() {
assembly {
if eq(sload(_status.slot), 2) {
mstore(0x00, 0x37ed32e8) // ReentrantCall() selector
revert(0x1c, 0x04)
}
sstore(_status.slot, 0x02)
}
_;
assembly {
sstore(_status.slot, 0x01)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
/// - For ERC20s, this implementation won't check that a token has code,
/// responsibility is delegated to the caller.
library SafeTransferLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ETH transfer has failed.
error ETHTransferFailed();
/// @dev The ERC20 `transferFrom` has failed.
error TransferFromFailed();
/// @dev The ERC20 `transfer` has failed.
error TransferFailed();
/// @dev The ERC20 `approve` has failed.
error ApproveFailed();
/// @dev The Permit2 operation has failed.
error Permit2Failed();
/// @dev The Permit2 amount must be less than `2**160 - 1`.
error Permit2AmountOverflow();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;
/// @dev Suggested gas stipend for contract receiving ETH to perform a few
/// storage reads and writes, but low enough to prevent griefing.
uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
/// @dev The unique EIP-712 domain domain separator for the DAI token contract.
bytes32 internal constant DAI_DOMAIN_SEPARATOR =
0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;
/// @dev The address for the WETH9 contract on Ethereum mainnet.
address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/// @dev The canonical Permit2 address.
/// [Github](https://github.com/Uniswap/permit2)
/// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ETH OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
//
// The regular variants:
// - Forwards all remaining gas to the target.
// - Reverts if the target reverts.
// - Reverts if the current contract has insufficient balance.
//
// The force variants:
// - Forwards with an optional gas stipend
// (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
// - If the target reverts, or if the gas stipend is exhausted,
// creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
// Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
// - Reverts if the current contract has insufficient balance.
//
// The try variants:
// - Forwards with a mandatory gas stipend.
// - Instead of reverting, returns whether the transfer succeeded.
/// @dev Sends `amount` (in wei) ETH to `to`.
function safeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Sends all the ETH in the current contract to `to`.
function safeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// Transfer all the ETH and check if it succeeded or not.
if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// forgefmt: disable-next-item
if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
function trySafeTransferAllETH(address to, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for
/// the current contract to manage.
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
// Perform the transfer, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
)
) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function trySafeTransferFrom(address token, address from, address to, uint256 amount)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
success :=
and( // The arguments of `and` are evaluated from right to left.
or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
)
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends all of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have their entire balance approved for the current contract to manage.
function safeTransferAllFrom(address token, address from, address to)
internal
returns (uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
)
) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
// Perform the transfer, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
)
) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransfer(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
)
) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sends all of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransferAll(address token, address to) internal returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
mstore(0x20, address()) // Store the address of the current contract.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
)
) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
mstore(0x14, to) // Store the `to` argument.
amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
)
) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// Reverts upon failure.
function safeApprove(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
// Perform the approval, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
)
) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
/// then retries the approval again (some tokens, e.g. USDT, requires this).
/// Reverts upon failure.
function safeApproveWithRetry(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
// Perform the approval, retrying upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
)
) {
mstore(0x34, 0) // Store 0 for the `amount`.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
mstore(0x34, amount) // Store back the original `amount`.
// Retry the approval, reverting upon failure.
if iszero(
and(
or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
)
) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Returns the amount of ERC20 `token` owned by `account`.
/// Returns zero if the `token` does not exist.
function balanceOf(address token, address account) internal view returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
amount :=
mul( // The arguments of `mul` are evaluated from right to left.
mload(0x20),
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
)
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// If the initial attempt fails, try to use Permit2 to transfer the token.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
if (!trySafeTransferFrom(token, from, to, amount)) {
permit2TransferFrom(token, from, to, amount);
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
/// Reverts upon failure.
function permit2TransferFrom(address token, address from, address to, uint256 amount)
internal
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(add(m, 0x74), shr(96, shl(96, token)))
mstore(add(m, 0x54), amount)
mstore(add(m, 0x34), to)
mstore(add(m, 0x20), shl(96, from))
// `transferFrom(address,address,uint160,address)`.
mstore(m, 0x36c78516000000000000000000000000)
let p := PERMIT2
let exists := eq(chainid(), 1)
if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
if iszero(and(call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00), exists)) {
mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
}
}
}
/// @dev Permit a user to spend a given amount of
/// another user's tokens via native EIP-2612 permit if possible, falling
/// back to Permit2 if native permit fails or is not implemented on the token.
function permit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
for {} shl(96, xor(token, WETH9)) {} {
mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
// Gas stipend to limit gas burn for tokens that don't refund gas when
// an non-existing function is called. 5K should be enough for a SLOAD.
staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
)
) { break }
// After here, we can be sure that token is a contract.
let m := mload(0x40)
mstore(add(m, 0x34), spender)
mstore(add(m, 0x20), shl(96, owner))
mstore(add(m, 0x74), deadline)
if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
mstore(0x14, owner)
mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
mstore(add(m, 0x94), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
// `nonces` is already at `add(m, 0x54)`.
// `1` is already stored at `add(m, 0x94)`.
mstore(add(m, 0xb4), and(0xff, v))
mstore(add(m, 0xd4), r)
mstore(add(m, 0xf4), s)
success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
break
}
mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
mstore(add(m, 0x54), amount)
mstore(add(m, 0x94), and(0xff, v))
mstore(add(m, 0xb4), r)
mstore(add(m, 0xd4), s)
success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
break
}
}
if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
}
/// @dev Simple permit on the Permit2 contract.
function simplePermit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0x927da105) // `allowance(address,address,address)`.
{
let addressMask := shr(96, not(0))
mstore(add(m, 0x20), and(addressMask, owner))
mstore(add(m, 0x40), and(addressMask, token))
mstore(add(m, 0x60), and(addressMask, spender))
mstore(add(m, 0xc0), and(addressMask, spender))
}
let p := mul(PERMIT2, iszero(shr(160, amount)))
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
)
) {
mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(p))), 0x04)
}
mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
// `owner` is already `add(m, 0x20)`.
// `token` is already at `add(m, 0x40)`.
mstore(add(m, 0x60), amount)
mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
// `nonce` is already at `add(m, 0xa0)`.
// `spender` is already at `add(m, 0xc0)`.
mstore(add(m, 0xe0), deadline)
mstore(add(m, 0x100), 0x100) // `signature` offset.
mstore(add(m, 0x120), 0x41) // `signature` length.
mstore(add(m, 0x140), r)
mstore(add(m, 0x160), s)
mstore(add(m, 0x180), shl(248, v))
if iszero(call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00)) {
mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
revert(0x1c, 0x04)
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.19;
/// @notice Stores all data from a single strategy
/// @dev Packed in two slots
struct StrategyData {
/// Slot 0
/// @notice Maximum percentage available to be lent to strategies(in BPS)
/// @dev in BPS. uint16 is enough to cover the max BPS value of 10_000
uint16 strategyDebtRatio;
/// @notice The performance fee
/// @dev in BPS. uint16 is enough to cover the max BPS value of 10_000
uint16 strategyPerformanceFee;
/// @notice Timestamp when the strategy was added.
/// @dev Overflowing July 21, 2554
uint48 strategyActivation;
/// @notice block.timestamp of the last time a report occured
/// @dev Overflowing July 21, 2554
uint48 strategyLastReport;
/// @notice Upper limit on the increase of debt since last harvest
/// @dev max debt per harvest to be set to a maximum value of 4,722,366,482,869,645,213,695
uint128 strategyMaxDebtPerHarvest;
/// Slot 1
/// @notice Lower limit on the increase of debt since last harvest
/// @dev min debt per harvest to be set to a maximum value of 16,777,215
uint128 strategyMinDebtPerHarvest;
/// @notice Total returns that Strategy reported to the Vault
/// @dev max strategy total gain of 79,228,162,514,264,337,593,543,950,335
uint128 strategyTotalUnrealizedGain;
/// Slot 2
/// @notice Total outstanding debt that Strategy has
/// @dev max total debt of 79,228,162,514,264,337,593,543,950,335
uint128 strategyTotalDebt;
/// @notice Total losses that Strategy has realized for Vault
/// @dev max strategy total loss of 79,228,162,514,264,337,593,543,950,335
uint128 strategyTotalLoss;
/// Slot 3
/// @notice True if the strategy has switched to autopilot mode
/// @dev it is activated from the strategy and will only work if `autoPilotEnabled` == true
/// @dev the strategy can still be manually harvested in autopilot mode
bool autoPilot;
}
{
"compilationTarget": {
"src/MaxApyVault.sol": "MaxApyVault"
},
"evmVersion": "shanghai",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": [
":@openzeppelin-contracts-5.0.2/=dependencies/@openzeppelin-contracts-5.0.2/",
":forge-std-1.8.2/=dependencies/forge-std-1.8.2/src/",
":forge-std/=dependencies/forge-std-1.8.2/src/",
":openzeppelin/=dependencies/@openzeppelin-contracts-5.0.2/",
":solady-0.0.201/=dependencies/solady-0.0.201/src/",
":solady/=dependencies/solady-0.0.201/src/"
]
}
[{"inputs":[{"internalType":"address","name":"admin","type":"address"},{"internalType":"address","name":"underlyingAsset_","type":"address"},{"internalType":"string","name":"name_","type":"string"},{"internalType":"string","name":"symbol_","type":"string"},{"internalType":"address","name":"_treasury","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AllowanceOverflow","type":"error"},{"inputs":[],"name":"AllowanceUnderflow","type":"error"},{"inputs":[],"name":"AlreadyInitialized","type":"error"},{"inputs":[],"name":"DepositMoreThanMax","type":"error"},{"inputs":[],"name":"FeesAlreadyAssesed","type":"error"},{"inputs":[],"name":"InsufficientAllowance","type":"error"},{"inputs":[],"name":"InsufficientBalance","type":"error"},{"inputs":[],"name":"InvalidDebtRatio","type":"error"},{"inputs":[],"name":"InvalidManagementFee","type":"error"},{"inputs":[],"name":"InvalidMinDebtPerHarvest","type":"error"},{"inputs":[],"name":"InvalidPerformanceFee","type":"error"},{"inputs":[],"name":"InvalidPermit","type":"error"},{"inputs":[],"name":"InvalidQueueOrder","type":"error"},{"inputs":[],"name":"InvalidReportedGainAndDebtPayment","type":"error"},{"inputs":[],"name":"InvalidStrategyUnderlying","type":"error"},{"inputs":[],"name":"InvalidStrategyVault","type":"error"},{"inputs":[],"name":"InvalidZeroAddress","type":"error"},{"inputs":[],"name":"InvalidZeroAmount","type":"error"},{"inputs":[],"name":"InvalidZeroShares","type":"error"},{"inputs":[],"name":"LossGreaterThanStrategyTotalDebt","type":"error"},{"inputs":[],"name":"MintMoreThanMax","type":"error"},{"inputs":[],"name":"NewOwnerIsZeroAddress","type":"error"},{"inputs":[],"name":"NoHandoverRequest","type":"error"},{"inputs":[],"name":"PermitExpired","type":"error"},{"inputs":[],"name":"QueueIsFull","type":"error"},{"inputs":[],"name":"RedeemMoreThanMax","type":"error"},{"inputs":[],"name":"ReentrantCall","type":"error"},{"inputs":[],"name":"StrategyAlreadyActive","type":"error"},{"inputs":[],"name":"StrategyDebtRatioAlreadyZero","type":"error"},{"inputs":[],"name":"StrategyInEmergencyExitMode","type":"error"},{"inputs":[],"name":"StrategyNotActive","type":"error"},{"inputs":[],"name":"TotalSupplyOverflow","type":"error"},{"inputs":[],"name":"Unauthorized","type":"error"},{"inputs":[],"name":"VaultDepositLimitExceeded","type":"error"},{"inputs":[],"name":"VaultInEmergencyShutdownMode","type":"error"},{"inputs":[],"name":"WithdrawMoreThanMax","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"isEnabled","type":"bool"}],"name":"AutopilotEnabled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"by","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newDepositLimit","type":"uint256"}],"name":"DepositLimitUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"emergencyShutdown","type":"bool"}],"name":"EmergencyShutdownUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"managementFee","type":"uint256"},{"indexed":false,"internalType":"uint16","name":"performanceFee","type":"uint16"},{"indexed":false,"internalType":"uint256","name":"strategistFee","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"duration","type":"uint256"}],"name":"FeesReported","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"strategy","type":"address"},{"indexed":false,"internalType":"bytes","name":"reason","type":"bytes"}],"name":"ForceHarvestFailed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newManagementFee","type":"uint256"}],"name":"ManagementFeeUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"pendingOwner","type":"address"}],"name":"OwnershipHandoverCanceled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"pendingOwner","type":"address"}],"name":"OwnershipHandoverRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint16","name":"newPerformanceFee","type":"uint16"}],"name":"PerformanceFeeUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"uint256","name":"roles","type":"uint256"}],"name":"RolesUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"newStrategy","type":"address"},{"indexed":false,"internalType":"uint16","name":"strategyDebtRatio","type":"uint16"},{"indexed":false,"internalType":"uint128","name":"strategyMaxDebtPerHarvest","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"strategyMinDebtPerHarvest","type":"uint128"},{"indexed":false,"internalType":"uint16","name":"strategyPerformanceFee","type":"uint16"}],"name":"StrategyAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"strategy","type":"address"},{"indexed":false,"internalType":"uint256","name":"withdrawn","type":"uint256"}],"name":"StrategyExited","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"strategy","type":"address"}],"name":"StrategyRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"strategy","type":"address"},{"indexed":false,"internalType":"uint256","name":"unrealizedGain","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"loss","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"debtPayment","type":"uint256"},{"indexed":false,"internalType":"uint128","name":"strategyTotalUnrealizedGain","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"strategyTotalLoss","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"strategyTotalDebt","type":"uint128"},{"indexed":false,"internalType":"uint256","name":"credit","type":"uint256"},{"indexed":false,"internalType":"uint16","name":"strategyDebtRatio","type":"uint16"}],"name":"StrategyReported","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"strategy","type":"address"}],"name":"StrategyRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"strategy","type":"address"},{"indexed":false,"internalType":"uint16","name":"newDebtRatio","type":"uint16"},{"indexed":false,"internalType":"uint128","name":"newMaxDebtPerHarvest","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"newMinDebtPerHarvest","type":"uint128"},{"indexed":false,"internalType":"uint16","name":"newPerformanceFee","type":"uint16"}],"name":"StrategyUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"treasury","type":"address"}],"name":"TreasuryUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"by","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"Withdraw","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"strategy","type":"address"},{"indexed":false,"internalType":"uint128","name":"strategyTotalDebt","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"loss","type":"uint128"}],"name":"WithdrawFromStrategy","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address[20]","name":"withdrawalQueue","type":"address[20]"}],"name":"WithdrawalQueueUpdated","type":"event"},{"inputs":[],"name":"ADMIN_ROLE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"AUTOPILOT_HARVEST_INTERVAL","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"result","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"EMERGENCY_ADMIN_ROLE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAXIMUM_STRATEGIES","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_BPS","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SECS_PER_YEAR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"STRATEGY_ROLE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newStrategy","type":"address"},{"internalType":"uint256","name":"strategyDebtRatio","type":"uint256"},{"internalType":"uint256","name":"strategyMaxDebtPerHarvest","type":"uint256"},{"internalType":"uint256","name":"strategyMinDebtPerHarvest","type":"uint256"},{"internalType":"uint256","name":"strategyPerformanceFee","type":"uint256"}],"name":"addStrategy","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"asset","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"autoPilotEnabled","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"cancelOwnershipHandover","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"pendingOwner","type":"address"}],"name":"completeOwnershipHandover","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"convertToAssets","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"convertToShares","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"strategy","type":"address"}],"name":"creditAvailable","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"strategy","type":"address"}],"name":"debtOutstanding","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"debtRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"deposit","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"depositLimit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"emergencyShutdown","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"strategy","type":"address"}],"name":"exitStrategy","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"strategy","type":"address"}],"name":"getStrategyTotalDebt","outputs":[{"internalType":"uint256","name":"strategyTotalDebt","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"roles","type":"uint256"}],"name":"grantRoles","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"roles","type":"uint256"}],"name":"hasAllRoles","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"roles","type":"uint256"}],"name":"hasAnyRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastReport","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"managementFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"maxDeposit","outputs":[{"internalType":"uint256","name":"maxAssets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"maxMint","outputs":[{"internalType":"uint256","name":"maxShares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"maxRedeem","outputs":[{"internalType":"uint256","name":"maxShares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"maxWithdraw","outputs":[{"internalType":"uint256","name":"maxAssets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"mint","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nexHarvestStrategyIndex","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"result","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"pendingOwner","type":"address"}],"name":"ownershipHandoverExpiresAt","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"performanceFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"previewDeposit","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"previewMint","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"previewRedeem","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"previewWithdraw","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"strategy","type":"address"}],"name":"removeStrategy","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"roles","type":"uint256"}],"name":"renounceRoles","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint128","name":"unrealizedGain","type":"uint128"},{"internalType":"uint128","name":"loss","type":"uint128"},{"internalType":"uint128","name":"debtPayment","type":"uint128"},{"internalType":"address","name":"managementFeeReceiver","type":"address"}],"name":"report","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"requestOwnershipHandover","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"roles","type":"uint256"}],"name":"revokeRoles","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"strategy","type":"address"}],"name":"revokeStrategy","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"rolesOf","outputs":[{"internalType":"uint256","name":"roles","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"_autoPilot","type":"bool"}],"name":"setAutoPilot","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"_autoPilotEnabled","type":"bool"}],"name":"setAutopilotEnabled","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_depositLimit","type":"uint256"}],"name":"setDepositLimit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"_emergencyShutdown","type":"bool"}],"name":"setEmergencyShutdown","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_managementFee","type":"uint256"}],"name":"setManagementFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_performanceFee","type":"uint256"}],"name":"setPerformanceFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_treasury","type":"address"}],"name":"setTreasury","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[20]","name":"queue","type":"address[20]"}],"name":"setWithdrawalQueue","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"sharePrice","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"strategies","outputs":[{"internalType":"uint16","name":"strategyDebtRatio","type":"uint16"},{"internalType":"uint16","name":"strategyPerformanceFee","type":"uint16"},{"internalType":"uint48","name":"strategyActivation","type":"uint48"},{"internalType":"uint48","name":"strategyLastReport","type":"uint48"},{"internalType":"uint128","name":"strategyMaxDebtPerHarvest","type":"uint128"},{"internalType":"uint128","name":"strategyMinDebtPerHarvest","type":"uint128"},{"internalType":"uint128","name":"strategyTotalUnrealizedGain","type":"uint128"},{"internalType":"uint128","name":"strategyTotalDebt","type":"uint128"},{"internalType":"uint128","name":"strategyTotalLoss","type":"uint128"},{"internalType":"bool","name":"autoPilot","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalDebt","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalDeposits","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalIdle","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"treasury","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"strategy","type":"address"},{"internalType":"uint256","name":"newDebtRatio","type":"uint256"},{"internalType":"uint256","name":"newMaxDebtPerHarvest","type":"uint256"},{"internalType":"uint256","name":"newMinDebtPerHarvest","type":"uint256"},{"internalType":"uint256","name":"newPerformanceFee","type":"uint256"}],"name":"updateStrategyData","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"withdrawalQueue","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"}]