// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
mapping(bytes32 role => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
return _roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
if (!hasRole(role, account)) {
_roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
if (hasRole(role, account)) {
_roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
________ ______________________
__ ___/___ ____________________________ ___________ __ \__ |_ __ \
_____ \_ / / /__ __ \_ ___/ _ \_ __ `__ \ _ \_ / / /_ /| | / / /
____/ // /_/ /__ /_/ / / / __/ / / / / / __/ /_/ /_ ___ / /_/ /
/____/ \__,_/ _ .___//_/ \___//_/ /_/ /_/\___//_____/ /_/ |_\____/
/_/
*/
pragma solidity 0.8.20;
import "../interfaces/IAuraBooster.sol";
import "../interfaces/IBasicRewards.sol";
import "./Constants.sol";
/// @title Aura Utility Functions
/// @author SupremeDAO
/// @notice Provides utility functions for interacting with Aura Finance contracts.
/// @dev This abstract contract includes functions for depositing, withdrawing, and unstaking in Aura Finance.
abstract contract AuraUtils is Constants {
/// @notice The Pool ID for Aura Finance.
uint256 public constant AURA_PID = 107;
/// @notice Address of the Aura Booster contract for deposit operations.
IAuraBooster public constant AURA_BOOSTER = IAuraBooster(0xA57b8d98dAE62B26Ec3bcC4a365338157060B234);
/// @notice Address of the Aura Vault for staking operations.
IBasicRewards public constant AURA_VAULT = IBasicRewards(0xe39570EF26fB9A562bf26F8c708b7433F65050af);
/// @notice Determines the token to be staked.
/// @dev Should be overridden to return the specific token to stake in Aura.
/// @return The IERC20 token to be staked.
function _tokenToStake() internal view virtual returns (IERC20);
/// @notice Deposits all available tokens into the Aura Booster.
/// @dev Approves and then deposits all tokens held by this contract into Aura using the depositAll method.
function _depositAllAura() internal {
// Approve the Aura Booster to spend the token
if (!_tokenToStake().approve(address(AURA_BOOSTER), _tokenToStake().balanceOf(address(this)))) {
revert ERC20_ApprovalFailed();
}
// Deposit all tokens to Aura
if (!AURA_BOOSTER.depositAll(AURA_PID, true)) {
revert ERC20_ApprovalFailed();
}
}
/// @notice Unstakes and withdraws a specific amount of tokens from the Aura Vault.
/// @dev Unstakes and withdraws a specified amount of tokens from Aura, including accrued rewards.
/// @param amount The amount of tokens to unstake and withdraw.
function _unstakeAndWithdrawAura(uint256 amount) internal {
// Unstake specified amount and withdraw from Aura Vault
AURA_VAULT.withdrawAndUnwrap(amount, true);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
________ ______________________
__ ___/___ ____________________________ ___________ __ \__ |_ __ \
_____ \_ / / /__ __ \_ ___/ _ \_ __ `__ \ _ \_ / / /_ /| | / / /
____/ // /_/ /__ /_/ / / / __/ / / / / / __/ /_/ /_ ___ / /_/ /
/____/ \__,_/ _ .___//_/ \___//_/ /_/ /_/\___//_____/ /_/ |_\____/
/_/
*/
pragma solidity 0.8.20;
import "../interfaces/IBalancerVault.sol";
import "../interfaces/IPool.sol";
import "./Constants.sol";
abstract contract BalancerUtils is Constants {
// address of balancer vault
// fix: balancer vault is fixed across chains, we can set it as immutable
IBalancerVault public constant BAL_VAULT = IBalancerVault(0xBA12222222228d8Ba445958a75a0704d566BF2C8);
bytes32 public constant POOL_BAL_WETH_ID = 0x5c6ee304399dbdb9c8ef030ab642b10820db8f56000200000000000000000014;
bytes32 public constant POOL_AURA_WETH_ID = 0xcfca23ca9ca720b6e98e3eb9b6aa0ffc4a5c08b9000200000000000000000274;
bytes32 public constant POOL_WSTETH_WETH_ID = 0x93d199263632a4ef4bb438f1feb99e57b4b5f0bd0000000000000000000005c2;
uint256 public constant FIXED_LIMIT = 1;
bytes public constant EMPTY_USER_DATA = "";
// Fixed control amount for BPT
uint256 public constant QUERY_CONTROL_AMOUNT = 10 ether;
// Fixed USDC Control Amount
uint256 public constant USDC_CONTROL_AMOUNT = 10e6;
// Pool tokens
IERC20 public immutable token0;
IERC20 public immutable token1;
// pool of D2D/USDC
bytes32 public immutable POOL_ID;
constructor(bytes32 _poolId) {
POOL_ID = _poolId;
(IERC20[] memory tokens,,) = BAL_VAULT.getPoolTokens(POOL_ID);
token0 = tokens[0];
token1 = tokens[1];
}
/// @notice Join balancer pool
/// @dev Single side join with usdc
/// @param usdcAmount the amount of usdc to deposit
/// @param d2dAmount the amount of d2d to deposit
/// @param minBptAmountOut the minimal amount of bpt to receive
function _joinPool(uint256 usdcAmount, uint256 d2dAmount, uint256 minBptAmountOut) internal {
(IERC20[] memory tokens,,) = BAL_VAULT.getPoolTokens(POOL_ID);
uint256[] memory maxAmountsIn = new uint256[](tokens.length);
// Set the amounts for D2D and USDC according to their positions in the pool
maxAmountsIn[0] = d2dAmount; // D2D token amount
maxAmountsIn[1] = usdcAmount; // USDC token amount
// Approve the Balancer Vault to withdraw the respective tokens
if(!IERC20(tokens[0]).approve(address(BAL_VAULT), d2dAmount)){
revert ERC20_ApprovalFailed();
}
if(!IERC20(tokens[1]).approve(address(BAL_VAULT), usdcAmount)){
revert ERC20_ApprovalFailed();
}
uint256 joinKind = uint256(IBalancerVault.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT);
bytes memory userData = abi.encode(joinKind, maxAmountsIn, minBptAmountOut);
IBalancerVault.JoinPoolRequest memory request = IBalancerVault.JoinPoolRequest({
assets: _convertERC20sToAssets(tokens),
maxAmountsIn: maxAmountsIn,
userData: userData,
fromInternalBalance: false
});
BAL_VAULT.joinPool(POOL_ID, address(this), address(this), request);
}
function _exitPool(uint256 bptAmountIn, uint256 exitTokenIndex, uint256 minAmountOut) internal {
(IERC20[] memory tokens,,) = BAL_VAULT.getPoolTokens(POOL_ID);
uint256[] memory minAmountsOut = new uint256[](tokens.length);
minAmountsOut[exitTokenIndex] = minAmountOut;
// Define the exit kind
uint256 exitKind = uint256(IBalancerVault.ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT);
bytes memory userData = abi.encode(exitKind, bptAmountIn, exitTokenIndex);
IBalancerVault.ExitPoolRequest memory request = IBalancerVault.ExitPoolRequest({
assets: _convertERC20sToAssets(tokens),
minAmountsOut: minAmountsOut,
userData: userData,
toInternalBalance: false
});
BAL_VAULT.exitPool(POOL_ID, address(this), payable(address(this)), request);
}
/// @notice Simulates an `exitRequest`
/// @dev Used to provide a baseline amountOut for subsequent transactions
/// @dev Note NEVER use the value obtained in this transaction as the only `minAmountOut`
/// @param bptAmountIn The amount of BTP tokens to send
/// @return bptIn Amount of BPT used in query
/// @return amountsOut Array of amounts out
function _simulateExitPool(uint256 bptAmountIn) internal returns (uint256 bptIn, uint256[] memory amountsOut) {
(IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock) = BAL_VAULT.getPoolTokens(POOL_ID);
// Construct the userData
// [enum Kind][bptAmountIn][exitTokenIndex]
bytes memory userData = abi.encode(uint256(0), uint256(bptAmountIn), uint256(1));
// The address is the first 160 b_exitPoolits of our target pool
// Note this may not always be the case!
// We shift the id 64 bits to the right and cast it to address
address pool = address(uint160(uint256(POOL_ID >> 96)));
uint256 swapFeePercentage = IPool(pool).getSwapFeePercentage();
// Query the pool directly, this call reverts if called through interface
bytes memory calldataToSim = abi.encodeWithSelector(
IPool.queryExit.selector,
POOL_ID,
AURA,
address(this),
balances,
lastChangeBlock,
swapFeePercentage,
userData
);
// This call "fails" but returns the required
(bool success, bytes memory data) = pool.call(calldataToSim);
(bptIn, amountsOut) = abi.decode(data, (uint256, uint256[]));
}
function _simulateJoinPool(uint256 usdcAmountIn) internal returns (uint256 bptOut, uint256[] memory amountsIn) {
(, uint256[] memory balances, uint256 lastChangeBlock) = BAL_VAULT.getPoolTokens(POOL_ID);
// Construct the userData
// [enum Kind][bptAmountIn][bptExpected]
uint256[] memory tokensAmounts = new uint256[](2);
tokensAmounts[1] = usdcAmountIn;
bytes memory userData = abi.encode(uint256(1), tokensAmounts, uint256(1));
// The address is the first 160 bits of our target pool
// Note this may not always be the case!
// We shift the id 64 bits to the right and cast it to address
address pool = address(uint160(uint256(POOL_ID >> 96)));
uint256 swapFeePercentage = IPool(pool).getSwapFeePercentage();
// Query the pool directly, this call reverts if called through interface
bytes memory calldataToSim = abi.encodeWithSelector(
IPool.queryJoin.selector,
POOL_ID,
AURA,
address(this),
balances,
lastChangeBlock,
swapFeePercentage,
userData
);
// Not checking success as this is not supposed to return true
(bool success, bytes memory data) = pool.call(calldataToSim);
(bptOut, amountsIn) = abi.decode(data, (uint256, uint256[]));
}
function _swapRewardBal(uint256 balAmount, uint256, uint256 deadline) internal {
IERC20(BAL).approve(address(BAL_VAULT), balAmount);
IBalancerVault.SingleSwap memory singleSwap = IBalancerVault.SingleSwap({
poolId: POOL_BAL_WETH_ID,
kind: IBalancerVault.SwapKind.GIVEN_IN,
assetIn: IAsset(BAL),
assetOut: IAsset(WETH),
amount: balAmount,
userData: EMPTY_USER_DATA
});
IBalancerVault.FundManagement memory funds = IBalancerVault.FundManagement({
sender: address(this),
fromInternalBalance: false,
recipient: payable(address(this)),
toInternalBalance: false
});
BAL_VAULT.swap(singleSwap, funds, FIXED_LIMIT, deadline);
}
function _swapRewardAura(uint256 auraAmount, uint256, uint256 deadline) internal {
IERC20(AURA).approve(address(BAL_VAULT), auraAmount);
IBalancerVault.SingleSwap memory singleSwap = IBalancerVault.SingleSwap({
poolId: POOL_AURA_WETH_ID,
kind: IBalancerVault.SwapKind.GIVEN_IN,
assetIn: IAsset(AURA),
assetOut: IAsset(WETH),
amount: auraAmount,
userData: EMPTY_USER_DATA
});
IBalancerVault.FundManagement memory funds = IBalancerVault.FundManagement({
sender: address(this),
fromInternalBalance: false,
recipient: payable(address(this)),
toInternalBalance: false
});
BAL_VAULT.swap(singleSwap, funds, FIXED_LIMIT, deadline);
}
function _swapRewardToWstEth(uint256 minWethAmount, uint256 deadline) internal {
IERC20(WETH).approve(address(BAL_VAULT), minWethAmount);
IBalancerVault.SingleSwap memory singleSwap = IBalancerVault.SingleSwap({
poolId: POOL_WSTETH_WETH_ID,
kind: IBalancerVault.SwapKind.GIVEN_IN,
assetIn: IAsset(WETH),
assetOut: IAsset(address(wstETH)),
amount: minWethAmount,
userData: EMPTY_USER_DATA
});
IBalancerVault.FundManagement memory funds = IBalancerVault.FundManagement({
sender: address(this),
fromInternalBalance: false,
recipient: payable(address(this)),
toInternalBalance: false
});
BAL_VAULT.swap(singleSwap, funds, FIXED_LIMIT, deadline);
}
/// @dev This helper function is a fast and cheap way to convert between IERC20[] and IAsset[] types
function _convertERC20sToAssets(IERC20[] memory tokens) internal pure returns (IAsset[] memory assets) {
// solhint-disable-next-line no-inline-assembly
assembly {
assets := tokens
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
________ ______________________
__ ___/___ ____________________________ ___________ __ \__ |_ __ \
_____ \_ / / /__ __ \_ ___/ _ \_ __ `__ \ _ \_ / / /_ /| | / / /
____/ // /_/ /__ /_/ / / / __/ / / / / / __/ /_/ /_ ___ / /_/ /
/____/ \__,_/ _ .___//_/ \___//_/ /_/ /_/\___//_____/ /_/ |_\____/
/_/
*/
pragma solidity 0.8.20;
import "../interfaces/IcrvUSD.sol";
import {IPPAgentV2JobOwner} from "../interfaces/IPPAgentV2JobOwner.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title Token Addresses, Interfaces and Errors
/// @author SupremeDAO
/// @notice Provides constant addresses and interfaces for various tokens used in the contracts.
/// @dev This abstract contract defines addresses and interfaces for tokens like BAL, AURA, WETH, and others.
abstract contract Constants {
/// @notice The address of the BAL token.
address public constant BAL = 0xba100000625a3754423978a60c9317c58a424e3D;
/// @notice The address of the AURA token.
address public constant AURA = 0xC0c293ce456fF0ED870ADd98a0828Dd4d2903DBF;
/// @notice The address of the WETH token.
address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/// @notice The ERC20 interface for wstETH token.
IERC20 public constant wstETH = IERC20(0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0);
/// @notice The ERC20 interface for USDC token.
IERC20 public constant USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
/// @notice The ERC20 interface for D2D token.
IERC20 public constant D2D = IERC20(0x43D4A3cd90ddD2F8f4f693170C9c8098163502ad);
/// @notice The ERC20 interface for D2D/USDC Balancer Pool Token (BPT).
IERC20 public constant D2D_USDC_BPT = IERC20(0x27C9f71cC31464B906E0006d4FcBC8900F48f15f);
/// @notice The crvUSD token interface.
IcrvUSD public constant crvUSD = IcrvUSD(0xf939E0A03FB07F59A73314E73794Be0E57ac1b4E);
// @notice The PowerAgent contract.
IPPAgentV2JobOwner public constant AgentContract = IPPAgentV2JobOwner(0xc9ce4CdA5897707546F3904C0FfCC6e429bC4546);
/// @dev Raised when an unknown executer attempts an action.
error UnknownExecuter();
/// @dev Raised when cancellation of a deposit is not allowed.
error DepositCancellationNotAllowed();
/// @dev Raised when ERC20 token transfer fails.
error AURA_DepositFailed();
/// @dev Raised when ERC20 token transferFrom fails.
error ERC20_TransferFromFailed();
/// @dev Raised when ERC20 token transfer fails.
error ERC20_TransferFailed();
// @dev Raised when approval execution is failed
error ERC20_ApprovalFailed();
/// @dev Raised when a zero deposit is attempted.
error ZeroDepositNotAllowed();
/// @dev Raised when a zero investment is attempted.
error ZeroInvestmentNotAllowed();
/// @dev Raised when an overloaded redeem function is incorrectly used.
error UseOverLoadedRedeemFunction();
// Cannot queue and execute in same block
error InvalidUnwind();
// Cannot queue and execuite in same block
error InvalidInvest();
/// @dev Raised when the percentage is larger than 100%
error InvalidInput();
/// @dev Raised when the fee percentage is larger than 70%
error InvalidFee();
/// @dev Raised when the amount of investments > maxInvestments amount
error InvestmentsOverflow();
/// @dev Job is called from Power Agent was created not by a caller
error InvalidJobOwner();
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
________ ______________________
__ ___/___ ____________________________ ___________ __ \__ |_ __ \
_____ \_ / / /__ __ \_ ___/ _ \_ __ `__ \ _ \_ / / /_ /| | / / /
____/ // /_/ /__ /_/ / / / __/ / / / / / __/ /_/ /_ ___ / /_/ /
/____/ \__,_/ _ .___//_/ \___//_/ /_/ /_/\___//_____/ /_/ |_\____/
/_/
*/
pragma solidity 0.8.20;
import "../interfaces/IcrvUSD.sol";
import "../interfaces/IcrvUSDController.sol";
import "../interfaces/IcrvUSDUSDCPool.sol";
import "./Constants.sol";
/// @title Curve Utility Functions
/// @author SupremeDAO
/// @notice Provides utility functions for interacting with Curve Finance contracts.
/// @dev This abstract contract includes functions for depositing, borrowing, repaying, and exchanging assets on Curve.
abstract contract CurveUtils is Constants {
/// @notice The controller contract for crvUSD loans.
IcrvUSDController public constant crvUSDController = IcrvUSDController(0x100dAa78fC509Db39Ef7D04DE0c1ABD299f4C6CE);
/// @notice The Curve pool for crvUSD and USDC exchange.
IcrvUSDUSDCPool public constant crvUSDUSDCPool = IcrvUSDUSDCPool(0x4DEcE678ceceb27446b35C672dC7d61F30bAD69E);
/// @notice Total amount of wstETH deposited.
uint256 public totalWsthethDeposited;
/// @notice Number of bands for the crvusd/wstETH soft liquidation range.
uint256 public N;
/// @notice Creates a loan position using wstETH as collateral.
/// @dev Used only for the initial creation of a loan position.
/// @param _wstETHAmount The amount of wstETH to be deposited as collateral.
/// @param _debtAmount The amount of crvUSD to be borrowed.
function _depositAndCreateLoan(uint256 _wstETHAmount, uint256 _debtAmount) internal {
if (_wstETHAmount == 0) {
revert ZeroDepositNotAllowed();
}
// Approve the crvUSDController to handle wstETH
if (!wstETH.approve(address(crvUSDController), _wstETHAmount)) {
revert ERC20_ApprovalFailed();
}
// Call create_loan on the controller
crvUSDController.create_loan(_wstETHAmount, _debtAmount, N);
// Update the total wstETH deposited after creating the loan
totalWsthethDeposited += _wstETHAmount;
}
/// @notice Removes the collateral from the controller
/// @param withdrawalAmount The amount of wstETH to withdraw
function _removeCollateral(uint256 withdrawalAmount) internal {
crvUSDController.remove_collateral(withdrawalAmount, false);
totalWsthethDeposited -= withdrawalAmount;
}
/// @notice Borrows additional crvUSD against the collateral.
/// @param _wstETHAmount The amount of wstETH deposited as collateral for the additional borrowing.
/// @param _debtAmount The amount of crvUSD to borrow.
function _borrowMore(uint256 _wstETHAmount, uint256 _debtAmount) internal {
// Approve the crvUSDController to handle additional wstETH
if (!wstETH.approve(address(crvUSDController), _wstETHAmount)) {
revert ERC20_ApprovalFailed();
}
// Borrow more crvUSD against the additional wstETH collateral
crvUSDController.borrow_more(_wstETHAmount, _debtAmount);
totalWsthethDeposited += _wstETHAmount;
}
/// @notice Repays a specified amount of the crvUSD loan.
/// @param debtToRepay The amount of crvUSD to repay.
function _repayCRVUSDLoan(uint256 debtToRepay) internal {
// Approve the crvUSDController to handle additional wstETH
if (!crvUSD.approve(address(crvUSDController), debtToRepay)) {
revert ERC20_ApprovalFailed();
}
// Repay the specified amount of crvUSD loan
crvUSDController.repay(debtToRepay);
}
/// @notice Exchanges crvUSD to USDC through the Curve pool.
/// @param _dx The amount of crvUSD to exchange.
function _exchangeCRVUSDtoUSDC(uint256 _dx) internal {
if (!crvUSD.approve(address(crvUSDUSDCPool), _dx)) {
revert ERC20_ApprovalFailed();
}
// Calculate the expected USDC amount and perform the exchange
uint256 expected = crvUSDUSDCPool.get_dy(1, 0, _dx) * 99 / 100;
crvUSDUSDCPool.exchange(1, 0, _dx, expected, address(this));
}
/// @notice Exchanges USDC to crvUSD through the Curve pool.
/// @param _dx The amount of USDC to exchange.
function _exchangeUSDCTocrvUSD(uint256 _dx) internal {
if (!USDC.approve(address(crvUSDUSDCPool), _dx)) {
revert ERC20_ApprovalFailed();
}
// Calculate the expected crvUSD amount and perform the exchange
uint256 expected = crvUSDUSDCPool.get_dy(0, 1, _dx) * 99 / 100;
crvUSDUSDCPool.exchange(0, 1, _dx, expected, address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
* ```
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC4626.sol)
pragma solidity ^0.8.20;
import {IERC20, IERC20Metadata, ERC20} from "../ERC20.sol";
import {SafeERC20} from "../utils/SafeERC20.sol";
import {IERC4626} from "../../../interfaces/IERC4626.sol";
import {Math} from "../../../utils/math/Math.sol";
/**
* @dev Implementation of the ERC4626 "Tokenized Vault Standard" as defined in
* https://eips.ethereum.org/EIPS/eip-4626[EIP-4626].
*
* This extension allows the minting and burning of "shares" (represented using the ERC20 inheritance) in exchange for
* underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends
* the ERC20 standard. Any additional extensions included along it would affect the "shares" token represented by this
* contract and not the "assets" token which is an independent contract.
*
* [CAUTION]
* ====
* In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning
* with a "donation" to the vault that inflates the price of a share. This is variously known as a donation or inflation
* attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial
* deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may
* similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by
* verifying the amount received is as expected, using a wrapper that performs these checks such as
* https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].
*
* Since v4.9, this implementation uses virtual assets and shares to mitigate that risk. The `_decimalsOffset()`
* corresponds to an offset in the decimal representation between the underlying asset's decimals and the vault
* decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which itself
* determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default offset
* (0) makes it non-profitable, as a result of the value being captured by the virtual shares (out of the attacker's
* donation) matching the attacker's expected gains. With a larger offset, the attack becomes orders of magnitude more
* expensive than it is profitable. More details about the underlying math can be found
* xref:erc4626.adoc#inflation-attack[here].
*
* The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued
* to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets
* will cause the first user to exit to experience reduced losses in detriment to the last users that will experience
* bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the
* `_convertToShares` and `_convertToAssets` functions.
*
* To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].
* ====
*/
abstract contract ERC4626 is ERC20, IERC4626 {
using Math for uint256;
IERC20 private immutable _asset;
uint8 private immutable _underlyingDecimals;
/**
* @dev Attempted to deposit more assets than the max amount for `receiver`.
*/
error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);
/**
* @dev Attempted to mint more shares than the max amount for `receiver`.
*/
error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);
/**
* @dev Attempted to withdraw more assets than the max amount for `receiver`.
*/
error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);
/**
* @dev Attempted to redeem more shares than the max amount for `receiver`.
*/
error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);
/**
* @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).
*/
constructor(IERC20 asset_) {
(bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);
_underlyingDecimals = success ? assetDecimals : 18;
_asset = asset_;
}
/**
* @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.
*/
function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool, uint8) {
(bool success, bytes memory encodedDecimals) = address(asset_).staticcall(
abi.encodeCall(IERC20Metadata.decimals, ())
);
if (success && encodedDecimals.length >= 32) {
uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));
if (returnedDecimals <= type(uint8).max) {
return (true, uint8(returnedDecimals));
}
}
return (false, 0);
}
/**
* @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This
* "original" value is cached during construction of the vault contract. If this read operation fails (e.g., the
* asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.
*
* See {IERC20Metadata-decimals}.
*/
function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) {
return _underlyingDecimals + _decimalsOffset();
}
/** @dev See {IERC4626-asset}. */
function asset() public view virtual returns (address) {
return address(_asset);
}
/** @dev See {IERC4626-totalAssets}. */
function totalAssets() public view virtual returns (uint256) {
return _asset.balanceOf(address(this));
}
/** @dev See {IERC4626-convertToShares}. */
function convertToShares(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Floor);
}
/** @dev See {IERC4626-convertToAssets}. */
function convertToAssets(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Floor);
}
/** @dev See {IERC4626-maxDeposit}. */
function maxDeposit(address) public view virtual returns (uint256) {
return type(uint256).max;
}
/** @dev See {IERC4626-maxMint}. */
function maxMint(address) public view virtual returns (uint256) {
return type(uint256).max;
}
/** @dev See {IERC4626-maxWithdraw}. */
function maxWithdraw(address owner) public view virtual returns (uint256) {
return _convertToAssets(balanceOf(owner), Math.Rounding.Floor);
}
/** @dev See {IERC4626-maxRedeem}. */
function maxRedeem(address owner) public view virtual returns (uint256) {
return balanceOf(owner);
}
/** @dev See {IERC4626-previewDeposit}. */
function previewDeposit(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Floor);
}
/** @dev See {IERC4626-previewMint}. */
function previewMint(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Ceil);
}
/** @dev See {IERC4626-previewWithdraw}. */
function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Ceil);
}
/** @dev See {IERC4626-previewRedeem}. */
function previewRedeem(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Floor);
}
/** @dev See {IERC4626-deposit}. */
function deposit(uint256 assets, address receiver) public virtual returns (uint256) {
uint256 maxAssets = maxDeposit(receiver);
if (assets > maxAssets) {
revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);
}
uint256 shares = previewDeposit(assets);
_deposit(_msgSender(), receiver, assets, shares);
return shares;
}
/** @dev See {IERC4626-mint}.
*
* As opposed to {deposit}, minting is allowed even if the vault is in a state where the price of a share is zero.
* In this case, the shares will be minted without requiring any assets to be deposited.
*/
function mint(uint256 shares, address receiver) public virtual returns (uint256) {
uint256 maxShares = maxMint(receiver);
if (shares > maxShares) {
revert ERC4626ExceededMaxMint(receiver, shares, maxShares);
}
uint256 assets = previewMint(shares);
_deposit(_msgSender(), receiver, assets, shares);
return assets;
}
/** @dev See {IERC4626-withdraw}. */
function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {
uint256 maxAssets = maxWithdraw(owner);
if (assets > maxAssets) {
revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);
}
uint256 shares = previewWithdraw(assets);
_withdraw(_msgSender(), receiver, owner, assets, shares);
return shares;
}
/** @dev See {IERC4626-redeem}. */
function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {
uint256 maxShares = maxRedeem(owner);
if (shares > maxShares) {
revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
}
uint256 assets = previewRedeem(shares);
_withdraw(_msgSender(), receiver, owner, assets, shares);
return assets;
}
/**
* @dev Internal conversion function (from assets to shares) with support for rounding direction.
*/
function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {
return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);
}
/**
* @dev Internal conversion function (from shares to assets) with support for rounding direction.
*/
function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {
return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);
}
/**
* @dev Deposit/mint common workflow.
*/
function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {
// If _asset is ERC777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the
// `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
// calls the vault, which is assumed not malicious.
//
// Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
// assets are transferred and before the shares are minted, which is a valid state.
// slither-disable-next-line reentrancy-no-eth
SafeERC20.safeTransferFrom(_asset, caller, address(this), assets);
_mint(receiver, shares);
emit Deposit(caller, receiver, assets, shares);
}
/**
* @dev Withdraw/redeem common workflow.
*/
function _withdraw(
address caller,
address receiver,
address owner,
uint256 assets,
uint256 shares
) internal virtual {
if (caller != owner) {
_spendAllowance(owner, caller, shares);
}
// If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
// `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
// calls the vault, which is assumed not malicious.
//
// Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
// shares are burned and after the assets are transferred, which is a valid state.
_burn(owner, shares);
SafeERC20.safeTransfer(_asset, receiver, assets);
emit Withdraw(caller, receiver, owner, assets, shares);
}
function _decimalsOffset() internal view virtual returns (uint8) {
return 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity >=0.7.0 <0.9.0;
/**
* @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero
* address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like
* types.
*
* This concept is unrelated to a Pool's Asset Managers.
*/
interface IAsset {
// solhint-disable-previous-line no-empty-blocks
}
// transaction example: https://etherscan.io/tx/0xb2d6067dfbde2eda99ae62b79d734b2943a78a06cba67ea63f48266b9a5f5138
// contract: https://etherscan.io/address/0xa57b8d98dae62b26ec3bcc4a365338157060b234
pragma solidity ^0.8.0;
interface IAuraBooster {
function deposit(uint256 _pid, uint256 _amount, bool _stake) external returns (bool);
function depositAll(uint256 _pid, bool _stake) external returns (bool);
function withdraw(uint256 _pid, uint256 _amount) external returns (bool);
function withdrawAll(uint256 _pid) external returns (bool);
function withdrawTo(uint256 _pid, uint256 _amount, address _to) external returns (bool);
}
// https://etherscan.io/address/0xba12222222228d8ba445958a75a0704d566bf2c8
// transaction example https://etherscan.io/tx/0x73bc32ab29651251c09215d9227e7abcc11bf8b120c82e7f3eda3ee08f80a592
pragma solidity ^0.8.0;
import "./IAsset.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IBalancerVault {
enum JoinKind {
INIT,
EXACT_TOKENS_IN_FOR_BPT_OUT,
TOKEN_IN_FOR_EXACT_BPT_OUT,
ALL_TOKENS_IN_FOR_EXACT_BPT_OUT
}
enum ExitKind {
EXACT_BPT_IN_FOR_ONE_TOKEN_OUT,
EXACT_BPT_IN_FOR_TOKENS_OUT,
BPT_IN_FOR_EXACT_TOKENS_OUT,
MANAGEMENT_FEE_TOKENS_OUT // for InvestmentPool
}
enum SwapKind {
GIVEN_IN,
GIVEN_OUT
}
/**
* @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on
* the `kind` value.
*
* `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).
* Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct SingleSwap {
bytes32 poolId;
SwapKind kind;
IAsset assetIn;
IAsset assetOut;
uint256 amount;
bytes userData;
}
/**
* @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the
* `recipient` account.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20
* transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`
* must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of
* `joinPool`.
*
* If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of
* transferred. This matches the behavior of `exitPool`.
*
* Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a
* revert.
*/
struct FundManagement {
address sender;
bool fromInternalBalance;
address payable recipient;
bool toInternalBalance;
}
function swap(SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline)
external
payable
returns (uint256);
/* @dev copied from the IVault.sol -\0_0/-
/**
* @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will
* trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized
* Pool shares.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount
* to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces
* these maximums.
*
* If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable
* this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the
* WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent
* back to the caller (not the sender, which is important for relayers).
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be
* sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final
* `assets` array might not be sorted. Pools with no registered tokens cannot be joined.
*
* If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only
* be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be
* withdrawn from Internal Balance: attempting to do so will trigger a revert.
*
* This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed
* directly to the Pool's contract, as is `recipient`.
*
* Emits a `PoolBalanceChanged` event.
*/
function joinPool(bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request)
external
payable;
struct JoinPoolRequest {
IAsset[] assets;
uint256[] maxAmountsIn;
bytes userData;
bool fromInternalBalance;
}
/**
* @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will
* trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized
* Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see
* `getPoolTokenInfo`).
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum
* token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault:
* it just enforces these minimums.
*
* If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To
* enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead
* of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit.
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must
* be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the
* final `assets` array might not be sorted. Pools with no registered tokens cannot be exited.
*
* If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise,
* an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to
* do so will trigger a revert.
*
* `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the
* `tokens` array. This array must match the Pool's registered tokens.
*
* This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and
* passed directly to the Pool's contract.
*
* Emits a `PoolBalanceChanged` event.
*/
function exitPool(bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request)
external;
struct ExitPoolRequest {
IAsset[] assets;
uint256[] minAmountsOut;
bytes userData;
bool toInternalBalance;
}
/**
* @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of
* the tokens' `balances` changed.
*
* The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all
* Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order.
*
* If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same
* order as passed to `registerTokens`.
*
* Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are
* the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo`
* instead.
*/
function getPoolTokens(bytes32 poolId)
external
view
returns (IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock);
/**
* @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the
* Vault with the same arguments, along with the number of tokens `recipient` would receive.
*
* This function is not meant to be called directly, but rather from a helper contract that fetches current Vault
* data, such as the protocol swap fee percentage and Pool balances.
*
* Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must
* explicitly use eth_call instead of eth_sendTransaction.
*/
function queryExit(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256 bptIn, uint256[] memory amountsOut);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IBasicRewards {
function stakeFor(address, uint256) external returns (bool);
function balanceOf(address) external view returns (uint256);
function totalSupply() external view returns (uint256);
function earned(address) external view returns (uint256);
function withdrawAll(bool) external returns (bool);
function withdraw(uint256, bool) external returns (bool);
function withdraw(address, uint256) external;
function withdrawAndUnwrap(uint256 amount, bool claim) external returns (bool);
function withdrawAllAndUnwrap(bool claim) external;
function getReward() external returns (bool);
function stake(uint256) external returns (bool);
function stake(address, uint256) external;
function extraRewards(uint256) external view returns (address);
function exit() external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4626.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*/
interface IERC4626 is IERC20, IERC20Metadata {
event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed sender,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/**
* @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
*
* - MUST be an ERC-20 token contract.
* - MUST NOT revert.
*/
function asset() external view returns (address assetTokenAddress);
/**
* @dev Returns the total amount of the underlying asset that is “managed” by Vault.
*
* - SHOULD include any compounding that occurs from yield.
* - MUST be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT revert.
*/
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToShares(uint256 assets) external view returns (uint256 shares);
/**
* @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
* through a deposit call.
*
* - MUST return a limited value if receiver is subject to some deposit limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
* - MUST NOT revert.
*/
function maxDeposit(address receiver) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
* call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
* in the same transaction.
* - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
* deposit would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewDeposit(uint256 assets) external view returns (uint256 shares);
/**
* @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* deposit execution, and are accounted for during deposit.
* - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
* - MUST return a limited value if receiver is subject to some mint limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
* - MUST NOT revert.
*/
function maxMint(address receiver) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
* in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
* same transaction.
* - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
* would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by minting.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
* execution, and are accounted for during mint.
* - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
* Vault, through a withdraw call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
* call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
* called
* in the same transaction.
* - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
* the withdrawal would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* withdraw execution, and are accounted for during withdraw.
* - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
* through a redeem call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxRedeem(address owner) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
* in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
* same transaction.
* - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
* redemption would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by redeeming.
*/
function previewRedeem(uint256 shares) external view returns (uint256 assets);
/**
* @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* redeem execution, and are accounted for during redeem.
* - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
interface IPPAgentV2JobOwner {
struct RegisterJobParams {
address jobAddress;
bytes4 jobSelector;
bool useJobOwnerCredits;
bool assertResolverSelector;
uint16 maxBaseFeeGwei;
uint16 rewardPct;
uint32 fixedReward;
uint256 jobMinCvp;
uint8 calldataSource;
uint24 intervalSeconds;
}
struct Job {
uint8 config;
bytes4 selector;
uint88 credits;
uint16 maxBaseFeeGwei;
uint16 rewardPct;
uint32 fixedReward;
uint8 calldataSource;
// For interval jobs
uint24 intervalSeconds;
uint32 lastExecutionAt;
}
struct Resolver {
address resolverAddress;
bytes resolverCalldata;
}
function registerJob(
RegisterJobParams calldata params_,
Resolver calldata resolver_,
bytes calldata preDefinedCalldata_
) external payable returns (bytes32 jobKey, uint256 jobId);
function getJobKey(
address jobAddress_,
uint256 jobId_
) external pure returns (bytes32 jobKey);
function getJobRaw(bytes32 jobKey_) external view returns (uint256 rawJob);
function jobNextKeeperId(bytes32 jobKey_) external view returns (uint256);
function getKeeper(
uint256 keeperId_
)
external
view
returns (
address admin,
address worker,
bool isActive,
uint256 currentStake,
uint256 slashedStake,
uint256 compensation,
uint256 pendingWithdrawalAmount,
uint256 pendingWithdrawalEndAt
);
function getJob(
bytes32 jobKey_
)
external
view
returns (
address owner,
address pendingTransfer,
uint256 jobLevelMinKeeperCvp,
Job memory details,
bytes memory preDefinedCalldata,
Resolver memory resolver
);
}
// Interface for Pool Queries
// These are taken adapted from Balancer Pool interfaces
pragma solidity ^0.8.0;
interface IPool {
function getSwapFeePercentage() external returns (uint256);
/**
* @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the
* Vault with the same arguments, along with the number of tokens `recipient` would receive.
*
* This function is not meant to be called directly, but rather from a helper contract that fetches current Vault
* data, such as the protocol swap fee percentage and Pool balances.
*
* Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must
* explicitly use eth_call instead of eth_sendTransaction.
*/
function queryExit(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256 bptIn, uint256[] memory amountsOut);
/**
* @dev Returns the amount of BPT that would be granted to `recipient` if the `onJoinPool` hook were called by the
* Vault with the same arguments, along with the number of tokens `sender` would have to supply.
*
* This function is not meant to be called directly, but rather from a helper contract that fetches current Vault
* data, such as the protocol swap fee percentage and Pool balances.
*
* Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must
* explicitly use eth_call instead of eth_sendTransaction.
*/
function queryJoin(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256 bptOut, uint256[] memory amountsIn);
}
// https://etherscan.io/address/0x95ecdc6caaf7e4805fcef2679a92338351d24297#code
pragma solidity ^0.8.0;
// ChatGPT generated interface
interface IcrvUSD {
// ERC1271 interface
function isValidSignature(bytes32 _hash, bytes calldata _signature) external view returns (bytes4);
// Functions from the provided Vyper code
function decimals() external view returns (uint8);
function version() external view returns (string memory);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function salt() external view returns (bytes32);
function allowance(address owner, address spender) external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function totalSupply() external view returns (uint256);
function nonces(address owner) external view returns (uint256);
function minter() external view returns (address);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
function transfer(address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function permit(
address _owner,
address _spender,
uint256 _value,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external returns (bool);
function increaseAllowance(address _spender, uint256 _add_value) external returns (bool);
function decreaseAllowance(address _spender, uint256 _sub_value) external returns (bool);
function burnFrom(address _from, uint256 _value) external returns (bool);
function burn(uint256 _value) external returns (bool);
function mint(address _to, uint256 _value) external returns (bool);
function set_minter(address _minter) external;
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// https://etherscan.io/address/0x100daa78fc509db39ef7d04de0c1abd299f4c6ce#code
pragma solidity ^0.8.0;
// ChatGPT generated interface
interface IcrvUSDController {
function debt(address user) external view returns (uint256);
function loan_exists(address user) external view returns (bool);
function total_debt() external view returns (uint256);
function max_borrowable(uint256 collateral, uint256 N) external view returns (uint256);
function min_collateral(uint256 debt, uint256 N) external view returns (uint256);
function calculate_debt_n1(uint256 collateral, uint256 debt, uint256 N) external view returns (int256);
function create_loan(uint256 collateral, uint256 debt, uint256 N) external payable;
function create_loan_extended(
uint256 collateral,
uint256 debt,
uint256 N,
address callbacker,
uint256[5] calldata callback_args
) external payable;
function add_collateral(uint256 collateral, address _for) external payable;
function remove_collateral(uint256 collateral, bool use_eth) external;
function borrow_more(uint256 collateral, uint256 debt) external payable;
function repay(uint256 _d_debt) external payable;
function health(address user, bool full) external view returns (int256);
function amm_price() external view returns (uint256);
function user_prices(address user) external view returns (uint256[2] memory);
function user_state(address user) external view returns (uint256[4] memory);
}
// https://etherscan.io/address/0x4dece678ceceb27446b35c672dc7d61f30bad69e
pragma solidity ^0.8.0;
// ChatGPT generated
interface IcrvUSDUSDCPool {
// Corresponds to the `get_dy` function in the Vyper contract
function get_dy(int128 i, int128 j, uint256 dx) external view returns (uint256);
// Corresponds to the `get_dx` function in the Vyper contract
function get_dx(int128 i, int128 j, uint256 dy) external view returns (uint256);
// Corresponds to the `exchange` function in the Vyper contract
function exchange(int128 i, int128 j, uint256 _dx, uint256 _min_dy, address _receiver) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
________ ______________________
__ ___/___ ____________________________ ___________ __ \__ |_ __ \
_____ \_ / / /__ __ \_ ___/ _ \_ __ `__ \ _ \_ / / /_ /| | / / /
____/ // /_/ /__ /_/ / / / __/ / / / / / __/ /_/ /_ ___ / /_/ /
/____/ \__,_/ _ .___//_/ \___//_/ /_/ /_/\___//_____/ /_/ |_\____/
/_/
*/
pragma solidity 0.8.20;
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {ERC4626, Math} from "@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {BalancerUtils} from "./periphery/BalancerUtils.sol";
import {AuraUtils} from "./periphery/AuraUtils.sol";
import {CurveUtils} from "./periphery/CurveUtils.sol";
import {LeverageStrategyStorage} from "./LeverageStrategyStorage.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
/// @title Leverage Strategy Contract
/// @notice This contract is the core of a leverage strategy involving borrowing tokens,
/// creating a CDP (Collateralized Debt Position), and using the borrowed assets to invest
/// and stake in the Aura pool to generate yield.
/// @dev The contract rebalances upon PowerAgent interaction
contract LeverageStrategy is
ERC4626,
ReentrancyGuard,
BalancerUtils,
AuraUtils,
CurveUtils,
AccessControl,
LeverageStrategyStorage
{
using Math for uint256;
// Events
// Add relevant events to log important contract actions/events
/// @notice Constructs the LeverageStrategy contract and initializes key components
/// @dev Grants the deployer the default admin role and initializes the contract with
/// Balancer pool ID, sets up ERC20 metadata, and establishes the base asset for ERC4626
/// @param _poolId The unique identifier of the Balancer pool used in the strategy
constructor(bytes32 _poolId)
BalancerUtils(_poolId)
ERC20("Supreme Aura D2D-USDC vault", "sAura-D2D-USD")
ERC4626(IERC20(address(AURA_VAULT)))
{
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
//================================================EXTERNAL FUNCTIONS===============================================//
/// @notice Initializes the contract with specific parameters and roles after deployment and makes it ready for investing
/// @dev Can only be called by an account with the DEFAULT_ADMIN_ROLE
/// This function sets key contract parameters and assigns roles to specified addresses.
/// It should be called immediately after contract deployment.
/// @param _N A numeric parameter used in the contract's logic (its specific role should be described)
/// @param _controller The address to be granted the CONTROLLER_ROLE (DAO)
/// @param _keeper The address (agent) to be granted the KEEPER_ROLE
/// @param _jobOwner The address that calls poweragent execution
function initialize(
uint256 _N,
address _controller,
address _keeper,
address _jobOwner
)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
//set the treasury address
controller = _controller;
//set the number of price bands to deposit into
N = _N;
//grant the controller role to the given address
_grantRole(CONTROLLER_ROLE, _controller);
//grant the keeper role to the given address (poweragent address)
_grantRole(KEEPER_ROLE, _keeper);
//grant the job owner role to the given address (it creates jobs in poweragent)
_grantRole(JOB_OWNER_ROLE, _jobOwner);
}
/// @notice Checks that the jov is called by job owner address
/// @dev Only PowerAgent job created by job owner can execute function
modifier onlyOwnerJob() {
bytes32 jobKey = _getJobKey();
(address jobOwner, , , , , ) = AgentContract.getJob(
jobKey
);
if (!hasRole(JOB_OWNER_ROLE, jobOwner)) revert InvalidJobOwner();
_;
}
/// @notice Sets the fee for rewards, determining the profit that gets withdrawn to the DAO
/// @param _fee the new value of the fee
function setFee(uint256 _fee) external onlyRole(CONTROLLER_ROLE){
if (_fee > MAX_DAO_FEE) {
revert InvalidFee();
}
fee = _fee;
}
/// @notice Upgrades the address for the poweragent job owner of the contract
/// @param _jobOwner the new caller's address
function setJobOwner(address _oldJobOwner, address _jobOwner) external onlyRole(CONTROLLER_ROLE){
revokeRole(JOB_OWNER_ROLE, _oldJobOwner);
grantRole(JOB_OWNER_ROLE, _jobOwner);
}
/// @notice Sets the maximal amount of funds that can be deposited into LeverageStrategy
/// @param _maxInvestment the new limit for the deposits
function setMaxInvestment(uint256 _maxInvestment) public onlyRole(CONTROLLER_ROLE){
if(_maxInvestment < currentDeposits){
maxInvestment = currentDeposits;
} else {
maxInvestment = _maxInvestment;
}
}
/// @notice Returns the health of the strategy's Collateralized Debt Position (CDP) on Curve Finance
/// @dev This function fetches the health metric from the Curve Finance controller
/// It provides an assessment of the current state of the CDP associated with this contract.
/// @return The health of the CDP as an integer value
function strategyHealth() public view returns (int256) {
//return the health of the strategy's CDP on Curve Finance
return crvUSDController.health(address(this), false);
}
/// @notice Cancel a deposit before the amount is invested by keeper or controller
/// depositor and sender are both same and can be used interchangebly.
/// @dev deletes a DepositRecord and returns the tokens back to sender
/// @param _key the key/id of the deposit record
function cancelDeposit(uint256 _key) external nonReentrant {
// get the deposit record for the key
DepositRecord memory deposit = deposits[_key];
// ensure that the funds deposited are still not used or already cancelled
if (deposit.state != DepositState.DEPOSITED || deposit.depositor == address(0)) {
revert DepositCancellationNotAllowed();
}
// ensure that the msg.sender is either the sender or receiver of the deposit
if (deposit.depositor != msg.sender && deposit.receiver != msg.sender) {
revert UnknownExecuter();
}
// remove the deposit record
delete deposits[_key];
// send relevant wstETH back to the depositor
_pushwstEth(deposit.depositor, deposit.amount);
emit DepositCancelled(_key);
}
/// @notice Redeems a specified amount of shares for the underlying asset, closes CDP and sends wstETH to the receiver
/// @dev This function handles the redemption process with checks for maximum redeemable shares and minimum amount out.
/// It reverts if the shares to be redeemed exceed the maximum allowed for the owner.
/// It also ensures that the actual amount of assets withdrawn is not less than a specified minimum.
/// @param shares The number of shares to be redeemed
/// @param receiver The address that will receive the wstETH assets
/// @param owner The address that owns the shares being redeemed
/// @param minAmountOut The minimum amount of USDC assets to receive from the exiting the Balancer pool
/// @return The amount of assets that were redeemed
function redeemWstEth(
uint256 shares,
address receiver,
address owner,
uint256 minAmountOut
)
public
nonReentrant
returns (uint256)
{
uint256 maxShares = maxRedeem(owner);
if (shares > maxShares) {
revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
}
currentDeposits -= currentDeposits * shares / this.totalSupply();
uint256 assets = previewRedeem(shares);
_withdraw(msg.sender, receiver, owner, assets, shares, minAmountOut);
return assets;
}
/// @notice Deposit and invest without waiting for keeper to execute it
/// @notice Vault shares are minted to receiver in this same operation
/// @dev When a user calls this function, their deposit isn't added to deposit record as the deposit is used immediately
/// @param assets amount of wstETH to be deposited
/// @param receiver receiver of the vault shares after the wstETH is utilized
/// @param _bptAmountOut amount of BPT token expected out once liquidity is provided
function depositAndInvest(
uint256 assets,
address receiver,
uint256 _bptAmountOut
)
public
nonReentrant
{
if (assets == 0) {
revert ZeroDepositNotAllowed();
}
if (currentDeposits + assets > maxInvestment) {
revert InvestmentsOverflow();
}
currentDeposits += assets;
uint256 _debtAmount = crvUSDController.max_borrowable(assets, N) * healthBuffer / HUNDRED_PERCENT;
// calculate shares
uint256 currentTotalShares = totalSupply();
// pull funds from the msg.sender
_pullwstEth(msg.sender, assets);
uint256 beforeBalance = AURA_VAULT.balanceOf(address(this));
// invest
_invest(assets, _debtAmount, _bptAmountOut);
// mint shares to the msg.sender
uint256 afterbalance = IERC20(address(AURA_VAULT)).balanceOf(address(this));
uint256 vsAssets = afterbalance - beforeBalance;
_mintShares(vsAssets, currentTotalShares, beforeBalance, receiver);
}
/// @notice Invests in the strategy by creating CDP using wstETH, investing in balancer pool
/// and staking BPT tokens on aura to generate yield
/// @dev This function is non-reentrant and can only be called by an account with the CONTROLLER_ROLE
/// It computes the total wstETH to be invested by aggregating deposit records and calculates the maximum borrowable amount.
/// The function then invests wstETH, and tracks the new Aura vault shares minted as a result.
/// Shares of the vault are minted proportionally to the contribution of each deposit record.
/// @param _bptAmountOut The targeted amount of Balancer Pool Tokens (BPT) to be received from the investment
function invest(uint256 _bptAmountOut)
external
nonReentrant
onlyRole(CONTROLLER_ROLE)
{
// calculate total wstETH by traversing through all the deposit records
(uint256 wstEthAmount, uint256 startKeyId,) = _computeAndRebalanceDepositRecords();
uint256 _debtAmount = crvUSDController.max_borrowable(wstEthAmount, N) * healthBuffer / HUNDRED_PERCENT;
uint256 currentShares = totalSupply();
// get the current balance of the Aura vault shares
// to be used to determine how many new vault shares were minted
uint256 beforeBalance = AURA_VAULT.balanceOf(address(this));
// invest
_invest(wstEthAmount, _debtAmount, _bptAmountOut);
// calculate total new shares minted
// here assets is Aura Vault shares
uint256 addedAssets = AURA_VAULT.balanceOf(address(this)) - beforeBalance;
// we mint vault shares propotional to deposits made by receivers of each deposit record that was used
_mintMultipleShares(startKeyId, currentShares, beforeBalance, addedAssets, wstEthAmount);
}
/// @notice This function is called by PowerPool and queues an invest call
/// @dev To provide a measure of manipulation mitigation this call takes a "snapshot"
/// of a control amount of asset, this will be compared in the next call.
/// This MUST be paired with a protected endpoint AND randomness with regards
/// to the subsequent `executeInvestFromKeeper` call timing
/// This function is non-reentrant and can only be called by an account with the KEEPER_ROLE
/// It computes the total wstETH to be invested by aggregating deposit records and calculates the maximum borrowable amount.
/// The function then invests wstETH, and tracks the new Aura vault shares minted as a result.
/// Shares of the vault are minted equally to the contributors of each deposit record
function investFromKeeper() external nonReentrant onlyRole(KEEPER_ROLE) onlyOwnerJob(){
// Queue an invest from Keeper Call
investQueued.timestamp = uint64(block.timestamp);
// We store a simulated amount out as a control value
(uint256 amountOut, ) = _simulateJoinPool(USDC_CONTROL_AMOUNT);
investQueued.minAmountOut = uint192(amountOut);
}
/// @notice Executes a queued invest from a Keeper
/// @dev Invest from keeper executes the call prepared in the previous transaction. Its goal is to execute investment
/// of bunch of deposits.
/// @param _bptAmountOut The minimum aount of BPT Tokens expected out
function executeInvestFromKeeper(uint256 _bptAmountOut, bool isReinvest) external nonReentrant onlyRole(KEEPER_ROLE) onlyOwnerJob(){
// Do not allow queue and execute in same block
if (investQueued.timestamp == block.timestamp || investQueued.timestamp == 0) revert InvalidInvest();
(uint256 expectedAmountOut, ) = _simulateJoinPool(USDC_CONTROL_AMOUNT);
// 1% slippage
if (
investQueued.minAmountOut > (uint192(expectedAmountOut) * 99 / 100) &&
(investQueued.minAmountOut != expectedAmountOut)
) {
// Slippage control out of date, reset so a new call to `investFromKeeper` can happen
investQueued.timestamp = 0;
}
if (isReinvest) {
uint256[4] memory debtBefore = crvUSDController.user_state(address(this));
uint256 maxBorrowable = crvUSDController.max_borrowable(debtBefore[0], N);
// We borrow without adding collateral
// The max amount given our current collateral - the amount we already have taken
_invest(0, maxBorrowable - debtBefore[2], expectedAmountOut);
} else {
// calculate total wstETH by traversing through all the deposit records
(uint256 wstEthAmount, uint256 startKeyId,) = _computeAndRebalanceDepositRecords();
uint256 currentTotalShares = totalSupply();
// get the current balance of the Aura vault shares
// to be used to determine how many new vault shares were minted
uint256 beforeBalance = AURA_VAULT.balanceOf(address(this));
// Here the keeper is borrowing only 95% of the max borrowable amount
uint256 maxBorrowable = crvUSDController.max_borrowable(wstEthAmount * healthBuffer / HUNDRED_PERCENT, N); //Should the keeper always borrow max or some %
_invest(wstEthAmount, maxBorrowable, _bptAmountOut);
// calculate total new shares minted
// here assets is Aura Vault shares
uint256 addedAssets = AURA_VAULT.balanceOf(address(this)) - beforeBalance;
// we equally mint vault shares to the receivers of each deposit record that was used
_mintMultipleShares(startKeyId, currentTotalShares, beforeBalance, addedAssets, wstEthAmount);
}
}
/// @notice Unwind call from the Controller
/// @dev Used by the Controller/DAO to manually unwind a specific percentage
/// @param auraShares The number of asset to unwind
/// @param minAmountOut Slippage protection (w.r.t. BPTToken)
function unwindPosition(uint256 auraShares, uint256 minAmountOut) external nonReentrant onlyRole(CONTROLLER_ROLE) {
_unwindPosition(auraShares, HUNDRED_PERCENT, minAmountOut);
}
/// @notice Queues an unwind call from the automated keeper
/// @dev First part of the two-step unwind process
function unwindPositionFromKeeper() external nonReentrant onlyRole(KEEPER_ROLE) onlyOwnerJob(){
(,uint256[] memory minAmountsOut) = _simulateExitPool(QUERY_CONTROL_AMOUNT);
// Grab the exit token index
unwindQueued.minAmountOut = uint192(minAmountsOut[1]);
unwindQueued.timestamp = uint64(block.timestamp);
}
/// @notice Executes a queued unwindFromKeeper
/// @dev Can only be called by Keeper
function executeUnwindFromKeeper() external onlyRole(KEEPER_ROLE) onlyOwnerJob(){
// Cannot queue and execute in same block!
if (unwindQueued.timestamp == uint64(block.timestamp)) revert InvalidUnwind();
// Timestamp is cleared after unwind
if (unwindQueued.timestamp != 0) {
// Get current quote
(,uint256[] memory amountsOut) = _simulateExitPool(QUERY_CONTROL_AMOUNT);
// If the new minAmountOut is 1% smaller than the stored amount out then there is too much slippage
// Note Always use a protected endpoint to submit transactions!
// Hardcoded slippage
if (
// If the quote amounts are the same, slippage hasn't changed
unwindQueued.minAmountOut == (uint192(amountsOut[1])) ||
// If the 99% of current quote is better than old quote, slippage is acceptable
unwindQueued.minAmountOut < (uint192(amountsOut[1]) * 99 / 100)
) {
_unwindPosition(
_convertToValue(AURA_VAULT.balanceOf(address(this)), unwindPercentage),
unwindPercentage,
0
);
// We need to set timestamp to 0 so next call can happen
unwindQueued.timestamp = 0;
} else {
// Slippage is too much
revert InvalidUnwind();
}
} else {
// No unwind if timestamp is `0`
revert InvalidUnwind();
}
}
/// @notice Sets the health buffer.
/// @dev This ensures that the protocol maintains a healthy colalteral factor
/// @param percentage Must be smaller than 10e12
function setHealthBuffer(uint256 percentage) external {
if (percentage > HUNDRED_PERCENT) revert InvalidInput();
healthBuffer = percentage;
}
/// @notice Swaps BAL and AURA rewards for WstETH, specifying minimum amounts and deadline
/// @dev This function is non-reentrant and can only be called by an account with the CONTROLLER_ROLE
/// It internally calls separate functions to handle the swapping of BAL to WETH and AURA to WETH.
/// Afterwards it calls a function to swap WETH to WstEth.
/// The swaps are executed with specified minimum return amounts and a deadline to ensure slippage protection and timely execution.
/// @param minWethAmountBal The minimum amount of WETH expected from swapping BALCONTROLLER
/// @param minWethAmountAura The minimum amount of WETH expected from swapping AURA
/// @param deadline The latest timestamp by which the swap must be completed
function swapRewardFromKeeper(
uint256 minWethAmountBal,
uint256 minWethAmountAura,
uint256 deadline
) external nonReentrant onlyRole(KEEPER_ROLE) {
uint256 balAmount = IERC20(BAL).balanceOf(address(this));
uint256 auraAmount = IERC20(AURA).balanceOf(address(this));
// Preparing fee transfer to the DAO
uint256 balFees = balAmount * fee / HUNDRED_PERCENT;
uint256 auraFees = auraAmount * fee / HUNDRED_PERCENT;
// And reward transfer to reinvest(it will be possible to withdraw it for the investors)
uint256 balReward = balAmount - balFees;
uint256 auraReward = auraAmount - auraFees;
// Transfers of the fees to the DAO
IERC20(BAL).transfer(controller, balFees);
IERC20(AURA).transfer(controller, balFees);
// swaps tokens to WETH
_swapRewardBal(balReward, minWethAmountBal, deadline);
_swapRewardAura(auraReward, minWethAmountAura, deadline);
uint256 wstEthBefore = wstETH.balanceOf(address(this));
// swaps WETH to wstETH
_swapRewardToWstEth(IERC20(WETH).balanceOf(address(this)), deadline);
uint256 wstEthAmount = wstETH.balanceOf(address(this)) - wstEthBefore;
(uint256 amountOut, ) = _simulateJoinPool(USDC_CONTROL_AMOUNT);
uint256 maxBorrowable = crvUSDController.max_borrowable(wstEthAmount * healthBuffer / HUNDRED_PERCENT, N);
_invest(wstEthAmount, maxBorrowable, amountOut);
}
/// @notice Allows the controller to adjust the percentage to unwind at a time
/// @param newPercentage The percentage of assets to unwind at a time, normalized to 1e12
/// @param newPercentage The percentage of assets to unwind at a time, normalized to 1e12
function setUnwindPercentage(uint256 newPercentage) external onlyRole(CONTROLLER_ROLE) {
if (newPercentage > HUNDRED_PERCENT) revert InvalidInput();
unwindPercentage = newPercentage;
}
//================================================INTERNAL FUNCTIONS===============================================//
/// @notice job key is received from the incomming transaction
/// @dev This call is needed to get the PowerAgent job owner's address
/// implemented according to https://github.com/Partituraio/PPAgentSafeModule/blob/dev/contracts/PPSafeAgent.sol
function _getJobKey() private pure returns (bytes32 jobKey) {
assembly {
jobKey := calldataload(sub(calldatasize(), 32))
}
}
/// @notice reverts everytime to ensure no one can use redeem and withdraw functions
/// @dev The normal `_withdraw` does not allow user to specify slippage protection
/// Given that we are swapping this is a good idea.
function _withdraw(
address,
address,
address,
uint256,
uint256
)
internal
override
nonReentrant
{
// just to ensure no one uses another withdraw function
revert UseOverLoadedRedeemFunction();
}
/// @notice Withdraw funds by burning vault shares
/// @dev Unwinds from AURA -> BPT -> CURVE -> sends wstETH to user
/// @param caller The caller of this function call
/// @param receiver The receiver of the wstETH. Receiver requires allowance.
/// @param owner The user whose shares are to be burned
/// @param assets The number of assets
/// @param shares The number of shares to be withdrawn
function _withdraw(
address caller,
address receiver,
address owner,
uint256 assets,
uint256 shares,
uint256 minAmountOut
) internal {
if (caller != owner) {
_spendAllowance(owner, caller, shares);
}
// calculate percentage of shares to be withdrawn
// i.e. the percentage of all the assets that this user has claim to
uint256 percentageToBeWithdrawn = _convertToPercentage(shares, totalSupply());
// assets location 1 - wstETH in contract - deposits waiting to invest
// assets location 2 - wstETH as extra collateral (collateral not utilised to create CDP)
// assets location 3 - wstETH used to borrow
// funds from assets location 2 and 3 can be withdrawn using unwind and withdraw wstETH
// This withdraws the proportion of assets
// 1) Withdraw BPT from Boosted AURA
// 2) Withdraw USDC from balancer pool (requires slippage protection)
// 3) Swap USDC for curveUSD
// 4) Repay borrow and receive wstETH
uint256 auraBalance = AURA_VAULT.balanceOf(address(this));
if(auraBalance > 0) {
_unwindPosition(auraBalance, percentageToBeWithdrawn, minAmountOut);
}
// We get the total collateral freed up
uint256[4] memory userState = crvUSDController.user_state(address(this));
/*
There is nuance here. The yield is expected to go up. But the health buffer means that there is
some part of the assets that's not utilised.
So we assume that the amount of collateral that the user has claim to is equal to his percentage * collateral provided
This collateral amount is increased when `swapReward` is called AND the Keeper or controller has reinvested the `wstETH`
obtained from the rewards.
Thus, we can simply take the `percentageToBeWithdrawn` and multiply it by the total collateral provided,
to find the amount of `totalWithdrawableWstEth
*/
uint256 totalWithdrawableWstETH = userState[0] * percentageToBeWithdrawn / HUNDRED_PERCENT;
// Now we check if there are any funds in the contract, which were withdrawn to the leverage strategy
uint256 stratBalance = wstETH.balanceOf(address(this));
uint256 additionalSum = 0;
// If there are some additional funds in the strategy, they should be also withdrawn
if (stratBalance > deposited) {
additionalSum = (stratBalance - deposited) * percentageToBeWithdrawn / HUNDRED_PERCENT;
}
// We remove this amount of collateral from the CurveController
_removeCollateral(totalWithdrawableWstETH);
// Now we burn the user's shares
_burn(owner, shares);
// Now we push the withdrawn wstETH to the user
_pushwstEth(receiver, totalWithdrawableWstETH + additionalSum);
emit Withdraw(caller, receiver, owner, assets, shares);
}
/// @notice Internally handles the unwinding of a position by redeeming and converting assets
/// @dev This function is internal and part of the unwinding logic used by public facing functions.
/// It involves multiple steps: unstaking Aura shares, exiting a Balancer pool, and repaying loans.
/// The function calculates the amount of Aura shares to unstake based on a percentage,
/// exchanges the redeemed assets, and then repays any outstanding loans.
/// @param _auraShares The total amount of Aura shares involved in the unwind
/// @param percentageUnwind The percentage of the position to unwind, scaled by 10^12
/// @param minAmountOut The minimum amount of underlying assets expected to receive from the unwinding
function _unwindPosition(
uint256 _auraShares,
uint256 percentageUnwind,
uint256 minAmountOut
) internal {
// Get the proportional amount of shares
uint256 auraSharesToUnStake = _convertToValue(_auraShares, percentageUnwind);
// Withdraw in order to get BPT tokens back
_unstakeAndWithdrawAura(auraSharesToUnStake);
uint256 bptAmount = _tokenToStake().balanceOf(address(this));
uint256 beforeUsdcBalance = USDC.balanceOf(address(this));
// Exit the balancer pool to receive USDC
_exitPool(bptAmount, 1, minAmountOut);
// Get current curveUSD balance
uint256 beforeCrvUSDBalance = crvUSD.balanceOf(address(this));
// Swap USDC to crvUSD
_exchangeUSDCTocrvUSD(USDC.balanceOf(address(this)) - beforeUsdcBalance);
// Repay the loan, there should now be excess collateral
_repayCRVUSDLoan(crvUSD.balanceOf(address(this)) - beforeCrvUSDBalance);
}
/// @notice Calculates the percentage representation of a value with respect to a total amount
/// @dev This function is internal and pure, used for computing the percentage of a part relative to a whole.
/// The calculation scales the percentage by a factor of 10^12 (HUNDRED_PERCENT).
/// @param value The value to be converted into a percentage
/// @param total The total amount relative to which the percentage is calculated
/// @return percent The percentage of the value with respect to the total, scaled by 10^12
function _convertToPercentage(uint256 value, uint256 total) internal pure returns (uint256 percent) {
return value * HUNDRED_PERCENT / total;
}
/// @notice Calculates the absolute value corresponding to a given percentage of a total amount
/// @dev This internal and pure function computes the value that a specified percentage represents of a total.
/// The calculation uses the HUNDRED_PERCENT constant (scaled by 10^12) to handle percentage scaling.
/// @param total The total amount from which the value is derived
/// @param percent The percentage of the total amount to be calculated, scaled by 10^12
/// @return value The calculated value that the percentage represents of the total amount
function _convertToValue(uint256 total, uint256 percent) internal pure returns (uint256 value) {
return total * percent / HUNDRED_PERCENT;
}
/// @notice the token to be staked in the strategy
/// @dev This internal view function returns the specific token that is used for staking in the strategy.
/// It overrides a base class implementation and is meant to be customizable in derived contracts.
/// @return The IERC20 token which is to be staked, represented here by the D2D_USDC_BPT token
function _tokenToStake() internal view override returns (IERC20) {
return D2D_USDC_BPT;
}
/// @notice Handles the internal investment process using wstETH, debt amount, and targeted BPT amount
/// @dev This internal function manages the investment workflow including creating or managing loans,
/// exchanging assets, providing liquidity, and staking LP tokens.
/// It opens a position on crvUSD if no loan exists or manages an existing one, exchanges crvUSD to USDC,
/// and uses the USDC to provide liquidity in the D2D/USDC pool on Balancer, finally staking the LP tokens on Aura Finance.
/// Reverts if the investment amount (_wstETHAmount) is zero.
/// @param _wstETHAmount The amount of wstETH to be used in the investment
/// @param _debtAmount The amount of debt to be taken on in the investment
/// @param _bptAmountOut The targeted amount of Balancer Pool Tokens to be received from the liquidity provision
function _invest(
uint256 _wstETHAmount,
uint256 _debtAmount,
uint256 _bptAmountOut
) internal {
// Opens a position on crvUSD if no loan already
// Note this address is an owner of a crvUSD CDP
// in the usual case we already have a CDP
// But there also should be a case when we create a new one
if (!crvUSDController.loan_exists(address(this))) {
_depositAndCreateLoan(_wstETHAmount, _debtAmount);
} else {
_borrowMore(_wstETHAmount, _debtAmount);
}
_exchangeCRVUSDtoUSDC(_debtAmount);
// Provide liquidity to the D2D/USDC Pool on Balancer
_joinPool(USDC.balanceOf(address(this)), D2D.balanceOf(address(this)), _bptAmountOut);
// Stake LP tokens on Aura Finance
_depositAllAura();
}
/// @notice mint vault shares to an address
/// @dev if total supply is zero, 1:1 ratio is used
/// @param assets amount of assets that was deposited, here assets is the Aura Vault Shares
/// @param to receiver of the vault shares (Leverage Stratgey Vault Shares)
function _mintShares(
uint256 assets,
uint256 currentShares,
uint256 currentAssets,
address to
) internal {
uint256 shares;
// won't cause DoS or gridlock because the token token will have no minted tokens before the creation
if (totalSupply() == 0) {
shares = assets; // 1:1 ratio when supply is zero
} else {
shares = _convertToShares(assets, currentShares, currentAssets, Math.Rounding.Floor);
}
_mint(to, shares);
}
/// @notice Converts an amount of new assets into equivalent shares based on the current state of the contract
/// @dev This internal view function calculates the number of shares corresponding to a given amount of new assets,
/// considering the current total shares and assets in the contract.
/// It uses the mulDiv function for multiplication and division, applying the specified rounding method.
/// A decimals offset is added to currentShares for precision adjustments.
/// @param newAssets The amount of new assets to be converted into shares
/// @param currentShares The current total number of shares in the contract
/// @param currentAssets The current total assets in the contract
/// @param rounding The rounding direction to be used in the calculation (up or down)
function _convertToShares(
uint256 newAssets,
uint256 currentShares,
uint256 currentAssets,
Math.Rounding rounding
)
internal
view
returns (uint256)
{
return newAssets.mulDiv(currentShares + 10 ** _decimalsOffset(), currentAssets + 1, rounding);
}
/// @notice create and store a neww deposit record
/// @param _amount amount of wstETH deposited
/// @param _depositor depositor of the wstETH
/// @param _receiver receiver of the vault shares after wstETH is invested successfully
function _recordDeposit(
uint256 _amount,
address _depositor,
address _receiver
)
internal
returns (uint256 recordKey)
{
recordKey = ++depositCounter;
deposits[recordKey].depositor = _depositor;
deposits[recordKey].amount = _amount;
deposits[recordKey].receiver = _receiver;
deposits[recordKey].state = DepositState.DEPOSITED;
}
/// @notice Take wstETH and create a deposit record
/// @dev Overrides inherited method
/// @notice Deposit is a two step process:
/// 1) User deposits wstETH to the vault and a record of their deposit is stored
/// 2) Keeper/Controller invokes `invest` which invests the wstETH into aura.
/// Upon successful invest, vault shares are minted to receivers
/// @param caller depositor address
/// @param receiver receiver of vault shares
/// @param assets amount of wstETH to be deposited (it's different from Aura Vault Shares)
function _deposit(
address caller,
address receiver,
uint256 assets,
uint256
) internal override {
if (currentDeposits + assets > maxInvestment) {
revert InvestmentsOverflow();
}
currentDeposits += assets;
deposited += assets;
if (assets == 0) {
revert ZeroDepositNotAllowed();
}
// add it to deposit and generate a key
uint256 depositKey = _recordDeposit(assets, caller, receiver);
_pullwstEth(caller, assets);
// emit
emit Deposited(depositKey, assets, caller, receiver);
}
/// @notice Use transferFrom to pull wstETH from an address
/// @param from Owner of the wstETH
/// @param value Amount of wstETH to be transferred
function _pullwstEth(address from, uint256 value) internal {
// pull funds from the msg.sender
bool transferSuccess = wstETH.transferFrom(from, address(this), value);
if (!transferSuccess) {
revert ERC20_TransferFromFailed();
}
}
/// @notice Compute total wstETH to be utilised for investment and mark those deposits as invested
/// @dev Vault shares are minted after the tokens are invested
/// @return _wstEthAmount Total wstETH amount to be used
/// @return _startKeyId the First deposit record whose wstETH haven't been used for investment
/// @return _totalDeposits Total number of deposit records utilised in this invest operation
function _computeAndRebalanceDepositRecords()
internal
returns (uint256 _wstEthAmount, uint256 _startKeyId, uint256 _totalDeposits)
{
// calculate number of deposit record which needs to be analysed
uint256 length = Math.min(depositCounter - lastUsedDepositKey, 200);
// set the key ID of first deposit record that will be used
_startKeyId = lastUsedDepositKey + 1;
// update the last used deposit record key
lastUsedDepositKey = lastUsedDepositKey + length;
// loop over deposit records
for (uint256 i; i < length; i++) {
// only use the deposit record if the deposit is not cancelled
if (deposits[_startKeyId + i].state == DepositState.DEPOSITED
&& deposits[_startKeyId + i].depositor != address(0) ) {
// increase the count of total genuine deposits to be used
_totalDeposits++;
// add the amount of depsoit to total wstETH to be used
_wstEthAmount += deposits[_startKeyId + i].amount;
// set the state to invested
deposits[_startKeyId + i].state = DepositState.INVESTED;
}
}
deposited -= _wstEthAmount;
return (_wstEthAmount, _startKeyId, _totalDeposits);
}
/// @notice Mint vault shares to receivers of all deposit records that was used for investment in current operation
/// @param _startKeyId First deposit record from where the mint of vault shares will begin
/// @param _assets Amount of Aura vault shares that were minted per deposit record
function _mintMultipleShares(
uint256 _startKeyId,
uint256 currentShares,
uint256 currentAssets,
uint256 _assets,
uint256 wstEthAmount
)
internal
{
// loop over the deposit records starting from the start deposit key ID
for (_startKeyId; _startKeyId <= lastUsedDepositKey; _startKeyId++) {
// only mint vault shares to deposit records whose funds have been utilised
if (deposits[_startKeyId].state == DepositState.INVESTED) {
// Is there a loss of precision issue here?
// We try to determine the number of shares that should be issued based on the proportion of wsteth provided
uint256 contribution = deposits[_startKeyId].amount * _assets / wstEthAmount;
_mintShares(contribution, currentShares, currentAssets, deposits[_startKeyId].receiver);
delete deposits[_startKeyId];
}
}
}
/// @notice Transfer wstETH to an address
/// @param to Receiver of wstETH
/// @param value Amount of wstETH to be transferred
function _pushwstEth(address to, uint256 value) internal {
// pull funds from the msg.sender
bool transferSuccess = wstETH.transfer(to, value);
if (!transferSuccess) {
revert ERC20_TransferFailed();
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
________ ______________________
__ ___/___ ____________________________ ___________ __ \__ |_ __ \
_____ \_ / / /__ __ \_ ___/ _ \_ __ `__ \ _ \_ / / /_ /| | / / /
____/ // /_/ /__ /_/ / / / __/ / / / / / __/ /_/ /_ ___ / /_/ /
/____/ \__,_/ _ .___//_/ \___//_/ /_/ /_/\___//_____/ /_/ |_\____/
/_/
*/
pragma solidity 0.8.20;
/// @title Leverage Strategy Storage Contract
/// @author SupremeDAO
/// @notice This abstract contract serves as a storage module for the Leverage Strategy,
/// holding state variables, structured data, and events used across the strategy implementation.
/// @dev This contract defines the essential storage structure including deposits,
/// state variables related to investment and borrowing, and custom error messages.
/// It doesn't contain logic for strategy execution but is inherited by contracts that do.
abstract contract LeverageStrategyStorage {
/// @notice Role identifier for the keeper role, responsible for protocol maintenance tasks. Role given to PowerAgent
bytes32 public constant KEEPER_ROLE = keccak256("KEEPER_ROLE");
/// @notice Role identifier for the controller role, responsible for high-level protocol management
bytes32 public constant CONTROLLER_ROLE = keccak256("CONTROLLER_ROLE");
/// @notice Role identifier for the caller role, responsible for high-level protocol management
bytes32 public constant JOB_OWNER_ROLE = keccak256("CALLER_ROLE");
/// @notice Fixed percentage (scaled by 10^12) used in unwinding positions, default set to 30%
uint256 public unwindPercentage = 30 * 10 ** 10;
/// @notice Constant representing 100%, used for percentage calculations, scaled by 10^12
uint256 public constant HUNDRED_PERCENT = 10 ** 12;
/// @notice Max percentage of fees on leverage transferred to DAO
uint256 public MAX_DAO_FEE = 80 * HUNDRED_PERCENT / 100;
/// @notice Amount of wstEth in the contract, that was deposited but is not yet invested
uint256 public deposited = 0;
/// @notice The maximal amount of investments processed by the strategy
uint256 public maxInvestment = 100 ether;
/// @notice The amount of current investments in the contract
uint256 public currentDeposits = 0;
/// @dev Represents the various states a deposit can be in.
enum DepositState {
DEPOSITED, // Deposit has been made.
INVESTED // Deposit has been invested.
}
/// @notice Address that receives a fraction of the yield.
address public controller;
/// @notice Percentage buffer to use, default 5%
uint256 public healthBuffer = 5e10;
/// @notice Percentage of funds, transferred to DAO
uint256 public fee = 60 * HUNDRED_PERCENT / 100;
/// @dev Struct to keep track of each deposit.
struct DepositRecord {
DepositState state;
address depositor;
address receiver;
uint256 amount;
}
struct QueuedAction {
uint64 timestamp;
uint192 minAmountOut;
}
/// @notice Counter for deposit records.
uint256 public depositCounter;
/// @notice Last used key in the deposit mapping.
uint256 public lastUsedDepositKey;
/// @notice Mapping of deposit records.
mapping(uint256 => DepositRecord) public deposits;
// The queued unwind
QueuedAction public unwindQueued;
QueuedAction public investQueued;
/// @notice Emitted when a deposit is made.
/// @param depositKey The key of the deposit in the mapping.
/// @param amount The amount of the deposit.
/// @param sender The address of the sender who made the deposit.
/// @param receiver The address of the receiver for the deposit.
event Deposited(uint256 indexed depositKey, uint256 amount, address indexed sender, address indexed receiver);
/// @notice Emitted when a deposit is cancelled.
/// @param depositKey The key of the cancelled deposit in the mapping.
event DepositCancelled(uint256 indexed depositKey);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
{
"compilationTarget": {
"contracts/LeverageStrategy.sol": "LeverageStrategy"
},
"evmVersion": "shanghai",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": [
":@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
":ds-test/=lib/forge-std/lib/ds-test/src/",
":erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
":forge-std/=lib/forge-std/src/",
":hardhat/=node_modules/hardhat/",
":openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}
[{"inputs":[{"internalType":"bytes32","name":"_poolId","type":"bytes32"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AURA_DepositFailed","type":"error"},{"inputs":[],"name":"AccessControlBadConfirmation","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bytes32","name":"neededRole","type":"bytes32"}],"name":"AccessControlUnauthorizedAccount","type":"error"},{"inputs":[],"name":"DepositCancellationNotAllowed","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"allowance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientAllowance","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientBalance","type":"error"},{"inputs":[{"internalType":"address","name":"approver","type":"address"}],"name":"ERC20InvalidApprover","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"ERC20InvalidReceiver","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"ERC20InvalidSender","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"}],"name":"ERC20InvalidSpender","type":"error"},{"inputs":[],"name":"ERC20_ApprovalFailed","type":"error"},{"inputs":[],"name":"ERC20_TransferFailed","type":"error"},{"inputs":[],"name":"ERC20_TransferFromFailed","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"ERC4626ExceededMaxDeposit","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"ERC4626ExceededMaxMint","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"ERC4626ExceededMaxRedeem","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"ERC4626ExceededMaxWithdraw","type":"error"},{"inputs":[],"name":"InvalidFee","type":"error"},{"inputs":[],"name":"InvalidInput","type":"error"},{"inputs":[],"name":"InvalidInvest","type":"error"},{"inputs":[],"name":"InvalidJobOwner","type":"error"},{"inputs":[],"name":"InvalidUnwind","type":"error"},{"inputs":[],"name":"InvestmentsOverflow","type":"error"},{"inputs":[],"name":"MathOverflowedMulDiv","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[],"name":"UnknownExecuter","type":"error"},{"inputs":[],"name":"UseOverLoadedRedeemFunction","type":"error"},{"inputs":[],"name":"ZeroDepositNotAllowed","type":"error"},{"inputs":[],"name":"ZeroInvestmentNotAllowed","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":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","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":true,"internalType":"uint256","name":"depositKey","type":"uint256"}],"name":"DepositCancelled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"depositKey","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"}],"name":"Deposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","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":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","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"},{"inputs":[],"name":"AURA","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"AURA_BOOSTER","outputs":[{"internalType":"contract IAuraBooster","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"AURA_PID","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"AURA_VAULT","outputs":[{"internalType":"contract IBasicRewards","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"AgentContract","outputs":[{"internalType":"contract IPPAgentV2JobOwner","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"BAL","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"BAL_VAULT","outputs":[{"internalType":"contract IBalancerVault","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"CONTROLLER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"D2D","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"D2D_USDC_BPT","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"EMPTY_USER_DATA","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"FIXED_LIMIT","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"HUNDRED_PERCENT","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"JOB_OWNER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"KEEPER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_DAO_FEE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"N","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"POOL_AURA_WETH_ID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"POOL_BAL_WETH_ID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"POOL_ID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"POOL_WSTETH_WETH_ID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"QUERY_CONTROL_AMOUNT","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"USDC","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"USDC_CONTROL_AMOUNT","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WETH","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","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":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_key","type":"uint256"}],"name":"cancelDeposit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"controller","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"convertToAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"convertToShares","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"crvUSD","outputs":[{"internalType":"contract IcrvUSD","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"crvUSDController","outputs":[{"internalType":"contract IcrvUSDController","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"crvUSDUSDCPool","outputs":[{"internalType":"contract IcrvUSDUSDCPool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"currentDeposits","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":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"_bptAmountOut","type":"uint256"}],"name":"depositAndInvest","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"depositCounter","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"deposited","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"deposits","outputs":[{"internalType":"enum LeverageStrategyStorage.DepositState","name":"state","type":"uint8"},{"internalType":"address","name":"depositor","type":"address"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_bptAmountOut","type":"uint256"},{"internalType":"bool","name":"isReinvest","type":"bool"}],"name":"executeInvestFromKeeper","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"executeUnwindFromKeeper","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"fee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"healthBuffer","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_N","type":"uint256"},{"internalType":"address","name":"_controller","type":"address"},{"internalType":"address","name":"_keeper","type":"address"},{"internalType":"address","name":"_jobOwner","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_bptAmountOut","type":"uint256"}],"name":"invest","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"investFromKeeper","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"investQueued","outputs":[{"internalType":"uint64","name":"timestamp","type":"uint64"},{"internalType":"uint192","name":"minAmountOut","type":"uint192"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastUsedDepositKey","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"maxDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxInvestment","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"maxMint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"maxRedeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"maxWithdraw","outputs":[{"internalType":"uint256","name":"","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":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"previewDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"previewMint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"previewRedeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"previewWithdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"minAmountOut","type":"uint256"}],"name":"redeemWstEth","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"callerConfirmation","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_fee","type":"uint256"}],"name":"setFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"percentage","type":"uint256"}],"name":"setHealthBuffer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_oldJobOwner","type":"address"},{"internalType":"address","name":"_jobOwner","type":"address"}],"name":"setJobOwner","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_maxInvestment","type":"uint256"}],"name":"setMaxInvestment","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newPercentage","type":"uint256"}],"name":"setUnwindPercentage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"strategyHealth","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"minWethAmountBal","type":"uint256"},{"internalType":"uint256","name":"minWethAmountAura","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapRewardFromKeeper","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"token0","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"token1","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalWsthethDeposited","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","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":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unwindPercentage","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"auraShares","type":"uint256"},{"internalType":"uint256","name":"minAmountOut","type":"uint256"}],"name":"unwindPosition","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unwindPositionFromKeeper","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unwindQueued","outputs":[{"internalType":"uint64","name":"timestamp","type":"uint64"},{"internalType":"uint192","name":"minAmountOut","type":"uint192"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"wstETH","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"}]