Contract Name:
SiloV2Adapter
Contract Source Code:
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity 0.8.27;
import { ERC4626AdapterHarvestable } from "src/abstracts/ERC4626AdapterHarvestable.sol";
import { ISiloIncentivesController } from "interfaces/silo/ISilo.sol";
contract SiloV2Adapter is ERC4626AdapterHarvestable {
/// @notice The Silo incentives controller.
ISiloIncentivesController public incentivesController;
/*//////////////////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////////////////*/
/// @notice Constructor for the strategy adapter.
/// @param _multistrategy The address of the multi-strategy contract.
/// @param _asset The address of the asset.
/// @param _vault The address of the ERC4626 vault.
/// @param _name The name of this Strategy Adapter.
/// @param _id The type identifier of this Strategy Adapter.
constructor(
address _multistrategy,
address _asset,
address _vault,
address _incentivesController,
HarvestAddresses memory _harvestAddresses,
string memory _name,
string memory _id
)
ERC4626AdapterHarvestable(
_multistrategy,
_asset,
_vault,
_harvestAddresses,
_name,
_id
)
{
incentivesController = ISiloIncentivesController(_incentivesController);
}
/*//////////////////////////////////////////////////////////////////////////
INTERNAL NON-CONSTANT FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Claims the rewards.
function _claim() internal override {
incentivesController.claimRewards(address(this));
}
}
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity 0.8.27;
import { IERC20, SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { StrategyAdapterHarvestable } from "./StrategyAdapterHarvestable.sol";
import { Errors } from "src/infra/libraries/Errors.sol";
abstract contract ERC4626AdapterHarvestable is StrategyAdapterHarvestable {
using SafeERC20 for IERC20;
using Math for uint256;
/// @notice The ERC4626 Vault
IERC4626 public vault;
/*//////////////////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////////////////*/
/// @notice Constructor for the strategy adapter.
/// @param _multistrategy The address of the multi-strategy contract.
/// @param _asset The address of the asset.
/// @param _vault The address of the ERC4626 vault.
/// @param _name The name of this Strategy Adapter.
/// @param _id The type identifier of this Strategy Adapter.
constructor(
address _multistrategy,
address _asset,
address _vault,
HarvestAddresses memory _harvestAddresses,
string memory _name,
string memory _id
)
StrategyAdapterHarvestable(_multistrategy, _asset, _harvestAddresses, _name, _id)
{
vault = IERC4626(_vault);
_giveAllowances();
}
/*//////////////////////////////////////////////////////////////////////////
INTERNAL CONSTANT FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Returns the total amount of assets held in this adapter.
function _totalAssets() internal override view returns(uint256) {
uint256 sharesBalance = vault.balanceOf(address(this));
uint256 assetsSupplied = vault.convertToAssets(sharesBalance);
uint256 assetBalance = IERC20(asset).balanceOf(address(this));
uint256 total = assetsSupplied + assetBalance;
return total > 0 ? total - 1 : total;
}
/// @inheritdoc StrategyAdapterHarvestable
function _verifyRewardToken(address _token) internal view override {
require(_token != address(vault), Errors.InvalidRewardToken(_token));
}
/*//////////////////////////////////////////////////////////////////////////
INTERNAL NON-CONSTANT FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Deposits all the liquidity into the ERC4626 vault.
function _deposit() internal override {
uint256 balance = IERC20(asset).balanceOf(address(this));
vault.deposit(balance, address(this));
}
/// @notice Withdraws a specified amount of assets from the ERC4626 vault.
/// @param _amount The amount of assets to withdraw from the Silo.
function _withdraw(uint256 _amount) internal override {
vault.withdraw(_amount, address(this), address(this));
}
/// @notice Performs an emergency withdrawal of all assets from the ERC4626 vault.
/// This function is intended for emergency situations where all assets need to be withdrawn immediately.
function _emergencyWithdraw() internal override {
uint256 maxWithdraw = vault.maxWithdraw(address(this));
if (maxWithdraw > 0) {
vault.withdraw(maxWithdraw, address(this), address(this));
}
}
/// @notice Sets the maximum allowance of the base asset for the ERC4626 vault.
function _giveAllowances() internal override {
IERC20(asset).forceApprove(address(vault), type(uint).max);
IERC20(wrappedGas).forceApprove(swapper, type(uint).max);
}
/// @notice Revokes the allowance of the base asset for the ERC4626 vault.
function _revokeAllowances() internal override {
IERC20(asset).forceApprove(address(vault), 0);
IERC20(wrappedGas).forceApprove(swapper, 0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20} from "@openzeppelin-4/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin-4/contracts/token/ERC20/utils/SafeERC20.sol";
interface ISilo {
function deposit(address asset, uint amount, bool collateralOnly) external;
function withdraw(address asset, uint amount, bool collateralOnly) external;
function balanceOf(address user) external view returns (uint256);
}
interface ISiloCollateralToken {
function asset() external view returns (address);
}
interface ISiloLens {
function balanceOfUnderlying(
uint256 _assetTotalDeposits,
address _shareToken,
address _user
) external view returns (uint256);
function totalDepositsWithInterest(
address _silo,
address _asset
) external view returns (uint256 _totalDeposits);
}
interface ISiloRewards {
function claimRewardsToSelf(
address[] memory assets,
uint256 amount
) external;
}
interface ISiloIncentivesController {
function claimRewards(address to) external;
}
// 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/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
// 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: GNU AGPLv3
pragma solidity 0.8.27;
import { IERC20, SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IStrategyAdapterHarvestable } from "interfaces/infra/multistrategy/IStrategyAdapterHarvestable.sol";
import { IGoatSwapper } from "interfaces/infra/IGoatSwapper.sol";
import { StrategyAdapter } from "src/abstracts/StrategyAdapter.sol";
import { Errors } from "src/infra/libraries/Errors.sol";
abstract contract StrategyAdapterHarvestable is IStrategyAdapterHarvestable, StrategyAdapter {
using SafeERC20 for IERC20;
struct HarvestAddresses {
address swapper;
address wrappedGas;
}
/// @notice The timestamp of the last successful harvest.
uint256 public lastHarvest;
/// @notice An array of reward token addresses that can be claimed and swapped.
address[] public rewards;
/// @notice The address of the Wrapped Gas token used as an intermediary for swaps.
/// Used because it has high liquidity.
address internal wrappedGas;
/// @notice The address of the swapper contract used to swap reward tokens.
address swapper;
/// @notice A mapping of minimum amounts for each reward token before it can be swapped.
/// @dev The key is the reward token address, and the value is the minimum amount required for swapping.
mapping(address token => uint minimumAmount) public minimumAmounts;
/*//////////////////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////////////////*/
/// @notice Constructor for the strategy adapter.
/// @param _multistrategy The address of the multi-strategy contract.
/// @param _asset The address of the asset.
/// @param _harvestAddresses Struct of Protocol Addresses.
/// @param _name The name of this Strategy Adapter.
/// @param _id The type identifier of this Strategy Adapter.
constructor(
address _multistrategy,
address _asset,
HarvestAddresses memory _harvestAddresses,
string memory _name,
string memory _id
)
StrategyAdapter(_multistrategy, _asset, _name, _id)
{
swapper = _harvestAddresses.swapper;
wrappedGas = _harvestAddresses.wrappedGas;
}
/*//////////////////////////////////////////////////////////////////////////
USER FACING CONSTANT FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @inheritdoc IStrategyAdapterHarvestable
function rewardsLength() external view returns (uint256) {
return rewards.length;
}
/*//////////////////////////////////////////////////////////////////////////
USER FACING NON-CONSTANT FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @inheritdoc IStrategyAdapterHarvestable
function harvest() external whenNotPaused {
_claim();
_swapRewardsToWrappedGas();
if (IERC20(wrappedGas).balanceOf(address(this)) > minimumAmounts[wrappedGas]) {
_swapWrappedGasToAsset();
uint256 assetsHarvested = IERC20(asset).balanceOf(address(this));
_deposit();
lastHarvest = block.timestamp;
emit AdapterHarvested(msg.sender, assetsHarvested, _totalAssets());
}
}
/// @inheritdoc IStrategyAdapterHarvestable
function addReward(address _token) external onlyOwner {
require(_token != asset && _token != wrappedGas, Errors.InvalidRewardToken(_token));
_verifyRewardToken(_token);
rewards.push(_token);
IERC20(_token).forceApprove(swapper, type(uint256).max);
}
/// @inheritdoc IStrategyAdapterHarvestable
function resetRewards() external onlyOwner {
for (uint i; i < rewards.length; ++i) {
IERC20(rewards[i]).forceApprove(swapper, 0);
}
delete rewards;
}
/// @inheritdoc IStrategyAdapterHarvestable
function setRewardMinimumAmount(address _token, uint _minAmount) external onlyOwner {
minimumAmounts[_token] = _minAmount;
}
/// @inheritdoc IStrategyAdapterHarvestable
function updateSwapper(address _swapper) external onlyOwner {
for (uint i; i < rewards.length; ++i) {
address token = rewards[i];
IERC20(token).forceApprove(swapper, 0);
IERC20(token).forceApprove(_swapper, type(uint256).max);
}
IERC20(wrappedGas).forceApprove(swapper, 0);
IERC20(wrappedGas).forceApprove(_swapper, type(uint256).max);
swapper = _swapper;
emit SwapperUpdated(_swapper);
}
/*//////////////////////////////////////////////////////////////////////////
INTERNAL NON-CONSTANT FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Swaps all reward tokens to Wrapped Gas.
/// @dev This function checks if the balance of each reward token exceeds the minimum amount before swapping.
function _swapRewardsToWrappedGas() internal virtual {
for (uint i; i < rewards.length; ++i) {
address token = rewards[i];
uint256 amount = IERC20(token).balanceOf(address(this));
if (amount > minimumAmounts[token]) {
IGoatSwapper(swapper).swap(token, wrappedGas, amount);
}
}
}
/// @notice Swaps Wrapped Gas to `asset`.
function _swapWrappedGasToAsset() internal virtual {
if (asset != wrappedGas) _swap(wrappedGas, asset);
}
/// @notice Swaps one token for another using the swapper contract.
/// @param tokenFrom The address of the token to swap from.
/// @param tokenTo The address of the token to swap to.
function _swap(address tokenFrom, address tokenTo) internal {
uint amount = IERC20(tokenFrom).balanceOf(address(this));
IGoatSwapper(swapper).swap(tokenFrom, tokenTo, amount);
}
/// @notice Claims rewards.
/// @dev This function is meant to be overridden by child contracts to implement reward claiming logic.
function _claim() internal virtual {}
/// @notice Verifies if a token is a valid reward token.
/// @dev This function is meant to be overridden by child contracts to implement token verification logic.
/// @param _token The address of the token to verify.
function _verifyRewardToken(address _token) internal view virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.20;
/// @title Errors
/// @notice Library containing all custom errors the protocol may revert with.
library Errors {
/*//////////////////////////////////////////////////////////////////////////
GENERICS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Thrown when `msg.sender` is not the manager.
error CallerNotManager(address caller);
/// @notice Thrown when `msg.sender` is not a guardian.
error CallerNotGuardian(address caller);
/// @notice Thrown when `amount` is zero.
error ZeroAmount(uint256 amount);
/// @notice Thrown when setting an address to the zero address.
error ZeroAddress();
/// @notice Thrown when `currentBalance` is lower than `amount`.
error InsufficientBalance(uint256 currentBalance, uint256 amount);
/// @notice Thrown when `addr` is an unexpected address.
error InvalidAddress(address addr);
/*//////////////////////////////////////////////////////////////////////////
MULTISTRATEGY
//////////////////////////////////////////////////////////////////////////*/
/// @notice Thrown when performing an action on a non-active strategy.
error StrategyNotActive(address strategy);
/// @notice Thrown when performing an action on an active strategy.
error StrategyAlreadyActive(address strategy);
/// @notice Thrown when a strategy is reporting a gain and a loss simultaneously.
error GainLossMismatch();
/// @notice Thrown when a deposit would exceed the depositLimit
error DepositLimit();
/// @notice Thrown when the owner tries to set a fee above the maximum permitted fee.
error ExcessiveFee(uint256 fee);
/// @notice Thrown when the debtRatio of a strategy or a multistrategy is above 100%.
error DebtRatioAboveMaximum(uint256 debtRatio);
/// @notice Thrown when trying to remove a strategy from `withdrawOrder` that still has outstanding debt.
error StrategyWithOutstandingDebt();
/// @notice Thrown when minDebtDelta is above maxDebtDelta or maxDebtDelta is below minDebtDelta.
error InvalidDebtDelta();
/// @notice Thrown when a strategy is reporting a loss higher than its total debt.
error InvalidStrategyLoss();
/// @notice Thrown when there is non-Zero Address following a Zero Address in withdrawOrder.
error InvalidWithdrawOrder();
/// @notice Thrown when trying to add a new strategy to the multistrategy but it already reached the
/// maximum amount of strategies.
error MaximumAmountStrategies();
/// @notice Thrown when trying to remove a strategy that has a `debtRatio` greater than 0.
error StrategyNotRetired();
/// @notice Thrown when there isn't enough liquidity to cover a withdraw
/// @param assets The amount of assets requested.
/// @param liquidity The current liquidity available in the contract.
error InsufficientLiquidity(uint256 assets, uint256 liquidity);
/// @notice Thrown when depositing / minting on a retired multistrategy.
error Retired();
/*//////////////////////////////////////////////////////////////////////////
STRATEGY ADAPTER
//////////////////////////////////////////////////////////////////////////*/
/// @notice Thrown when the caller is not the Multistrategy.
error CallerNotMultistrategy(address caller);
/// @notice Thrown when the `_asset` parameter on the constructor doesn't match
/// the `deposit` token on Multistrategy.
error AssetMismatch(address multAsset, address stratAsset);
/// @notice Thrown when the requested slippage limit exceeds the maximum permitted value.
/// @param slippageLimit The slippage limit in basis points (BPS).
error SlippageLimitExceeded(uint256 slippageLimit);
/// @notice Thrown when the actual slippage exceeds the allowed slippage.
/// @param amount0 The expected amount after accounting for allowed slippage.
/// @param amount1 The actual amount obtained.
error SlippageCheckFailed(uint256 amount0, uint256 amount1);
/// @notice Thrown when the reward added is the base asset of the Strategy.
error InvalidRewardToken(address rewardToken);
/*//////////////////////////////////////////////////////////////////////////
ERC-4626
//////////////////////////////////////////////////////////////////////////*/
/**
* @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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @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 amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` 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 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../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 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.encodeWithSelector(token.transfer.selector, 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.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 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);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @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.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @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, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @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.isContract(address(token));
}
}
// 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/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) (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: 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: GNU AGPLv3
pragma solidity ^0.8.27;
interface IStrategyAdapterHarvestable {
/// @notice Emitted when the adapter successfully harvests rewards.
/// @param caller The address of the caller who triggered the harvest.
/// @param amountHarvested The amount of `want` tokens harvested.
/// @param totalAssets The total assets held by the adapter after the harvest.
event AdapterHarvested(address caller, uint256 amountHarvested, uint256 totalAssets);
/// @notice Emitted when the swapper contract is updated.
/// @param newSwapper The address of the new swapper contract.
event SwapperUpdated(address newSwapper);
/// @notice Returns the amount of different reward tokens existent in the `rewards` array
function rewardsLength() external view returns (uint256);
/// @notice Harvests rewards, swaps them to WETH, and then to the desired asset.
/// @dev This function claims rewards, swaps them to WETH, and then converts WETH to the `want` token.
function harvest() external;
/// @notice Adds a new reward token to be claimed.
/// @param token The address of the reward token to add.
/// @dev The token must not be the same as `want` or `weth`.
function addReward(address token) external;
/// @notice Resets the list of reward tokens.
/// @dev This function removes all reward tokens and revokes their approvals.
function resetRewards() external;
/// @notice Sets the minimum amount of a reward token required for swapping.
/// @param token The address of the reward token.
/// @param minAmount The minimum amount of the token required for swapping.
function setRewardMinimumAmount(address token, uint256 minAmount) external;
/// @notice Updates the swapper contract used for swapping tokens.
/// @param swapper The address of the new swapper contract.
/// @dev This function revokes approvals from the old swapper and grants them to the new swapper.
function updateSwapper(address swapper) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IGoatSwapper {
function swap(
address fromToken,
address toToken,
uint256 amountIn
) external returns (uint256 amountOut);
function swap(
address fromToken,
address toToken,
uint256 amountIn,
uint256 minAmountOut
) external returns (uint256 amountOut);
function getAmountOut(
address _fromToken,
address _toToken,
uint256 _amountIn
) external view returns (uint256 amountOut);
struct SwapInfo {
address router;
bytes data;
uint256 amountIndex;
}
function setSwapInfo(
address _fromToken,
address _toToken,
SwapInfo calldata _swapInfo
) external;
function setSwapInfos(
address[] calldata _fromTokens,
address[] calldata _toTokens,
SwapInfo[] calldata _swapInfos
) external;
}
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity 0.8.27;
import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import { IERC20, SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { StrategyAdapterAdminable } from "src/abstracts/StrategyAdapterAdminable.sol";
import { IStrategyAdapter } from "interfaces/infra/multistrategy/IStrategyAdapter.sol";
import { IMultistrategy } from "interfaces/infra/multistrategy/IMultistrategy.sol";
import { Errors } from "src/infra/libraries/Errors.sol";
abstract contract StrategyAdapter is IStrategyAdapter, StrategyAdapterAdminable {
using SafeERC20 for IERC20;
using Math for uint256;
/// @dev 100% in BPS, setting the slippage to 100% means no slippage protection.
uint256 constant MAX_SLIPPAGE = 10_000;
/// @inheritdoc IStrategyAdapter
address public immutable multistrategy;
/// @inheritdoc IStrategyAdapter
address public immutable asset;
/// @inheritdoc IStrategyAdapter
uint256 public slippageLimit;
/// @notice Name of this Strategy Adapter
string public name;
/// @notice Identifier of this Strategy Adapter
string public id;
/*//////////////////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////////////////*/
/// @dev Reverts if `_asset` doesn't match `asset` on the Multistrategy.
/// @param _multistrategy Address of the multistrategy this strategy will belongs to.
/// @param _asset Address of the token used to deposit and withdraw on this strategy.
constructor(address _multistrategy, address _asset, string memory _name, string memory _id) StrategyAdapterAdminable(msg.sender) {
require(_asset == IERC4626(_multistrategy).asset(), Errors.AssetMismatch(IERC4626(_multistrategy).asset(), _asset));
multistrategy = _multistrategy;
asset = _asset;
slippageLimit = 0;
name = _name;
id = _id;
IERC20(asset).forceApprove(multistrategy, type(uint256).max);
}
/// @dev Reverts if called by any account other than the Multistrategy this strategy belongs to.
modifier onlyMultistrategy() {
require(msg.sender == multistrategy, Errors.CallerNotMultistrategy(msg.sender));
_;
}
/*//////////////////////////////////////////////////////////////////////////
USER FACING CONSTANT FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @inheritdoc IStrategyAdapter
function totalAssets() external view returns (uint256) {
return _totalAssets();
}
/// @inheritdoc IStrategyAdapter
function currentPnL() external view returns (uint256, uint256) {
return _calculateGainAndLoss(_totalAssets());
}
/*//////////////////////////////////////////////////////////////////////////
USER FACING NON-CONSTANT FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @inheritdoc IStrategyAdapter
function requestCredit() external onlyOwner whenNotPaused {
uint256 credit = IMultistrategy(multistrategy).requestCredit();
if(credit > 0) {
_deposit();
}
}
/// @inheritdoc IStrategyAdapter
function setSlippageLimit(uint256 _slippageLimit) external onlyOwner {
require(_slippageLimit <= MAX_SLIPPAGE, Errors.SlippageLimitExceeded(_slippageLimit));
slippageLimit = _slippageLimit;
emit SlippageLimitSet(_slippageLimit);
}
/// @inheritdoc IStrategyAdapter
function sendReport(uint256 _repayAmount) external onlyOwner whenNotPaused {
_sendReport(_repayAmount);
}
/// @inheritdoc IStrategyAdapter
function askReport() external onlyMultistrategy whenNotPaused {
_sendReport(0);
}
/// @inheritdoc IStrategyAdapter
function sendReportPanicked() external onlyOwner whenPaused {
_sendReportPanicked();
}
/// @inheritdoc IStrategyAdapter
/// @dev Any surplus on the withdraw won't be sent to the multistrategy.
/// It will be eventually reported back as gain when sendReport is called.
function withdraw(uint256 _amount) external onlyMultistrategy whenNotPaused returns (uint256) {
_tryWithdraw(_amount);
uint256 withdrawn = Math.min(_amount, _liquidity());
IERC20(asset).safeTransfer(multistrategy, withdrawn);
return withdrawn;
}
/// @inheritdoc IStrategyAdapter
function panic() external onlyGuardian {
_emergencyWithdraw();
_revokeAllowances();
_pause();
}
/// @inheritdoc IStrategyAdapter
function pause() external onlyGuardian {
_revokeAllowances();
_pause();
}
/// @inheritdoc IStrategyAdapter
function unpause() external onlyOwner {
_unpause();
_giveAllowances();
}
/*//////////////////////////////////////////////////////////////////////////
INTERNAL CONSTANT FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Calculates the gain and loss based on current assets.
///
/// This function performs the following actions:
/// - Retrieves the total debt of the strategy from the multi-strategy contract.
/// - Determines whether the current assets are greater than or equal to the total debt to calculate the gain.
/// - If the current assets are less than the total debt, calculates the loss.
///
/// @param _currentAssets The current assets held by the strategy.
/// @return gain The calculated gain.
/// @return loss The calculated loss.
function _calculateGainAndLoss(uint256 _currentAssets) internal view returns (uint256, uint256) {
uint256 totalDebt = IMultistrategy(multistrategy).strategyTotalDebt(address(this));
uint256 gain = 0;
uint256 loss = 0;
if(_currentAssets >= totalDebt) {
gain = _currentAssets - totalDebt;
} else {
loss = totalDebt - _currentAssets;
}
return (gain, loss);
}
/// @notice Calculates the amount to be withdrawn from the strategy.
///
/// This function performs the following actions:
/// - Retrieves the exceeding debt of the strategy from the multi-strategy contract.
/// - If there is exceeding debt and a repayment amount is specified:
/// - Calculates the amount to be withdrawn to repay the exceeding debt at maximum slippage.
/// - Ensures the amount to be withdrawn does not exceed the repayment amount, adding any strategy gain.
/// - If there is no exceeding debt or no repayment amount, returns the strategy gain as the amount to be withdrawn.
/// - Note that slippage calculations are not applied here as any slippage would be considered a loss and subtracted from the gain.
///
/// @param _repayAmount The amount to be repaid.
/// @param _strategyGain The gain of the strategy.
/// @return The amount to be withdrawn from the strategy.
function _calculateAmountToBeWithdrawn(uint256 _repayAmount, uint256 _strategyGain) internal view returns (uint256) {
uint256 exceedingDebt = IMultistrategy(multistrategy).debtExcess(address(this));
if(exceedingDebt > 0 && _repayAmount > 0) {
if(slippageLimit == MAX_SLIPPAGE) return _repayAmount + _strategyGain;
uint256 exceedingDebtWithSlippage = exceedingDebt.mulDiv(MAX_SLIPPAGE, MAX_SLIPPAGE - slippageLimit);
return Math.min(_repayAmount, exceedingDebtWithSlippage) + _strategyGain;
}
return _strategyGain;
}
/// @notice Calculates the adjusted gain and loss after accounting for slippage.
///
/// This function performs the following actions:
/// - Calculates the slippage loss as the difference between the amount intended to be withdrawn and the actual amount withdrawn.
/// - If there is no slippage loss, returns the original gain and loss.
/// - If there is slippage loss:
/// - Deducts the slippage loss from the gain.
/// - If the slippage loss exceeds the gain, the remaining slippage loss is added to the loss.
/// - Returns the adjusted gain and loss after accounting for slippage.
///
/// @param _gain The initial gain before slippage.
/// @param _loss The initial loss before slippage.
/// @param _currentBalance The current balance of asset in this contract.
/// @param _toBeWithdrawn The amount intended to be withdrawn.
/// @return The adjusted gain and loss after slippage.
function _calculateGainAndLossAfterSlippage(
uint256 _gain,
uint256 _loss,
uint256 _currentBalance,
uint256 _toBeWithdrawn
) internal pure returns (uint256, uint256) {
uint256 slippageLoss = (_toBeWithdrawn > _currentBalance) ? _toBeWithdrawn - _currentBalance : 0;
if(slippageLoss == 0) return (_gain, _loss);
if(slippageLoss > _gain) {
slippageLoss -= _gain;
_gain = 0;
} else {
_gain -= slippageLoss;
slippageLoss = 0;
}
_loss += slippageLoss;
return (_gain, _loss);
}
/// @notice Returns the current balance of asset in this contract.
function _liquidity() internal view returns (uint256) {
return IERC20(asset).balanceOf(address(this));
}
/// @notice Returns the amount of `asset` the underlying strategy holds. In the case this strategy
/// has swapped `asset` for another asset, it should return the most approximate value.
/// @dev Child contract must implement the logic to calculate the amount of assets.
function _totalAssets() internal virtual view returns (uint256) {}
/*//////////////////////////////////////////////////////////////////////////
INTERNAL NON-CONSTANT FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Sends a report on the strategy's performance.
///
/// This function performs the following actions:
/// - Calculates the current assets of the strategy.
/// - Attempts to withdraw the repayment amount plus any gain.
/// - Ensures that the gain is not used to repay the debt.
/// - Reports the available amount for repayment, the gain, and the loss to the multi-strategy.
///
/// @param _repayAmount The amount to be repaid to the multi-strategy.
function _sendReport(uint256 _repayAmount) internal {
uint256 currentAssets = _totalAssets();
(uint256 gain, uint256 loss) = _calculateGainAndLoss(currentAssets);
uint256 toBeWithdrawn = _calculateAmountToBeWithdrawn(_repayAmount, gain);
_tryWithdraw(toBeWithdrawn);
(gain, loss) = _calculateGainAndLossAfterSlippage(gain, loss, _liquidity(), toBeWithdrawn);
uint256 availableForRepay = _liquidity() - gain;
IMultistrategy(multistrategy).strategyReport(availableForRepay, gain, loss);
}
/// @notice Sends a report on the strategy's performance after the strategy has been panicked.
///
/// This function performs the following actions:
/// - Retrieves the current balance of the asset held by the contract.
/// - Calculates the gain and loss based on the current assets.
/// - Ensures that the gain is not used to repay the debt.
/// - Reports the available amount for repayment, the gain, and the loss to the multi-strategy.
function _sendReportPanicked() internal {
uint256 currentAssets = _liquidity();
(uint256 gain, uint256 loss) = _calculateGainAndLoss(currentAssets);
uint256 availableForRepay = currentAssets - gain;
IMultistrategy(multistrategy).strategyReport(availableForRepay, gain, loss);
}
/// @notice Attempts to withdraw a specified amount from the strategy.
///
/// This function performs the following actions:
/// - Calls the internal `_withdraw` function to withdraw the desired amount.
/// - Checks the current balance of the contract after the withdrawal.
/// - If the balance is less than the desired amount, it reverts with an insufficient balance error.
///
/// @param _amount The amount to withdraw from the strategy.
function _tryWithdraw(uint256 _amount) internal {
if(_amount == 0 || _amount <= _liquidity()) return;
// Liquidity is considered as amount already withdrawn, this amount doesn't need
// to be withdrawn.
_withdraw(_amount - _liquidity());
uint256 currentBalance = _liquidity();
uint256 desiredBalance = _amount.mulDiv(MAX_SLIPPAGE - slippageLimit, MAX_SLIPPAGE);
require(currentBalance >= desiredBalance, Errors.SlippageCheckFailed(desiredBalance, currentBalance));
}
/// @notice Deposits the entire balance of `asset` this contract holds into the underlying strategy.
/// @dev Child contract must implement the logic that will put the funds to work.
function _deposit() internal virtual {}
/// @notice Withdraws the specified `_amount` of `asset` from the underlying strategy.
/// @dev Child contract must implement the logic that will withdraw the funds.
/// @param _amount The amount of `asset` to withdraw.
function _withdraw(uint256 _amount) internal virtual {}
/// @notice Withdraws as much funds as possible from the underlying strategy.
/// @dev Child contract must implement the logic to withdraw as much funds as possible.
/// The withdraw process shouldn't have a slippage check, as it is in an emergency situation.
///
function _emergencyWithdraw() internal virtual {}
/// @dev Grants allowance for `asset` to the contracts used by the strategy adapter.
/// It should be overridden by derived contracts to specify the exact contracts and amounts for the allowances.
function _giveAllowances() internal virtual {}
/// @dev Revokes all previously granted allowances for `asset`.
/// It should be overridden by derived contracts to specify the exact contracts from which allowances are revoked.
function _revokeAllowances() internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @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 v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @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.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @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, it is bubbled up by this
* function (like regular Solidity function calls).
*
* 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.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @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`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) 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(errorMessage);
}
}
}
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity 0.8.27;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
import { IStrategyAdapterAdminable } from "interfaces/infra/multistrategy/IStrategyAdapterAdminable.sol";
import { Errors } from "src/infra/libraries/Errors.sol";
abstract contract StrategyAdapterAdminable is IStrategyAdapterAdminable, Ownable, Pausable {
/*//////////////////////////////////////////////////////////////////////////
STORAGE
//////////////////////////////////////////////////////////////////////////*/
/// @inheritdoc IStrategyAdapterAdminable
mapping(address guardianAddress => bool isActive) public guardians;
constructor(address _owner) Ownable(_owner) {}
/*//////////////////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Reverts if called by any account other than the owner, the manager, or a guardian.
modifier onlyGuardian() {
require(msg.sender == owner() || guardians[msg.sender], Errors.CallerNotGuardian(msg.sender));
_;
}
/*//////////////////////////////////////////////////////////////////////////
USER-FACING NON-CONSTANT FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @inheritdoc IStrategyAdapterAdminable
function enableGuardian(address _guardian) external onlyOwner {
guardians[_guardian] = true;
emit GuardianEnabled(_guardian);
}
/// @inheritdoc IStrategyAdapterAdminable
function revokeGuardian(address _guardian) external onlyOwner {
guardians[_guardian] = false;
emit GuardianRevoked(_guardian);
}
}
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity ^0.8.27;
interface IStrategyAdapter {
/// @notice Emitted when the slippage limit is set.
/// @param slippageLimit The new slippage limit in basis points (BPS).
event SlippageLimitSet(uint256 slippageLimit);
/// @notice Returns the address of the multistrategy this Strategy belongs to.
function multistrategy() external view returns (address);
/// @notice Returns the address of the token used tby this strategy.
/// @dev it should be the same as the token used by the multistrategy.
function asset() external view returns (address);
/// @notice Returns the identifier of this Strategy Adapter.
function id() external view returns (string memory);
/// @notice Returns the name of this Strategy Adapter.
function name() external view returns (string memory);
/// @notice Returns the current slippage limit in basis points (BPS).
/// @dev The slippage limit is expressed in BPS, where 10,000 BPS equals 100%.
/// @return The maximum allowable slippage in basis points.
function slippageLimit() external view returns (uint256);
/// @notice Sets the maximum allowable slippage limit for withdrawals.
/// @dev Slippage limit is expressed in basis points (BPS), where 10,000 BPS equals 100%.
/// This limit represents the tolerated difference between the expected withdrawal amount
/// and the actual amount withdrawn from the strategy.
/// @param _slippageLimit The maximum allowable slippage in basis points.
function setSlippageLimit(uint256 _slippageLimit) external;
/// @notice Requests a credit to the multistrategy. The multistrategy will send the
/// maximum amount of credit available for this strategy.
function requestCredit() external;
/// @notice Sends a report to the Multistrategy of any gain or loss this strategy has
/// made along an amount to be withdrawn and be used for debt repayment.
/// @dev Only the owner can call it
/// @param _amountToWithdraw Amount that will be withdrawn from the strategy and will
/// be available for debt repayment.
function sendReport(uint256 _amountToWithdraw) external;
/// @notice Sends a report to the Multistrategy of any gain or loss this strategy has made.
/// @dev This report wont withdraw any funds to repay debt to the Multistrategy.
/// Only the multistrategy can call it
function askReport() external;
/// @notice Sends a report to the Multistrategy after this strategy has been panicked.
/// Reporting any gains or loss based on the balance the could be emergency withdrawn
/// @dev This function should only be called after a strategy has been retired.
function sendReportPanicked() external;
/// @notice Withdraws `asset` from the strategy.
/// @dev Only callable by the multistrategy.
/// @param _amount Amount of tokens to withdraw from the strategy.
function withdraw(uint256 _amount) external returns (uint256);
/// @notice Returns the amount of `asset` this strategy holds.
function totalAssets() external view returns (uint256);
/// @notice Returns the gain or loss this strategy has made since the last report.
/// @dev The returned values will account for max slippage.
function currentPnL() external view returns (uint256, uint256);
/// @notice Starts the panic process for this strategy.
/// The panic process consists of:
/// - Withdraw as much funds as possible from the underlying strategy.
/// - Report back to the multistrategy with the available funds.
/// - Revoke the allowance that this adapter has given to the underlying strategy.
/// - Pauses this contract.
function panic() external;
/// @notice Pauses the smart contract.
/// @dev Functions that implement the `paused` modifier will revert when called.
/// Guardians and Owner can call this function
function pause() external;
/// @notice Unpauses the smart contract.
/// @dev Functions that implement the `paused` won't revert when called.
/// Only the Owner can call this function
function unpause() external;
}
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity ^0.8.27;
import { IMultistrategyManageable } from "interfaces/infra/multistrategy/IMultistrategyManageable.sol";
interface IMultistrategy is IMultistrategyManageable {
/// @notice Emitted when an account has made a deposit.
/// @param amount Amount of asset that has been deposited.
/// @param recipient Address that will receive the receipt tokens.
event Deposit(uint256 amount, address indexed recipient);
/// @notice Emitted when an account has made a withdraw.
/// @param amount Amount of shares that have been withdrawn.
event Withdraw(uint256 amount);
/// @notice Emitted when a strategy has requested a credit.
/// @param strategy Address of the strategy that requested the credit.
/// @param amount Amount of credit that has been granted to the strategy.
event CreditRequested(address indexed strategy, uint256 amount);
/// @notice Emitted when a strategy has submitted a report.
/// @param strategy Address of the strategy that has submitted the report.
/// @param debtRepaid Amount of debt that has been repaid by the strategy.
/// @param gain Amount of gain that the strategy has reported.
/// @param loss Amount of loss that the strategy has reported.
event StrategyReported(address indexed strategy, uint256 debtRepaid, uint256 gain, uint256 loss);
/// @notice Timestamp of the last report made by a strategy.
function lastReport() external view returns (uint256);
/// @notice Amount of tokens that are locked as "locked profit" and can't be withdrawn.
function lockedProfit() external view returns (uint256);
/// @notice Rate at which the locked profit gets unlocked per second.
function lockedProfitDegradation() external view returns (uint256);
/// @notice Returns the value of a share in `asset` value.
function pricePerShare() external view returns (uint256);
/// @notice Returns the amount of tokens a strategy can borrow from this Multistrategy.
/// @param strategy Address of the strategy we want to know the credit available for.
function creditAvailable(address strategy) external view returns (uint256);
/// @notice Returns the excess of debt a strategy currently holds.
/// @param strategy Address of the strategy we want to know if it has any debt excess.
function debtExcess(address strategy) external view returns (uint256);
/// @notice Returns the total debt of `strategy`.
/// @param strategy Address of the strategy we want to know the `totalDebt`.
function strategyTotalDebt(address strategy) external view returns (uint256);
/// @notice Returns the aggregate PnL of all strategies at max slippage.
function currentPnL() external view returns (uint256, uint256);
/// @notice Send the available credit of the caller to the caller.
/// @dev Reverts if the caller is *NOT* an active strategy
function requestCredit() external returns (uint256);
/// @notice Report the profit or loss of a strategy along any debt the strategy is willing to pay back.
/// @dev Can only be called by an active strategy.
/// @param _debtRepayment Amount that the strategy will send back to the multistrategy as debt repayment.
/// @param _gain Amount that the strategy has realized as a gain since the last report and will send it
/// to this Multistrategy as earnings.
/// @param _loss Amount that the strategy has realized as a loss since the last report.
function strategyReport(uint256 _debtRepayment, uint256 _gain, uint256 _loss) external;
/// @notice Emergency function to rescue tokens not related to the Multistrategy sent to the contract by mistake.
/// @param token Address of the token that will be rescued.
/// @param recipient Address of who will receive the tokens.
function rescueToken(address token, address recipient) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity ^0.8.27;
interface IStrategyAdapterAdminable {
/// @notice Emitted when a new guardian has been granted access.
/// @param _guardian The address of the guardian.
event GuardianEnabled(address indexed _guardian);
/// @notice Emitted when a the access of a guardian has been revoked.
/// @param _guardian The address of the guardian.
event GuardianRevoked(address indexed _guardian);
/// @notice List of addresses enabled as guardian.
/// @param _guardian The address to check if it is a guardian.
function guardians(address _guardian) external view returns (bool);
/// @notice Enables an address to be a guardian.
/// @dev Doesn't revert if:
/// - guardian address is zero address.
/// - guardian address is already enabled as guardian.
/// @param _guardian The address of the guardian.
function enableGuardian(address _guardian) external;
/// @notice Revokes an address to be a guardian.
/// @dev Doesn't revert if:
/// - guardian address is zero address.
/// - guardian address is already revoked.
/// @param _guardian The address of the guardian.
function revokeGuardian(address _guardian) external;
}
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity ^0.8.27;
import { IMultistrategyAdminable } from "interfaces/infra/multistrategy/IMultistrategyAdminable.sol";
import { MStrat } from "src/types/DataTypes.sol";
interface IMultistrategyManageable is IMultistrategyAdminable {
/// @notice Emitted when the protocol fee recipient is set.
/// @param _protocolFeeRecipient The address that will receive the protocol fee.
event ProtocolFeeRecipientSet(address indexed _protocolFeeRecipient);
/// @notice Emitted when the performance fee is set.
/// @param _performanceFee The new performance fee value.
event PerformanceFeeSet(uint256 _performanceFee);
/// @notice Emitted when the deposit limit is set.
/// @param _depositLimit The new deposit limit value.
event DepositLimitSet(uint256 _depositLimit);
/// @notice Emitted when the slippage limit is set.
/// @param _slippageLimit The new slippage limit value.
event SlippageLimitSet(uint256 _slippageLimit);
/// @notice Emitted when a new withdrawal order has been set.
event WithdrawOrderSet();
/// @notice Emitted when the debt ratio for a specific strategy is set.
/// @param _strategy The address of the strategy whose debt ratio was updated.
/// @param _debtRatio The new debt ratio value for the specified strategy.
event StrategyDebtRatioSet(address indexed _strategy, uint256 _debtRatio);
/// @notice Emitted when the minimum debt delta for a specific strategy is set.
/// @param _strategy The address of the strategy whose minimum debt delta was updated.
/// @param _minDebtDelta The new minimum debt delta value for the specified strategy.
event StrategyMinDebtDeltaSet(address indexed _strategy, uint256 _minDebtDelta);
/// @notice Emitted when the maximum debt delta for a specific strategy is set.
/// @param _strategy The address of the strategy whose maximum debt delta was updated.
/// @param _maxDebtDelta The new maximum debt delta value for the specified strategy.
event StrategyMaxDebtDeltaSet(address indexed _strategy, uint256 _maxDebtDelta);
/// @notice Emitted when a new strategy is added.
/// @param _strategy The address of the newly added strategy.
event StrategyAdded(address indexed _strategy);
/// @notice Emitted when a strategy is retired.
/// @param _strategy The address of the retired strategy.
event StrategyRetired(address indexed _strategy);
/// @notice Emitted when a strategy is removed.
/// @param _strategy The address of the removed strategy.
event StrategyRemoved(address indexed _strategy);
/// @notice Emitted when the deposits into this multistrategy are paused.
event MultistrategyRetired();
/// @notice Address that will receive performance fee.
function protocolFeeRecipient() external view returns (address);
/// @notice Fee on the yield generated (in BPS).
/// @dev Performance fee is taken on `strategyReport()` function on the Multistrategy contract.
function performanceFee() external view returns (uint256);
/// @notice Limit for total assets the multistrategy can hold.
function depositLimit() external view returns (uint256);
/// @notice Debt ratio of the multistrategy across all strategies (in BPS).
/// @dev The debt ratio cannot exceed 10_000 BPS (100 %).
function debtRatio() external view returns (uint256);
/// @notice Amount of tokens that the strategies have borrowed in total.
function totalDebt() external view returns (uint256);
/// @notice Returns the current slippage limit in basis points (BPS).
/// @dev The slippage limit is expressed in BPS, where 10,000 BPS equals 100%.
function slippageLimit() external view returns (uint256);
/// @notice Amount of active strategies.
function activeStrategies() external view returns (uint8);
/// @notice Returns true if multistrategy has been retired.
function retired() external view returns (bool);
/// @notice Returns the withdraw order.
function getWithdrawOrder() external view returns (address[] memory);
/// @notice Returns the strategy params of `strategy`
/// @param _strategy Address of the strategy the it will returns the parameters of.
function getStrategyParameters(address _strategy) external view returns (MStrat.StrategyParams calldata);
/// @notice Sets the recipient address of the performance fee.
/// @dev Emits a `SetProtocolFeeRecipient` event.
/// @param _protocolFeeRecipient Address that will receive the fees.
function setProtocolFeeRecipient(address _protocolFeeRecipient) external;
/// @notice Sets the performance fee in BPS.
/// @dev Reverts if `performanceFee` is above MAX_PERFORMANCE_FEE
/// @dev Emits a `SetPerformanceFee` event.
/// @param _performanceFee New performance fee.
function setPerformanceFee(uint256 _performanceFee) external;
/// @notice Sets the deposit limit.
/// @dev Emits a `SetDepositLimit` event.
/// @param _depositLimit New deposit limit.
function setDepositLimit(uint256 _depositLimit) external;
/// @notice Sets the slippage limit of this Multistrategy.
/// @dev The slippage limit is expressed in BPS, where 10,000 BPS equals 100%.
/// @param _slippageLimit New slippage limit.
function setSlippageLimit(uint256 _slippageLimit) external;
/// @notice Sets the withdraw order. First position in the array will be the first strategy that it will get the funds withdrawn
/// @dev It will revert if a strategy in the array is not active or if the array contains duplicate addresses.
/// @param _strategies Array of strategy addresses
function setWithdrawOrder(address[] memory _strategies) external;
/// @notice Adds a strategy to the multistrategy.
/// @dev The strategy will be appended to `withdrawOrder`.
/// @param _strategy The address of the strategy.
/// @param _debtRatio The share of total assets in the Multistrategy this strategy will have access to.
/// @param _minDebtDelta Lower limit on the increase of debt.
/// @param _maxDebtDelta Upper limit on the increase of debt.
function addStrategy(
address _strategy,
uint256 _debtRatio,
uint256 _minDebtDelta,
uint256 _maxDebtDelta
) external;
/// @notice Sets the strategy debtRatio to 0, which prevents any further deposits into the strategy.
/// @dev Retiring a strategy will set the approval of `asset` to the retired strategy to 0.
/// @param _strategy The address of the strategy that will be retired.
function retireStrategy(address _strategy) external;
/// @notice Removes a strategy from `withdrawOrder`.
/// @param _strategy The address of the strategy that will be removed.
function removeStrategy(address _strategy) external;
/// @notice Change the debt ratio of a strategy.
/// @param _strategy Address of the strategy.
/// @param _debtRatio New debt ratio.
function setStrategyDebtRatio(address _strategy, uint256 _debtRatio) external;
/// @notice Change the minimum amount of debt a strategy can take.
/// @dev Used to limit the minimum amount of debt a strategy should take.
/// Taking a small credit wouldn't be optimal gas-wise.
/// @param _strategy Address of the strategy.
/// @param _minDebtDelta Lower limit of the change of debt.
function setStrategyMinDebtDelta(address _strategy, uint256 _minDebtDelta) external;
/// @notice Change the maximum amount of debt a strategy can take at once.
/// @dev Used to protect large debt repayments or withdraws. Risks are IL, or low liquidity.
/// @param _strategy Address of the strategy.
/// @param _maxDebtDelta Upper limit of the change of debt.
function setStrategyMaxDebtDelta(address _strategy, uint256 _maxDebtDelta) external;
/// @notice Retires the Multistrategy. End of Life.
function retire() external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity ^0.8.27;
/// @title IMultistrategyAdminable
/// @notice Contract module that provides a 3 level access control mechanism, with an owner, a manager
/// and a list of guardians that can be granted exclusive access to specific functions.
/// The inheriting contract must set the initial owner and the initial manager in the constructor.
interface IMultistrategyAdminable {
/*//////////////////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Emitted when a new manager is set.
/// @param _manager The address of the new manager.
event ManagerSet(address indexed _manager);
/// @notice Emitted when a new guardian has been granted access.
/// @param _guardian The address of the guardian.
event GuardianEnabled(address indexed _guardian);
/// @notice Emitted when a the access of a guardian has been revoked.
/// @param _guardian The address of the guardian.
event GuardianRevoked(address indexed _guardian);
/*//////////////////////////////////////////////////////////////////////////
CONSTANT FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice The address of the manager.
function manager() external view returns (address);
/// @notice List of addresses enabled as guardian.
/// @param _guardian The address to check if it is a guardian.
function guardians(address _guardian) external view returns (bool);
/*//////////////////////////////////////////////////////////////////////////
NON-CONSTANT FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Sets the manager address.
/// @dev Doesn't revert if:
/// - manager address is zero address.
/// - manager address is the same as previous manager address.
/// @param _manager Address of the new manager.
function setManager(address _manager) external;
/// @notice Enables an address to be a guardian.
/// @dev Doesn't revert if:
/// - guardian address is zero address.
/// - guardian address is already enabled as guardian.
/// @param _guardian The address of the guardian.
function enableGuardian(address _guardian) external;
/// @notice Revokes an address to be a guardian.
/// @dev Doesn't revert if:
/// - guardian address is zero address.
/// - guardian address is already revoked.
/// @param _guardian The address of the guardian.
function revokeGuardian(address _guardian) external;
/// @notice Pauses the smart contract.
/// @dev Functions that implement the `paused` modifier will revert when called.
/// Guardians, Manager and Owner can call this function
function pause() external;
/// @notice Unpauses the smart contract.
/// @dev Functions that implement the `paused` won't revert when called.
/// Guardians, Manager and Owner can call this function
function unpause() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.20;
/// @notice Namespace for the structs used in `Multistrategy`
library MStrat {
/// @notice Struct that contains a strategy data
/// @param activation Block.timestamp of when the strategy was activated. 0 means not active
/// @param debtRatio Maximum amount the strategy can borrow from the Multistrategy (in BPS of total assets in a Multistrategy)
/// @param lastReport
/// @param minDebtDelta Lower limit on the increase or decrease of debt since last harvest
/// @param maxDebtDelta Upper limit on the increase or decrease of debt since last harvest
/// @param totalDebt Total debt that this strategy has
/// @param totalGain Total gains that this strategy has realized
/// @param totalLoss Total losses that this strategy has realized
struct StrategyParams {
uint256 activation;
uint256 debtRatio;
uint256 lastReport;
uint256 minDebtDelta;
uint256 maxDebtDelta;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
}